blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
fcc2543c326147f53bf9e94b6ed9529830719d7b | [
"w = base_size\nh = base_size\nif center is None:\n x_center = self.center_offset * w\n y_center = self.center_offset * h\nelse:\n x_center, y_center = center\nh_ratios = torch.sqrt(ratios)\nw_ratios = 1 / h_ratios\nif self.scale_major:\n ws = (w * scales[:, None] * w_ratios[None, :]).view(-1)\n hs =... | <|body_start_0|>
w = base_size
h = base_size
if center is None:
x_center = self.center_offset * w
y_center = self.center_offset * h
else:
x_center, y_center = center
h_ratios = torch.sqrt(ratios)
w_ratios = 1 / h_ratios
if self.... | YXYXAnchorGenerator | [
"GPL-1.0-or-later",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class YXYXAnchorGenerator:
def gen_single_level_base_anchors(self, base_size: Union[int, float], scales: Tensor, ratios: Tensor, center: Optional[Tuple[float]]=None) -> Tensor:
"""Generate base anchors of a single level. Args: base_size (int | float): Basic size of an anchor. scales (torch.Ten... | stack_v2_sparse_classes_75kplus_train_005100 | 4,261 | permissive | [
{
"docstring": "Generate base anchors of a single level. Args: base_size (int | float): Basic size of an anchor. scales (torch.Tensor): Scales of the anchor. ratios (torch.Tensor): The ratio between the height and width of anchors in a single level. center (tuple[float], optional): The center of the base anchor... | 2 | stack_v2_sparse_classes_30k_train_007354 | Implement the Python class `YXYXAnchorGenerator` described below.
Class description:
Implement the YXYXAnchorGenerator class.
Method signatures and docstrings:
- def gen_single_level_base_anchors(self, base_size: Union[int, float], scales: Tensor, ratios: Tensor, center: Optional[Tuple[float]]=None) -> Tensor: Genera... | Implement the Python class `YXYXAnchorGenerator` described below.
Class description:
Implement the YXYXAnchorGenerator class.
Method signatures and docstrings:
- def gen_single_level_base_anchors(self, base_size: Union[int, float], scales: Tensor, ratios: Tensor, center: Optional[Tuple[float]]=None) -> Tensor: Genera... | 8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6 | <|skeleton|>
class YXYXAnchorGenerator:
def gen_single_level_base_anchors(self, base_size: Union[int, float], scales: Tensor, ratios: Tensor, center: Optional[Tuple[float]]=None) -> Tensor:
"""Generate base anchors of a single level. Args: base_size (int | float): Basic size of an anchor. scales (torch.Ten... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class YXYXAnchorGenerator:
def gen_single_level_base_anchors(self, base_size: Union[int, float], scales: Tensor, ratios: Tensor, center: Optional[Tuple[float]]=None) -> Tensor:
"""Generate base anchors of a single level. Args: base_size (int | float): Basic size of an anchor. scales (torch.Tensor): Scales o... | the_stack_v2_python_sparse | ai/mmdetection/projects/EfficientDet/efficientdet/anchor_generator.py | alldatacenter/alldata | train | 774 | |
f1ef18f59cf030dc6201626f4b2a99d34a8e94e0 | [
"self.row_i = row_i\nself.start_i = start_i\nself.end_i = end_i\nself.n = n\nself.gap = None\nself.min_h = int(n * frac_h)",
"g = self.gap\nif g is not None:\n return g[1] - g[0] < f - s\nelse:\n return True",
"g = self.gap\nif g is None:\n self.gap = (s, f)\nelif f - s > g[1] - g[0]:\n self.gap = (... | <|body_start_0|>
self.row_i = row_i
self.start_i = start_i
self.end_i = end_i
self.n = n
self.gap = None
self.min_h = int(n * frac_h)
<|end_body_0|>
<|body_start_1|>
g = self.gap
if g is not None:
return g[1] - g[0] < f - s
else:
... | Private Object that will keep track of current row data. | __GapData | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class __GapData:
"""Private Object that will keep track of current row data."""
def __init__(self, row_i, start_i, end_i, n, frac_h):
"""Intitalize Camera object with following optional parameters: row_i Number of frames to average over start_i Ratio of bottom part of image to keep end_i R... | stack_v2_sparse_classes_75kplus_train_005101 | 3,049 | permissive | [
{
"docstring": "Intitalize Camera object with following optional parameters: row_i Number of frames to average over start_i Ratio of bottom part of image to keep end_i Rescale image by sub_sample n Upper values to keep in depth image",
"name": "__init__",
"signature": "def __init__(self, row_i, start_i,... | 3 | stack_v2_sparse_classes_30k_train_029328 | Implement the Python class `__GapData` described below.
Class description:
Private Object that will keep track of current row data.
Method signatures and docstrings:
- def __init__(self, row_i, start_i, end_i, n, frac_h): Intitalize Camera object with following optional parameters: row_i Number of frames to average o... | Implement the Python class `__GapData` described below.
Class description:
Private Object that will keep track of current row data.
Method signatures and docstrings:
- def __init__(self, row_i, start_i, end_i, n, frac_h): Intitalize Camera object with following optional parameters: row_i Number of frames to average o... | cc436ee5e52e66947bd932f4670acc701a6bbda0 | <|skeleton|>
class __GapData:
"""Private Object that will keep track of current row data."""
def __init__(self, row_i, start_i, end_i, n, frac_h):
"""Intitalize Camera object with following optional parameters: row_i Number of frames to average over start_i Ratio of bottom part of image to keep end_i R... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class __GapData:
"""Private Object that will keep track of current row data."""
def __init__(self, row_i, start_i, end_i, n, frac_h):
"""Intitalize Camera object with following optional parameters: row_i Number of frames to average over start_i Ratio of bottom part of image to keep end_i Rescale image ... | the_stack_v2_python_sparse | main/navigation/obstacle_avoid.py | IntelligentQuadruped/Implementation | train | 2 |
06c04b422eee36009c6b9c7c408104f89dca00b3 | [
"changed = False\nif options.delay is not None and 0 <= options.delay != self.delay:\n self.delay = options.delay\n changed = True\nif options.bandwidth is not None and 0 <= options.bandwidth != self.bandwidth:\n self.bandwidth = options.bandwidth\n changed = True\nif options.loss is not None and 0 <= o... | <|body_start_0|>
changed = False
if options.delay is not None and 0 <= options.delay != self.delay:
self.delay = options.delay
changed = True
if options.bandwidth is not None and 0 <= options.bandwidth != self.bandwidth:
self.bandwidth = options.bandwidth
... | Options for creating and updating links within core. | LinkOptions | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinkOptions:
"""Options for creating and updating links within core."""
def update(self, options: 'LinkOptions') -> bool:
"""Updates current options with values from other options. :param options: options to update with :return: True if any value has changed, False otherwise"""
... | stack_v2_sparse_classes_75kplus_train_005102 | 9,883 | permissive | [
{
"docstring": "Updates current options with values from other options. :param options: options to update with :return: True if any value has changed, False otherwise",
"name": "update",
"signature": "def update(self, options: 'LinkOptions') -> bool"
},
{
"docstring": "Checks if the current opti... | 3 | stack_v2_sparse_classes_30k_train_043903 | Implement the Python class `LinkOptions` described below.
Class description:
Options for creating and updating links within core.
Method signatures and docstrings:
- def update(self, options: 'LinkOptions') -> bool: Updates current options with values from other options. :param options: options to update with :return... | Implement the Python class `LinkOptions` described below.
Class description:
Options for creating and updating links within core.
Method signatures and docstrings:
- def update(self, options: 'LinkOptions') -> bool: Updates current options with values from other options. :param options: options to update with :return... | 20071eed2e73a2287aa385698dd604f4933ae7ff | <|skeleton|>
class LinkOptions:
"""Options for creating and updating links within core."""
def update(self, options: 'LinkOptions') -> bool:
"""Updates current options with values from other options. :param options: options to update with :return: True if any value has changed, False otherwise"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LinkOptions:
"""Options for creating and updating links within core."""
def update(self, options: 'LinkOptions') -> bool:
"""Updates current options with values from other options. :param options: options to update with :return: True if any value has changed, False otherwise"""
changed = ... | the_stack_v2_python_sparse | daemon/core/emulator/data.py | coreemu/core | train | 606 |
c6c4fb0366e5424cf570ac351b0e66719888a3cf | [
"sql = u'select cl.company_line_name, bs1.bus_station_name as up_station_name,bs2.bus_station_name as off_station_name from student_line_seat ls join info_company_line cl on ls.up_company_line_id = cl.company_line_id join info_bus_station bs1 on bs1.bus_station_id = ls.up_station_id join info_bus_station bs2 on bs2... | <|body_start_0|>
sql = u'select cl.company_line_name, bs1.bus_station_name as up_station_name,bs2.bus_station_name as off_station_name from student_line_seat ls join info_company_line cl on ls.up_company_line_id = cl.company_line_id join info_bus_station bs1 on bs1.bus_station_id = ls.up_station_id join info_bu... | StudentLineSeat | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StudentLineSeat:
def get_one_bus_station(self, login_user_id):
"""查询站点(家长) :param login_user_id: :return:"""
<|body_0|>
def get_all_bus_station(self, login_user_id):
"""获取站点列表(家长) :param login_user_id: :return:"""
<|body_1|>
def get_student_id(self, logi... | stack_v2_sparse_classes_75kplus_train_005103 | 5,237 | no_license | [
{
"docstring": "查询站点(家长) :param login_user_id: :return:",
"name": "get_one_bus_station",
"signature": "def get_one_bus_station(self, login_user_id)"
},
{
"docstring": "获取站点列表(家长) :param login_user_id: :return:",
"name": "get_all_bus_station",
"signature": "def get_all_bus_station(self, l... | 6 | stack_v2_sparse_classes_30k_train_049715 | Implement the Python class `StudentLineSeat` described below.
Class description:
Implement the StudentLineSeat class.
Method signatures and docstrings:
- def get_one_bus_station(self, login_user_id): 查询站点(家长) :param login_user_id: :return:
- def get_all_bus_station(self, login_user_id): 获取站点列表(家长) :param login_user_i... | Implement the Python class `StudentLineSeat` described below.
Class description:
Implement the StudentLineSeat class.
Method signatures and docstrings:
- def get_one_bus_station(self, login_user_id): 查询站点(家长) :param login_user_id: :return:
- def get_all_bus_station(self, login_user_id): 获取站点列表(家长) :param login_user_i... | a7cf5a0b6daa372ed860dc43d92c55fcde764eb9 | <|skeleton|>
class StudentLineSeat:
def get_one_bus_station(self, login_user_id):
"""查询站点(家长) :param login_user_id: :return:"""
<|body_0|>
def get_all_bus_station(self, login_user_id):
"""获取站点列表(家长) :param login_user_id: :return:"""
<|body_1|>
def get_student_id(self, logi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StudentLineSeat:
def get_one_bus_station(self, login_user_id):
"""查询站点(家长) :param login_user_id: :return:"""
sql = u'select cl.company_line_name, bs1.bus_station_name as up_station_name,bs2.bus_station_name as off_station_name from student_line_seat ls join info_company_line cl on ls.up_compan... | the_stack_v2_python_sparse | python_project/smart_schoolBus_project/app/schoolbus_situation/models/student_line_seat_model.py | malqch/aibus | train | 0 | |
3a391091e6dc7f4b366b9f62d3c03c5da0bb8bb5 | [
"path = urls.WIDS['GET_CLIENT_ATTACKS']\nparams = {'limit': limit, 'offset': offset, 'sort': sort, 'calculate_total': calculate_total}\nif group:\n params['group'] = group\nif label:\n params['label'] = label\nif site:\n params['site'] = site\nif swarm_id:\n params['swarm_id'] = swarm_id\nif start:\n ... | <|body_start_0|>
path = urls.WIDS['GET_CLIENT_ATTACKS']
params = {'limit': limit, 'offset': offset, 'sort': sort, 'calculate_total': calculate_total}
if group:
params['group'] = group
if label:
params['label'] = label
if site:
params['site'] = ... | A Python Class to obtain Aruba Central's Wireless Intrusion Detection details based on REST APIs. | WIDS | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WIDS:
"""A Python Class to obtain Aruba Central's Wireless Intrusion Detection details based on REST APIs."""
def list_client_attacks(self, conn, group=None, label=None, site=None, swarm_id=None, start=None, end=None, from_timestamp=None, to_timestamp=None, limit=100, calculate_total=True, s... | stack_v2_sparse_classes_75kplus_train_005104 | 22,300 | permissive | [
{
"docstring": "Get client attacks over a time period :param conn: Instance of class:`pycentral.ArubaCentralBase` to make an API call. :type conn: class:`pycentral.ArubaCentralBase` :param group: List of group names, defaults to None :type group: list, optional :param label: List of label names, defaults to Non... | 3 | stack_v2_sparse_classes_30k_train_051428 | Implement the Python class `WIDS` described below.
Class description:
A Python Class to obtain Aruba Central's Wireless Intrusion Detection details based on REST APIs.
Method signatures and docstrings:
- def list_client_attacks(self, conn, group=None, label=None, site=None, swarm_id=None, start=None, end=None, from_t... | Implement the Python class `WIDS` described below.
Class description:
A Python Class to obtain Aruba Central's Wireless Intrusion Detection details based on REST APIs.
Method signatures and docstrings:
- def list_client_attacks(self, conn, group=None, label=None, site=None, swarm_id=None, start=None, end=None, from_t... | d938396a18193473afbe54e6cc6697d2bd4954a7 | <|skeleton|>
class WIDS:
"""A Python Class to obtain Aruba Central's Wireless Intrusion Detection details based on REST APIs."""
def list_client_attacks(self, conn, group=None, label=None, site=None, swarm_id=None, start=None, end=None, from_timestamp=None, to_timestamp=None, limit=100, calculate_total=True, s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WIDS:
"""A Python Class to obtain Aruba Central's Wireless Intrusion Detection details based on REST APIs."""
def list_client_attacks(self, conn, group=None, label=None, site=None, swarm_id=None, start=None, end=None, from_timestamp=None, to_timestamp=None, limit=100, calculate_total=True, sort='-ts', of... | the_stack_v2_python_sparse | pycentral/rapids.py | jayp193/pycentral | train | 0 |
0f9da1ab15d2483bf7758884f7b68b1d4e70f75e | [
"self.name = name\nself.dataType = dataType\nself.verbose = verbose\nself.Ueast = self.__loadDspMaps__(eastFiles)\nself.Unorth = self.__loadDspMaps__(northFiles)\nself.Uup = self.__loadDspMaps__(upFiles)\nself.Nepochs = len(eastFiles)\nself.__estbSpatialExtent__(eastFiles[0])",
"dspMaps = []\nfor filename in file... | <|body_start_0|>
self.name = name
self.dataType = dataType
self.verbose = verbose
self.Ueast = self.__loadDspMaps__(eastFiles)
self.Unorth = self.__loadDspMaps__(northFiles)
self.Uup = self.__loadDspMaps__(upFiles)
self.Nepochs = len(eastFiles)
self.__estb... | displacementDataset | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class displacementDataset:
def __init__(self, name, eastFiles, northFiles, upFiles, dataType='cumulative', verbose=False):
"""Initialize."""
<|body_0|>
def __loadDspMaps__(self, filenames):
"""Load grd data using gdal."""
<|body_1|>
def __estbSpatialExtent__(s... | stack_v2_sparse_classes_75kplus_train_005105 | 10,004 | no_license | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self, name, eastFiles, northFiles, upFiles, dataType='cumulative', verbose=False)"
},
{
"docstring": "Load grd data using gdal.",
"name": "__loadDspMaps__",
"signature": "def __loadDspMaps__(self, filenames)"
... | 6 | stack_v2_sparse_classes_30k_test_000355 | Implement the Python class `displacementDataset` described below.
Class description:
Implement the displacementDataset class.
Method signatures and docstrings:
- def __init__(self, name, eastFiles, northFiles, upFiles, dataType='cumulative', verbose=False): Initialize.
- def __loadDspMaps__(self, filenames): Load grd... | Implement the Python class `displacementDataset` described below.
Class description:
Implement the displacementDataset class.
Method signatures and docstrings:
- def __init__(self, name, eastFiles, northFiles, upFiles, dataType='cumulative', verbose=False): Initialize.
- def __loadDspMaps__(self, filenames): Load grd... | ae5a5be3679975f2bf95166d1fee24171eef7dc1 | <|skeleton|>
class displacementDataset:
def __init__(self, name, eastFiles, northFiles, upFiles, dataType='cumulative', verbose=False):
"""Initialize."""
<|body_0|>
def __loadDspMaps__(self, filenames):
"""Load grd data using gdal."""
<|body_1|>
def __estbSpatialExtent__(s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class displacementDataset:
def __init__(self, name, eastFiles, northFiles, upFiles, dataType='cumulative', verbose=False):
"""Initialize."""
self.name = name
self.dataType = dataType
self.verbose = verbose
self.Ueast = self.__loadDspMaps__(eastFiles)
self.Unorth = sel... | the_stack_v2_python_sparse | RelaxAnalysis/showRelax.py | wuxyair/InsarToolkit | train | 0 | |
5a22377024926bb3632b4f0c81c3320d1c0b3639 | [
"super(LogicalSwitchListSchema, self).__init__()\nself.table = [LogicalSwitchEntrySchema()]\nif py_dict is not None:\n self.get_object_from_py_dict(py_dict)",
"payload = self._parser.get_parsed_data(raw_payload)\npy_dict = {'table': payload}\nreturn self.get_object_from_py_dict(py_dict)"
] | <|body_start_0|>
super(LogicalSwitchListSchema, self).__init__()
self.table = [LogicalSwitchEntrySchema()]
if py_dict is not None:
self.get_object_from_py_dict(py_dict)
<|end_body_0|>
<|body_start_1|>
payload = self._parser.get_parsed_data(raw_payload)
py_dict = {'ta... | LogicalSwitchListSchema | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogicalSwitchListSchema:
def __init__(self, py_dict=None):
"""Constructor to create LogicalSwitchListSchema object"""
<|body_0|>
def set_data_raw(self, raw_payload):
"""Convert raw data to py_dict based on the class parser and assign the py_dict to class element so t... | stack_v2_sparse_classes_75kplus_train_005106 | 1,832 | no_license | [
{
"docstring": "Constructor to create LogicalSwitchListSchema object",
"name": "__init__",
"signature": "def __init__(self, py_dict=None)"
},
{
"docstring": "Convert raw data to py_dict based on the class parser and assign the py_dict to class element so that get_object_from_py_dict() can take i... | 2 | stack_v2_sparse_classes_30k_train_011770 | Implement the Python class `LogicalSwitchListSchema` described below.
Class description:
Implement the LogicalSwitchListSchema class.
Method signatures and docstrings:
- def __init__(self, py_dict=None): Constructor to create LogicalSwitchListSchema object
- def set_data_raw(self, raw_payload): Convert raw data to py... | Implement the Python class `LogicalSwitchListSchema` described below.
Class description:
Implement the LogicalSwitchListSchema class.
Method signatures and docstrings:
- def __init__(self, py_dict=None): Constructor to create LogicalSwitchListSchema object
- def set_data_raw(self, raw_payload): Convert raw data to py... | 5b55817c050b637e2747084290f6206d2e622938 | <|skeleton|>
class LogicalSwitchListSchema:
def __init__(self, py_dict=None):
"""Constructor to create LogicalSwitchListSchema object"""
<|body_0|>
def set_data_raw(self, raw_payload):
"""Convert raw data to py_dict based on the class parser and assign the py_dict to class element so t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LogicalSwitchListSchema:
def __init__(self, py_dict=None):
"""Constructor to create LogicalSwitchListSchema object"""
super(LogicalSwitchListSchema, self).__init__()
self.table = [LogicalSwitchEntrySchema()]
if py_dict is not None:
self.get_object_from_py_dict(py_di... | the_stack_v2_python_sparse | SystemTesting/pylib/nsx/vsm/centralized_cli/schema/logicalswitch_list_schema.py | Cloudxtreme/MyProject | train | 0 | |
7b9b802e055e68ea0051f191fbd2929a260be32d | [
"n = len(nums)\nans = []\nfor i in range(n):\n if nums[i] == target:\n ans.append(i)\n break\nfor i in range(n - 1, -1, -1):\n if nums[i] == target:\n ans.append(i)\n break\nif not ans:\n ans.extend([-1, -1])\nreturn ans",
"size = len(nums)\nif size == 0:\n return [-1, -1]\... | <|body_start_0|>
n = len(nums)
ans = []
for i in range(n):
if nums[i] == target:
ans.append(i)
break
for i in range(n - 1, -1, -1):
if nums[i] == target:
ans.append(i)
break
if not ans:
... | OfficialSolution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OfficialSolution:
def search_range(self, nums: List[int], target: int) -> List[int]:
"""线性扫描。"""
<|body_0|>
def search_range_2(self, nums: List[int], target: int) -> List[int]:
"""二分查找。"""
<|body_1|>
def __find_first_position(self, nums: List[int], size,... | stack_v2_sparse_classes_75kplus_train_005107 | 4,200 | no_license | [
{
"docstring": "线性扫描。",
"name": "search_range",
"signature": "def search_range(self, nums: List[int], target: int) -> List[int]"
},
{
"docstring": "二分查找。",
"name": "search_range_2",
"signature": "def search_range_2(self, nums: List[int], target: int) -> List[int]"
},
{
"docstring... | 4 | stack_v2_sparse_classes_30k_val_001334 | Implement the Python class `OfficialSolution` described below.
Class description:
Implement the OfficialSolution class.
Method signatures and docstrings:
- def search_range(self, nums: List[int], target: int) -> List[int]: 线性扫描。
- def search_range_2(self, nums: List[int], target: int) -> List[int]: 二分查找。
- def __find... | Implement the Python class `OfficialSolution` described below.
Class description:
Implement the OfficialSolution class.
Method signatures and docstrings:
- def search_range(self, nums: List[int], target: int) -> List[int]: 线性扫描。
- def search_range_2(self, nums: List[int], target: int) -> List[int]: 二分查找。
- def __find... | 6932d69353b94ec824dd0ddc86a92453f6673232 | <|skeleton|>
class OfficialSolution:
def search_range(self, nums: List[int], target: int) -> List[int]:
"""线性扫描。"""
<|body_0|>
def search_range_2(self, nums: List[int], target: int) -> List[int]:
"""二分查找。"""
<|body_1|>
def __find_first_position(self, nums: List[int], size,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OfficialSolution:
def search_range(self, nums: List[int], target: int) -> List[int]:
"""线性扫描。"""
n = len(nums)
ans = []
for i in range(n):
if nums[i] == target:
ans.append(i)
break
for i in range(n - 1, -1, -1):
if... | the_stack_v2_python_sparse | 0034_find-first-and-last-position-of-element-in-sorted-array.py | Nigirimeshi/leetcode | train | 0 | |
13ac392692ff7ef0c671e10d234b2b83f0418211 | [
"if _env not in os.environ:\n raise ValueError('Environment variable %s not exists' % _env)\nreturn self.FromFile(os.environ[_env])",
"config_context = {}\nexec(compile(open(_path, 'rt').read(), os.path.basename(_path), 'exec'), config_context)\nreturn self.FromDict(config_context)",
"for ident, cfg_ident, v... | <|body_start_0|>
if _env not in os.environ:
raise ValueError('Environment variable %s not exists' % _env)
return self.FromFile(os.environ[_env])
<|end_body_0|>
<|body_start_1|>
config_context = {}
exec(compile(open(_path, 'rt').read(), os.path.basename(_path), 'exec'), confi... | CheckBotConfig | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CheckBotConfig:
def FromEnv(self, _env):
"""Load configures from file whose path is specified by Environment Variable _env. :params: _env Environment variable name."""
<|body_0|>
def FromFile(self, _path):
"""Load configures from file. :params: _path File path."""
... | stack_v2_sparse_classes_75kplus_train_005108 | 1,786 | no_license | [
{
"docstring": "Load configures from file whose path is specified by Environment Variable _env. :params: _env Environment variable name.",
"name": "FromEnv",
"signature": "def FromEnv(self, _env)"
},
{
"docstring": "Load configures from file. :params: _path File path.",
"name": "FromFile",
... | 3 | stack_v2_sparse_classes_30k_val_002467 | Implement the Python class `CheckBotConfig` described below.
Class description:
Implement the CheckBotConfig class.
Method signatures and docstrings:
- def FromEnv(self, _env): Load configures from file whose path is specified by Environment Variable _env. :params: _env Environment variable name.
- def FromFile(self,... | Implement the Python class `CheckBotConfig` described below.
Class description:
Implement the CheckBotConfig class.
Method signatures and docstrings:
- def FromEnv(self, _env): Load configures from file whose path is specified by Environment Variable _env. :params: _env Environment variable name.
- def FromFile(self,... | 4402e890eaf02e57b57ad04596490e0e8759a814 | <|skeleton|>
class CheckBotConfig:
def FromEnv(self, _env):
"""Load configures from file whose path is specified by Environment Variable _env. :params: _env Environment variable name."""
<|body_0|>
def FromFile(self, _path):
"""Load configures from file. :params: _path File path."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CheckBotConfig:
def FromEnv(self, _env):
"""Load configures from file whose path is specified by Environment Variable _env. :params: _env Environment variable name."""
if _env not in os.environ:
raise ValueError('Environment variable %s not exists' % _env)
return self.FromF... | the_stack_v2_python_sparse | CheckBot/config.py | StarStudio/StarSSO | train | 1 | |
e557fd25820b0cee50b89fc86ef2d068f1342ee5 | [
"super(Model.MetadataNet, self).__init__()\nself.l1 = nn.Linear(7, 8)\nself.l2 = nn.Linear(8, 16)\nself.l3 = nn.Linear(16, 32)\nself.l4 = nn.Linear(32, 32)\nself.l5 = nn.Linear(32, 64)\nself.activation = F.relu",
"x = self.activation(self.l1(x))\nx = self.activation(self.l2(x))\nx = self.activation(self.l3(x))\nx... | <|body_start_0|>
super(Model.MetadataNet, self).__init__()
self.l1 = nn.Linear(7, 8)
self.l2 = nn.Linear(8, 16)
self.l3 = nn.Linear(16, 32)
self.l4 = nn.Linear(32, 32)
self.l5 = nn.Linear(32, 64)
self.activation = F.relu
<|end_body_0|>
<|body_start_1|>
x ... | A simple feed-forward network for metadata. | MetadataNet | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MetadataNet:
"""A simple feed-forward network for metadata."""
def __init__(self):
"""Initializes Metadata Net as a 5-layer deep network."""
<|body_0|>
def forward(self, x):
"""Feeds some metadata through the network. Args: x: A minibatch of metadata. Returns: An... | stack_v2_sparse_classes_75kplus_train_005109 | 4,723 | permissive | [
{
"docstring": "Initializes Metadata Net as a 5-layer deep network.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Feeds some metadata through the network. Args: x: A minibatch of metadata. Returns: An encoding of the metadata to feed into APOGEE Net.",
"name": "f... | 2 | null | Implement the Python class `MetadataNet` described below.
Class description:
A simple feed-forward network for metadata.
Method signatures and docstrings:
- def __init__(self): Initializes Metadata Net as a 5-layer deep network.
- def forward(self, x): Feeds some metadata through the network. Args: x: A minibatch of ... | Implement the Python class `MetadataNet` described below.
Class description:
A simple feed-forward network for metadata.
Method signatures and docstrings:
- def __init__(self): Initializes Metadata Net as a 5-layer deep network.
- def forward(self, x): Feeds some metadata through the network. Args: x: A minibatch of ... | 3efe111c80d95b46e2f07288e98e6ee10cbcac9b | <|skeleton|>
class MetadataNet:
"""A simple feed-forward network for metadata."""
def __init__(self):
"""Initializes Metadata Net as a 5-layer deep network."""
<|body_0|>
def forward(self, x):
"""Feeds some metadata through the network. Args: x: A minibatch of metadata. Returns: An... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MetadataNet:
"""A simple feed-forward network for metadata."""
def __init__(self):
"""Initializes Metadata Net as a 5-layer deep network."""
super(Model.MetadataNet, self).__init__()
self.l1 = nn.Linear(7, 8)
self.l2 = nn.Linear(8, 16)
self.l3 = nn.Linear(16, 32)
... | the_stack_v2_python_sparse | python/astra/contrib/apogeenet/model.py | sdss/astra | train | 8 |
59e9d2098a55239da7e837e119d1dcbcc24de6d8 | [
"mpcpy_ts_list = self._make_mpcpy_ts_list(measurement_key)\ndf = self._mpcpy_ts_list_to_dataframe(mpcpy_ts_list, display_data=True)\nreturn df",
"mpcpy_ts_list = self._make_mpcpy_ts_list(measurement_key)\ndf = self._mpcpy_ts_list_to_dataframe(mpcpy_ts_list, display_data=False)\nreturn df",
"mpcpy_ts_list = []\n... | <|body_start_0|>
mpcpy_ts_list = self._make_mpcpy_ts_list(measurement_key)
df = self._mpcpy_ts_list_to_dataframe(mpcpy_ts_list, display_data=True)
return df
<|end_body_0|>
<|body_start_1|>
mpcpy_ts_list = self._make_mpcpy_ts_list(measurement_key)
df = self._mpcpy_ts_list_to_data... | Mixin class to handle operations on measurement dictionaries. Concrete class requires _mpcpyPandas methods. | _Measurements | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _Measurements:
"""Mixin class to handle operations on measurement dictionaries. Concrete class requires _mpcpyPandas methods."""
def display_measurements(self, measurement_key):
"""Get measurements data in display units as pandas dataframe. Parameters ---------- measurement_key : str... | stack_v2_sparse_classes_75kplus_train_005110 | 36,882 | permissive | [
{
"docstring": "Get measurements data in display units as pandas dataframe. Parameters ---------- measurement_key : string The measurement dictionary key for which to get the data for all of the variables. Returns ------- df : ``pandas`` dataframe Timeseries dataframe in display units containing data for all me... | 3 | stack_v2_sparse_classes_30k_test_000196 | Implement the Python class `_Measurements` described below.
Class description:
Mixin class to handle operations on measurement dictionaries. Concrete class requires _mpcpyPandas methods.
Method signatures and docstrings:
- def display_measurements(self, measurement_key): Get measurements data in display units as pand... | Implement the Python class `_Measurements` described below.
Class description:
Mixin class to handle operations on measurement dictionaries. Concrete class requires _mpcpyPandas methods.
Method signatures and docstrings:
- def display_measurements(self, measurement_key): Get measurements data in display units as pand... | 63d2fc77a53ea17800834f8000013616d7eab9c9 | <|skeleton|>
class _Measurements:
"""Mixin class to handle operations on measurement dictionaries. Concrete class requires _mpcpyPandas methods."""
def display_measurements(self, measurement_key):
"""Get measurements data in display units as pandas dataframe. Parameters ---------- measurement_key : str... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _Measurements:
"""Mixin class to handle operations on measurement dictionaries. Concrete class requires _mpcpyPandas methods."""
def display_measurements(self, measurement_key):
"""Get measurements data in display units as pandas dataframe. Parameters ---------- measurement_key : string The measu... | the_stack_v2_python_sparse | mpcpy_mods/utility_mod.py | niujide/CommunityDRSims | train | 0 |
34f6c0aab7b59ff12b6bac73b52d833cbd02d554 | [
"for rec in self:\n if rec.product_id:\n res = self.env['product.product'].search([('id', '=', rec.product_id.id)])._compute_quantities_dict(self._context.get('lot_id'), self._context.get('owner_id'), self._context.get('package_id'), self._context.get('from_date'), self._context.get('to_date'))\n i... | <|body_start_0|>
for rec in self:
if rec.product_id:
res = self.env['product.product'].search([('id', '=', rec.product_id.id)])._compute_quantities_dict(self._context.get('lot_id'), self._context.get('owner_id'), self._context.get('package_id'), self._context.get('from_date'), self._... | AddItemWizard | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddItemWizard:
def _compute_qty(self):
"""This function compute on hand quantity and forcasted quantity of product."""
<|body_0|>
def _compute_product_qty_to_sell(self):
"""Returns the available products to Sell."""
<|body_1|>
def prepare_move_dict(self,... | stack_v2_sparse_classes_75kplus_train_005111 | 8,376 | permissive | [
{
"docstring": "This function compute on hand quantity and forcasted quantity of product.",
"name": "_compute_qty",
"signature": "def _compute_qty(self)"
},
{
"docstring": "Returns the available products to Sell.",
"name": "_compute_product_qty_to_sell",
"signature": "def _compute_produc... | 4 | stack_v2_sparse_classes_30k_test_002117 | Implement the Python class `AddItemWizard` described below.
Class description:
Implement the AddItemWizard class.
Method signatures and docstrings:
- def _compute_qty(self): This function compute on hand quantity and forcasted quantity of product.
- def _compute_product_qty_to_sell(self): Returns the available produc... | Implement the Python class `AddItemWizard` described below.
Class description:
Implement the AddItemWizard class.
Method signatures and docstrings:
- def _compute_qty(self): This function compute on hand quantity and forcasted quantity of product.
- def _compute_product_qty_to_sell(self): Returns the available produc... | a4b796fc8a9d291ff1b4c93e53e27f566947adf2 | <|skeleton|>
class AddItemWizard:
def _compute_qty(self):
"""This function compute on hand quantity and forcasted quantity of product."""
<|body_0|>
def _compute_product_qty_to_sell(self):
"""Returns the available products to Sell."""
<|body_1|>
def prepare_move_dict(self,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AddItemWizard:
def _compute_qty(self):
"""This function compute on hand quantity and forcasted quantity of product."""
for rec in self:
if rec.product_id:
res = self.env['product.product'].search([('id', '=', rec.product_id.id)])._compute_quantities_dict(self._conte... | the_stack_v2_python_sparse | pos_repair_order/wizard/add_repair_line_wizard.py | divyapy/odoo | train | 0 | |
6c66d5e86baeecd1cc46b1034f24e7a5285d4c96 | [
"assert len(ids) == 1, 'This option should only be used for a single id at a time.'\ninvoice = self.pool['account.invoice'].browse(cr, uid, ids, context=context)\nhon = False\nfor inv in invoice:\n if inv.hon is True:\n hon = True\nif hon:\n datas = {'ids': ids, 'model': 'account.invoice.hon', 'form': ... | <|body_start_0|>
assert len(ids) == 1, 'This option should only be used for a single id at a time.'
invoice = self.pool['account.invoice'].browse(cr, uid, ids, context=context)
hon = False
for inv in invoice:
if inv.hon is True:
hon = True
if hon:
... | Inherits invoice and adds hon boolean to invoice to flag hon-invoices | account_invoice | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class account_invoice:
"""Inherits invoice and adds hon boolean to invoice to flag hon-invoices"""
def invoice_print(self, cr, uid, ids, context=None):
"""This function prints the invoice and mark it as sent, so that we can see more easily the next step of the workflow"""
<|body_0|... | stack_v2_sparse_classes_75kplus_train_005112 | 5,216 | no_license | [
{
"docstring": "This function prints the invoice and mark it as sent, so that we can see more easily the next step of the workflow",
"name": "invoice_print",
"signature": "def invoice_print(self, cr, uid, ids, context=None)"
},
{
"docstring": "This function opens a window to compose an email, wi... | 2 | stack_v2_sparse_classes_30k_train_025562 | Implement the Python class `account_invoice` described below.
Class description:
Inherits invoice and adds hon boolean to invoice to flag hon-invoices
Method signatures and docstrings:
- def invoice_print(self, cr, uid, ids, context=None): This function prints the invoice and mark it as sent, so that we can see more ... | Implement the Python class `account_invoice` described below.
Class description:
Inherits invoice and adds hon boolean to invoice to flag hon-invoices
Method signatures and docstrings:
- def invoice_print(self, cr, uid, ids, context=None): This function prints the invoice and mark it as sent, so that we can see more ... | b04e4ec9c35a459ef3b2f3c2a6540fc07824d27f | <|skeleton|>
class account_invoice:
"""Inherits invoice and adds hon boolean to invoice to flag hon-invoices"""
def invoice_print(self, cr, uid, ids, context=None):
"""This function prints the invoice and mark it as sent, so that we can see more easily the next step of the workflow"""
<|body_0|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class account_invoice:
"""Inherits invoice and adds hon boolean to invoice to flag hon-invoices"""
def invoice_print(self, cr, uid, ids, context=None):
"""This function prints the invoice and mark it as sent, so that we can see more easily the next step of the workflow"""
assert len(ids) == 1, ... | the_stack_v2_python_sparse | __unported__/nsm_hon/account_invoice.py | praveen-kumarG/nsm-addons | train | 0 |
8c0d72ae7cc97b27b3868462300ef474434533dd | [
"discussion = Discussion.query.get(discussion_id)\nif discussion is None:\n return abort(HTTPStatus.NOT_FOUND, message='Discussion is not found')\ndiscussion.view_count += 1\ndb.session.commit()\nreturn discussion",
"discussion = Discussion.query.get(discussion_id)\nif discussion is None:\n return abort(HTT... | <|body_start_0|>
discussion = Discussion.query.get(discussion_id)
if discussion is None:
return abort(HTTPStatus.NOT_FOUND, message='Discussion is not found')
discussion.view_count += 1
db.session.commit()
return discussion
<|end_body_0|>
<|body_start_1|>
dis... | DiscussionItem | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DiscussionItem:
def get(self, discussion_id):
"""Get discussion info * This action **increases the views count**"""
<|body_0|>
def patch(self, discussion_id):
"""Edit discussion info * User can edit **their discussion** (not frozen) * User with permission to **"edit ... | stack_v2_sparse_classes_75kplus_train_005113 | 3,433 | permissive | [
{
"docstring": "Get discussion info * This action **increases the views count**",
"name": "get",
"signature": "def get(self, discussion_id)"
},
{
"docstring": "Edit discussion info * User can edit **their discussion** (not frozen) * User with permission to **\"edit discussions\"** can edit the d... | 3 | stack_v2_sparse_classes_30k_train_008588 | Implement the Python class `DiscussionItem` described below.
Class description:
Implement the DiscussionItem class.
Method signatures and docstrings:
- def get(self, discussion_id): Get discussion info * This action **increases the views count**
- def patch(self, discussion_id): Edit discussion info * User can edit *... | Implement the Python class `DiscussionItem` described below.
Class description:
Implement the DiscussionItem class.
Method signatures and docstrings:
- def get(self, discussion_id): Get discussion info * This action **increases the views count**
- def patch(self, discussion_id): Edit discussion info * User can edit *... | dce87ffe395ae4bd08b47f28e07594e1889da819 | <|skeleton|>
class DiscussionItem:
def get(self, discussion_id):
"""Get discussion info * This action **increases the views count**"""
<|body_0|>
def patch(self, discussion_id):
"""Edit discussion info * User can edit **their discussion** (not frozen) * User with permission to **"edit ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DiscussionItem:
def get(self, discussion_id):
"""Get discussion info * This action **increases the views count**"""
discussion = Discussion.query.get(discussion_id)
if discussion is None:
return abort(HTTPStatus.NOT_FOUND, message='Discussion is not found')
discussi... | the_stack_v2_python_sparse | src/backend/app/api/public/discussions/discussion/discussion.py | aimanow/sft | train | 0 | |
c8e04e94744e10f9e4b534d4a9afa6ac19090c61 | [
"scope = canned_query\nquery = user_query\nif logged_in_user_proxy:\n query = IS_STARRED_RE.sub('starredby:%016x' % logged_in_user_proxy.user_id, query)\n query = ME_RE.sub(logged_in_user_proxy.username, query)\n scope = IS_STARRED_RE.sub('starredby:%016x' % logged_in_user_proxy.user_id, scope)\n scope ... | <|body_start_0|>
scope = canned_query
query = user_query
if logged_in_user_proxy:
query = IS_STARRED_RE.sub('starredby:%016x' % logged_in_user_proxy.user_id, query)
query = ME_RE.sub(logged_in_user_proxy.username, query)
scope = IS_STARRED_RE.sub('starredby:%0... | This class handles issue search and issue index building requests. IssueIndex uses the SearchEngine class to parse and run issue queries and to submit revised search engine documents to the search engine. Also, it adds DIT-specific fields and additional user query syntax. | IssueIndex | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IssueIndex:
"""This class handles issue search and issue index building requests. IssueIndex uses the SearchEngine class to parse and run issue queries and to submit revised search engine documents to the search engine. Also, it adds DIT-specific fields and additional user query syntax."""
d... | stack_v2_sparse_classes_75kplus_train_005114 | 6,786 | permissive | [
{
"docstring": "Run the user's query in the context of a project's canned query. Args: user_query: string of user query in user syntax. project_name: the name of the project to search in. canned_query: string of canned query context in user syntax. logged_in_user_proxy: Null when no user is logged in, otherwise... | 3 | stack_v2_sparse_classes_30k_train_012288 | Implement the Python class `IssueIndex` described below.
Class description:
This class handles issue search and issue index building requests. IssueIndex uses the SearchEngine class to parse and run issue queries and to submit revised search engine documents to the search engine. Also, it adds DIT-specific fields and ... | Implement the Python class `IssueIndex` described below.
Class description:
This class handles issue search and issue index building requests. IssueIndex uses the SearchEngine class to parse and run issue queries and to submit revised search engine documents to the search engine. Also, it adds DIT-specific fields and ... | 104069e83c0c6eafc70bd0a8a4d3bf0b57b00e1d | <|skeleton|>
class IssueIndex:
"""This class handles issue search and issue index building requests. IssueIndex uses the SearchEngine class to parse and run issue queries and to submit revised search engine documents to the search engine. Also, it adds DIT-specific fields and additional user query syntax."""
d... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IssueIndex:
"""This class handles issue search and issue index building requests. IssueIndex uses the SearchEngine class to parse and run issue queries and to submit revised search engine documents to the search engine. Also, it adds DIT-specific fields and additional user query syntax."""
def SearchProj... | the_stack_v2_python_sparse | src/dit/issueindex.py | scashin133/longhouse | train | 0 |
93b3eae173a8cc589faea3e7007c8d4cba236de5 | [
"enc_hex = Encoder.encode_hex(bssid, psk)\nenc_freq = Encoder.encode_frequencies(enc_hex)\nreturn enc_freq",
"bssid = bssid.lower().strip()\npsk = psk.strip()\nmain = MainActivity()\nencoder = DataEncoder()\nshort_bssid = main._to_mac_address(bssid)\nmac = main._gen_mac_bytes(short_bssid)\nencoded = encoder.encod... | <|body_start_0|>
enc_hex = Encoder.encode_hex(bssid, psk)
enc_freq = Encoder.encode_frequencies(enc_hex)
return enc_freq
<|end_body_0|>
<|body_start_1|>
bssid = bssid.lower().strip()
psk = psk.strip()
main = MainActivity()
encoder = DataEncoder()
short_bs... | Essentially a minimalist wrapper for ..voice.encoder.DataEncoder.DataEncoder Utilising: ..voice.MainActivity.MainActivity ..voice.encoder.VoicePlayer.VoicePlayer | Encoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Encoder:
"""Essentially a minimalist wrapper for ..voice.encoder.DataEncoder.DataEncoder Utilising: ..voice.MainActivity.MainActivity ..voice.encoder.VoicePlayer.VoicePlayer"""
def encode(bssid, psk):
"""Shortcut for: Encoder.encode_hex Encoder.encode_frequencies Encode 'bssid' and '... | stack_v2_sparse_classes_75kplus_train_005115 | 2,118 | no_license | [
{
"docstring": "Shortcut for: Encoder.encode_hex Encoder.encode_frequencies Encode 'bssid' and 'psk' into 'frequencies'",
"name": "encode",
"signature": "def encode(bssid, psk)"
},
{
"docstring": "Wrapper for: ..voice.MainActivity.MainActivity._to_mac_address ..voice.MainActivity.MainActivity._g... | 3 | stack_v2_sparse_classes_30k_train_023365 | Implement the Python class `Encoder` described below.
Class description:
Essentially a minimalist wrapper for ..voice.encoder.DataEncoder.DataEncoder Utilising: ..voice.MainActivity.MainActivity ..voice.encoder.VoicePlayer.VoicePlayer
Method signatures and docstrings:
- def encode(bssid, psk): Shortcut for: Encoder.e... | Implement the Python class `Encoder` described below.
Class description:
Essentially a minimalist wrapper for ..voice.encoder.DataEncoder.DataEncoder Utilising: ..voice.MainActivity.MainActivity ..voice.encoder.VoicePlayer.VoicePlayer
Method signatures and docstrings:
- def encode(bssid, psk): Shortcut for: Encoder.e... | 7d370342f34e26e6e66718ae397eb1d81253cd8a | <|skeleton|>
class Encoder:
"""Essentially a minimalist wrapper for ..voice.encoder.DataEncoder.DataEncoder Utilising: ..voice.MainActivity.MainActivity ..voice.encoder.VoicePlayer.VoicePlayer"""
def encode(bssid, psk):
"""Shortcut for: Encoder.encode_hex Encoder.encode_frequencies Encode 'bssid' and '... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Encoder:
"""Essentially a minimalist wrapper for ..voice.encoder.DataEncoder.DataEncoder Utilising: ..voice.MainActivity.MainActivity ..voice.encoder.VoicePlayer.VoicePlayer"""
def encode(bssid, psk):
"""Shortcut for: Encoder.encode_hex Encoder.encode_frequencies Encode 'bssid' and 'psk' into 'fr... | the_stack_v2_python_sparse | yatwin/onekeywifi/encoder/Encoder.py | andre95d/python-yatwin | train | 0 |
8f3adcda12a07b37f80d5bc4edd04bc768e61c96 | [
"res = []\n\ndef dfs(root: TreeNode):\n if not root:\n return\n nonlocal res\n res.append(root.val)\n dfs(root.left)\n dfs(root.right)\ndfs(root)\nreturn res",
"if not root:\n return []\nstack, res = ([], [])\ncur = root\nwhile stack or cur:\n while cur:\n res.append(cur.val)\n ... | <|body_start_0|>
res = []
def dfs(root: TreeNode):
if not root:
return
nonlocal res
res.append(root.val)
dfs(root.left)
dfs(root.right)
dfs(root)
return res
<|end_body_0|>
<|body_start_1|>
if not root:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
"""前序遍历-递归 :param root: :return:"""
<|body_0|>
def preorderTraversal_2(self, root: TreeNode) -> List[int]:
"""前序遍历-栈迭代法,先进后出 :param root: :return:"""
<|body_1|>
def inorderTraversal(self... | stack_v2_sparse_classes_75kplus_train_005116 | 2,937 | no_license | [
{
"docstring": "前序遍历-递归 :param root: :return:",
"name": "preorderTraversal",
"signature": "def preorderTraversal(self, root: TreeNode) -> List[int]"
},
{
"docstring": "前序遍历-栈迭代法,先进后出 :param root: :return:",
"name": "preorderTraversal_2",
"signature": "def preorderTraversal_2(self, root: ... | 6 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def preorderTraversal(self, root: TreeNode) -> List[int]: 前序遍历-递归 :param root: :return:
- def preorderTraversal_2(self, root: TreeNode) -> List[int]: 前序遍历-栈迭代法,先进后出 :param root: ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def preorderTraversal(self, root: TreeNode) -> List[int]: 前序遍历-递归 :param root: :return:
- def preorderTraversal_2(self, root: TreeNode) -> List[int]: 前序遍历-栈迭代法,先进后出 :param root: ... | 150a216213ddb2012b603899717ad7a769c1b3c3 | <|skeleton|>
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
"""前序遍历-递归 :param root: :return:"""
<|body_0|>
def preorderTraversal_2(self, root: TreeNode) -> List[int]:
"""前序遍历-栈迭代法,先进后出 :param root: :return:"""
<|body_1|>
def inorderTraversal(self... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
"""前序遍历-递归 :param root: :return:"""
res = []
def dfs(root: TreeNode):
if not root:
return
nonlocal res
res.append(root.val)
dfs(root.left)
df... | the_stack_v2_python_sparse | code/30_二叉树前中后序遍历.py | fsc2016/LeetCode | train | 0 | |
c32129c77f04840651d90ebb9a50df32385d6cc9 | [
"dp = [float('inf') for _ in range(amount + 1)]\ndp[0] = 0\nfor n in range(amount + 1):\n for coin in coins:\n if n + coin <= amount:\n dp[n + coin] = min(dp[n + coin], dp[n] + 1)\nreturn dp[-1] if dp[-1] < float('inf') else -1",
"def search(amount, count, index):\n if amount == 0:\n ... | <|body_start_0|>
dp = [float('inf') for _ in range(amount + 1)]
dp[0] = 0
for n in range(amount + 1):
for coin in coins:
if n + coin <= amount:
dp[n + coin] = min(dp[n + coin], dp[n] + 1)
return dp[-1] if dp[-1] < float('inf') else -1
<|end... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def coinChange(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int"""
<|body_0|>
def coinChange_search(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_st... | stack_v2_sparse_classes_75kplus_train_005117 | 2,530 | no_license | [
{
"docstring": ":type coins: List[int] :type amount: int :rtype: int",
"name": "coinChange",
"signature": "def coinChange(self, coins, amount)"
},
{
"docstring": ":type coins: List[int] :type amount: int :rtype: int",
"name": "coinChange_search",
"signature": "def coinChange_search(self,... | 2 | stack_v2_sparse_classes_30k_train_004556 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def coinChange(self, coins, amount): :type coins: List[int] :type amount: int :rtype: int
- def coinChange_search(self, coins, amount): :type coins: List[int] :type amount: int :... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def coinChange(self, coins, amount): :type coins: List[int] :type amount: int :rtype: int
- def coinChange_search(self, coins, amount): :type coins: List[int] :type amount: int :... | e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59 | <|skeleton|>
class Solution:
def coinChange(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int"""
<|body_0|>
def coinChange_search(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def coinChange(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int"""
dp = [float('inf') for _ in range(amount + 1)]
dp[0] = 0
for n in range(amount + 1):
for coin in coins:
if n + coin <= amount:
... | the_stack_v2_python_sparse | src/lt_322.py | oxhead/CodingYourWay | train | 0 | |
eaed9ea467b0c1ddf086ce307aabdfd2cc4efb2d | [
"self.device_name = device_name\nself.id = id\nself.is_root_device = is_root_device\nself.name = name\nself.size_gb = size_gb\nself.mtype = mtype",
"if dictionary is None:\n return None\ndevice_name = dictionary.get('deviceName')\nid = dictionary.get('id')\nis_root_device = dictionary.get('isRootDevice')\nname... | <|body_start_0|>
self.device_name = device_name
self.id = id
self.is_root_device = is_root_device
self.name = name
self.size_gb = size_gb
self.mtype = mtype
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
device_name = dicti... | Implementation of the 'GcpDiskInfo' model. Specified info about the GCP disk. Attributes: device_name (string): Specifies the name of the device. Eg - /dev/sdb. id (long|int): Specified ID of the disk. is_root_device (bool): Specifies if the disk is attached as root device. name (string): Specifies the name of the disk... | GcpDiskInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GcpDiskInfo:
"""Implementation of the 'GcpDiskInfo' model. Specified info about the GCP disk. Attributes: device_name (string): Specifies the name of the device. Eg - /dev/sdb. id (long|int): Specified ID of the disk. is_root_device (bool): Specifies if the disk is attached as root device. name (... | stack_v2_sparse_classes_75kplus_train_005118 | 2,398 | permissive | [
{
"docstring": "Constructor for the GcpDiskInfo class",
"name": "__init__",
"signature": "def __init__(self, device_name=None, id=None, is_root_device=None, name=None, size_gb=None, mtype=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary):... | 2 | stack_v2_sparse_classes_30k_train_021194 | Implement the Python class `GcpDiskInfo` described below.
Class description:
Implementation of the 'GcpDiskInfo' model. Specified info about the GCP disk. Attributes: device_name (string): Specifies the name of the device. Eg - /dev/sdb. id (long|int): Specified ID of the disk. is_root_device (bool): Specifies if the ... | Implement the Python class `GcpDiskInfo` described below.
Class description:
Implementation of the 'GcpDiskInfo' model. Specified info about the GCP disk. Attributes: device_name (string): Specifies the name of the device. Eg - /dev/sdb. id (long|int): Specified ID of the disk. is_root_device (bool): Specifies if the ... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class GcpDiskInfo:
"""Implementation of the 'GcpDiskInfo' model. Specified info about the GCP disk. Attributes: device_name (string): Specifies the name of the device. Eg - /dev/sdb. id (long|int): Specified ID of the disk. is_root_device (bool): Specifies if the disk is attached as root device. name (... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GcpDiskInfo:
"""Implementation of the 'GcpDiskInfo' model. Specified info about the GCP disk. Attributes: device_name (string): Specifies the name of the device. Eg - /dev/sdb. id (long|int): Specified ID of the disk. is_root_device (bool): Specifies if the disk is attached as root device. name (string): Spec... | the_stack_v2_python_sparse | cohesity_management_sdk/models/gcp_disk_info.py | cohesity/management-sdk-python | train | 24 |
a74bfae1169ead3d4da5e435506d5fc0f4ff1aed | [
"if self.target_version:\n return os.path.join(self.dist_dir, '%s.win32-py%s.exe' % (fullname, self.target_version))\nelse:\n return os.path.join(self.dist_dir, '%s.win32.exe' % fullname)",
"import struct\nself.mkpath(self.dist_dir)\ncfgdata = self.get_inidata()\ninstaller_name = self.get_installer_filename... | <|body_start_0|>
if self.target_version:
return os.path.join(self.dist_dir, '%s.win32-py%s.exe' % (fullname, self.target_version))
else:
return os.path.join(self.dist_dir, '%s.win32.exe' % fullname)
<|end_body_0|>
<|body_start_1|>
import struct
self.mkpath(self.d... | Version of bdist_wininst with customization point for filename This class should operate identically to the built-in class for Python 2.3 and below, it exists solely to provide the customization point which exists in Python 2.4a2 and beyond | BdistWinInstaller | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BdistWinInstaller:
"""Version of bdist_wininst with customization point for filename This class should operate identically to the built-in class for Python 2.3 and below, it exists solely to provide the customization point which exists in Python 2.4a2 and beyond"""
def get_installer_filename... | stack_v2_sparse_classes_75kplus_train_005119 | 2,690 | no_license | [
{
"docstring": "Calculate the final installer filename",
"name": "get_installer_filename",
"signature": "def get_installer_filename(self, fullname)"
},
{
"docstring": "Do the actual creation of the executable file The base command, unfortunately, does not break down this command into sub-command... | 2 | stack_v2_sparse_classes_30k_train_047433 | Implement the Python class `BdistWinInstaller` described below.
Class description:
Version of bdist_wininst with customization point for filename This class should operate identically to the built-in class for Python 2.3 and below, it exists solely to provide the customization point which exists in Python 2.4a2 and be... | Implement the Python class `BdistWinInstaller` described below.
Class description:
Version of bdist_wininst with customization point for filename This class should operate identically to the built-in class for Python 2.3 and below, it exists solely to provide the customization point which exists in Python 2.4a2 and be... | c30bf50ba29cb562d530e71a9d6c3d8ad75aa230 | <|skeleton|>
class BdistWinInstaller:
"""Version of bdist_wininst with customization point for filename This class should operate identically to the built-in class for Python 2.3 and below, it exists solely to provide the customization point which exists in Python 2.4a2 and beyond"""
def get_installer_filename... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BdistWinInstaller:
"""Version of bdist_wininst with customization point for filename This class should operate identically to the built-in class for Python 2.3 and below, it exists solely to provide the customization point which exists in Python 2.4a2 and beyond"""
def get_installer_filename(self, fullna... | the_stack_v2_python_sparse | pyobjc/PyOpenGL-2.0.2.01/setup/bdist_wininst.py | orestis/pyobjc | train | 8 |
3695cfd1fb288cf2aa5fa22bac31836e0f4bea28 | [
"logging.debug('%sCreate Namespace ...', LoggerSetup.get_log_deep(2))\nself.ipdb = ipdb if ipdb else IPDB()\nself.ipdb_netns = None\nself.nsp_name = nsp_name\ntry:\n self.ipdb_netns = IPDB(nl=NetNS(nsp_name))\n self.ipdb_netns.interfaces['lo'].up().commit()\n logging.debug('%s[+] Namespace(' + nsp_name + '... | <|body_start_0|>
logging.debug('%sCreate Namespace ...', LoggerSetup.get_log_deep(2))
self.ipdb = ipdb if ipdb else IPDB()
self.ipdb_netns = None
self.nsp_name = nsp_name
try:
self.ipdb_netns = IPDB(nl=NetNS(nsp_name))
self.ipdb_netns.interfaces['lo'].up()... | A Network-Namespace is logically another copy of the network stack, with its own routes, firewall rules, and network devices. By default a process inherits its Network-Namespace from its parent. Initially all the processes share the same default Network-Namespace from the init process. | Namespace | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Namespace:
"""A Network-Namespace is logically another copy of the network stack, with its own routes, firewall rules, and network devices. By default a process inherits its Network-Namespace from its parent. Initially all the processes share the same default Network-Namespace from the init proce... | stack_v2_sparse_classes_75kplus_train_005120 | 4,597 | no_license | [
{
"docstring": ":param ipdb: IPDB is a transactional database, containing records, representing network stack objects. Any change in the database is not reflected immediately in OS, but waits until commit() is called. :param nsp_name: Name of the Namespace",
"name": "__init__",
"signature": "def __init_... | 4 | stack_v2_sparse_classes_30k_train_039601 | Implement the Python class `Namespace` described below.
Class description:
A Network-Namespace is logically another copy of the network stack, with its own routes, firewall rules, and network devices. By default a process inherits its Network-Namespace from its parent. Initially all the processes share the same defaul... | Implement the Python class `Namespace` described below.
Class description:
A Network-Namespace is logically another copy of the network stack, with its own routes, firewall rules, and network devices. By default a process inherits its Network-Namespace from its parent. Initially all the processes share the same defaul... | 551fb53a6d4f865f076d9485e7290699d988731c | <|skeleton|>
class Namespace:
"""A Network-Namespace is logically another copy of the network stack, with its own routes, firewall rules, and network devices. By default a process inherits its Network-Namespace from its parent. Initially all the processes share the same default Network-Namespace from the init proce... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Namespace:
"""A Network-Namespace is logically another copy of the network stack, with its own routes, firewall rules, and network devices. By default a process inherits its Network-Namespace from its parent. Initially all the processes share the same default Network-Namespace from the init process."""
d... | the_stack_v2_python_sparse | network/namespace.py | PumucklOnTheAir/TestFramework | train | 9 |
ac929f91981d9dbd39f06dadbbcbcb8e1fb85053 | [
"user = get_a_user(locationid)\nif not user:\n api.abort(404)\nelse:\n return user\ndata = request.json\nreturn get_a_user(data=data)",
"user = complete_locations(locationid)\nif not user:\n api.abort(404)\nelse:\n return user\ndata = request.json\nreturn complete_locations(data=data)",
"user = dele... | <|body_start_0|>
user = get_a_user(locationid)
if not user:
api.abort(404)
else:
return user
data = request.json
return get_a_user(data=data)
<|end_body_0|>
<|body_start_1|>
user = complete_locations(locationid)
if not user:
ap... | Locations | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Locations:
def get(self, locationid):
"""get a locations given its identifier"""
<|body_0|>
def put(self, locationid):
"""locations Update"""
<|body_1|>
def delete(self, locationid):
"""locations Deleted"""
<|body_2|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_75kplus_train_005121 | 2,674 | no_license | [
{
"docstring": "get a locations given its identifier",
"name": "get",
"signature": "def get(self, locationid)"
},
{
"docstring": "locations Update",
"name": "put",
"signature": "def put(self, locationid)"
},
{
"docstring": "locations Deleted",
"name": "delete",
"signature... | 3 | stack_v2_sparse_classes_30k_train_010153 | Implement the Python class `Locations` described below.
Class description:
Implement the Locations class.
Method signatures and docstrings:
- def get(self, locationid): get a locations given its identifier
- def put(self, locationid): locations Update
- def delete(self, locationid): locations Deleted | Implement the Python class `Locations` described below.
Class description:
Implement the Locations class.
Method signatures and docstrings:
- def get(self, locationid): get a locations given its identifier
- def put(self, locationid): locations Update
- def delete(self, locationid): locations Deleted
<|skeleton|>
cl... | 4fa4042304ee01cf23ecc81f9c27977fd12c31b9 | <|skeleton|>
class Locations:
def get(self, locationid):
"""get a locations given its identifier"""
<|body_0|>
def put(self, locationid):
"""locations Update"""
<|body_1|>
def delete(self, locationid):
"""locations Deleted"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Locations:
def get(self, locationid):
"""get a locations given its identifier"""
user = get_a_user(locationid)
if not user:
api.abort(404)
else:
return user
data = request.json
return get_a_user(data=data)
def put(self, locationid):
... | the_stack_v2_python_sparse | main/controller/locations_controller.py | Gauravkumar45/Flask-RESTPlus-API | train | 0 | |
ff1a4f7edad5fb8903acd5571be18c816ca4df81 | [
"self.dataloader = dataloader\nself.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nself.encoder = Encoder(latent_dim).to(self.device)\nself.decoder = Decoder(latent_dim).to(self.device)\nself.criterion = nn.L1Loss()\nself.optim = torch.optim.Adam((*self.encoder.parameters(), *self.decoder.pa... | <|body_start_0|>
self.dataloader = dataloader
self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
self.encoder = Encoder(latent_dim).to(self.device)
self.decoder = Decoder(latent_dim).to(self.device)
self.criterion = nn.L1Loss()
self.optim = torch.o... | A simple, fully-connected AutoEncoder for MNIST digits. | AutoEncoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AutoEncoder:
"""A simple, fully-connected AutoEncoder for MNIST digits."""
def __init__(self, dataloader: DataLoader, latent_dim: int=2) -> None:
"""Initialize the autoencoder with a dataloader and latent dim."""
<|body_0|>
def encode(self, image: torch.Tensor) -> torch.... | stack_v2_sparse_classes_75kplus_train_005122 | 4,076 | permissive | [
{
"docstring": "Initialize the autoencoder with a dataloader and latent dim.",
"name": "__init__",
"signature": "def __init__(self, dataloader: DataLoader, latent_dim: int=2) -> None"
},
{
"docstring": "Encode an image as a latent vector.",
"name": "encode",
"signature": "def encode(self... | 5 | stack_v2_sparse_classes_30k_train_010257 | Implement the Python class `AutoEncoder` described below.
Class description:
A simple, fully-connected AutoEncoder for MNIST digits.
Method signatures and docstrings:
- def __init__(self, dataloader: DataLoader, latent_dim: int=2) -> None: Initialize the autoencoder with a dataloader and latent dim.
- def encode(self... | Implement the Python class `AutoEncoder` described below.
Class description:
A simple, fully-connected AutoEncoder for MNIST digits.
Method signatures and docstrings:
- def __init__(self, dataloader: DataLoader, latent_dim: int=2) -> None: Initialize the autoencoder with a dataloader and latent dim.
- def encode(self... | 39527af3f24acae787fcb7c84fe5df2bf6557c14 | <|skeleton|>
class AutoEncoder:
"""A simple, fully-connected AutoEncoder for MNIST digits."""
def __init__(self, dataloader: DataLoader, latent_dim: int=2) -> None:
"""Initialize the autoencoder with a dataloader and latent dim."""
<|body_0|>
def encode(self, image: torch.Tensor) -> torch.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AutoEncoder:
"""A simple, fully-connected AutoEncoder for MNIST digits."""
def __init__(self, dataloader: DataLoader, latent_dim: int=2) -> None:
"""Initialize the autoencoder with a dataloader and latent dim."""
self.dataloader = dataloader
self.device = torch.device('cuda' if to... | the_stack_v2_python_sparse | 12021/visualizing_AE_MNIST/autoencoder.py | fare21/medium | train | 0 |
e2fa4c0c3f045bd7b49d517d7b93a8aa4c0e66fb | [
"tokens = ['a', 'bb', 'ccc']\ntext = 'a bb ccc'\nspans = list(generic_token_spans(text, tokens))\nexpected = [Span(0, 1), Span(2, 4), Span(8, 11)]\nself.assertEquals(expected, spans)",
"tokens = ['a', 'b b', 'c c c']\ntext = 'a bb ccc'\nspans = list(generic_token_spans(text, tokens))\nexpected = [Span(0, 1)... | <|body_start_0|>
tokens = ['a', 'bb', 'ccc']
text = 'a bb ccc'
spans = list(generic_token_spans(text, tokens))
expected = [Span(0, 1), Span(2, 4), Span(8, 11)]
self.assertEquals(expected, spans)
<|end_body_0|>
<|body_start_1|>
tokens = ['a', 'b b', 'c c c']
te... | Working with part of speech taggers | PosTag | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PosTag:
"""Working with part of speech taggers"""
def test_simple_align(self):
"""trivial token realignment"""
<|body_0|>
def test_messy_align(self):
"""ignore whitespace in token"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
tokens = ['a', 'b... | stack_v2_sparse_classes_75kplus_train_005123 | 978 | no_license | [
{
"docstring": "trivial token realignment",
"name": "test_simple_align",
"signature": "def test_simple_align(self)"
},
{
"docstring": "ignore whitespace in token",
"name": "test_messy_align",
"signature": "def test_messy_align(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_035314 | Implement the Python class `PosTag` described below.
Class description:
Working with part of speech taggers
Method signatures and docstrings:
- def test_simple_align(self): trivial token realignment
- def test_messy_align(self): ignore whitespace in token | Implement the Python class `PosTag` described below.
Class description:
Working with part of speech taggers
Method signatures and docstrings:
- def test_simple_align(self): trivial token realignment
- def test_messy_align(self): ignore whitespace in token
<|skeleton|>
class PosTag:
"""Working with part of speech... | c550f4383016e05fe20ad7180a027979e3540d1f | <|skeleton|>
class PosTag:
"""Working with part of speech taggers"""
def test_simple_align(self):
"""trivial token realignment"""
<|body_0|>
def test_messy_align(self):
"""ignore whitespace in token"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PosTag:
"""Working with part of speech taggers"""
def test_simple_align(self):
"""trivial token realignment"""
tokens = ['a', 'bb', 'ccc']
text = 'a bb ccc'
spans = list(generic_token_spans(text, tokens))
expected = [Span(0, 1), Span(2, 4), Span(8, 11)]
... | the_stack_v2_python_sparse | educe/external/tests.py | kowey/educe | train | 1 |
546fba9b9522a58b2ca7ea79e031a432bfe6873c | [
"self.num_points = num_points\nself.x_values = [0]\nself.y_values = [0]",
"direction = choice([1, -1])\ndistance = choice([0, 1, 2, 3, 4])\nget_step = direction * distance\nreturn get_step",
"while len(self.x_values) < self.num_points:\n x_step = self.get_step()\n y_step = self.get_step()\n if x_step =... | <|body_start_0|>
self.num_points = num_points
self.x_values = [0]
self.y_values = [0]
<|end_body_0|>
<|body_start_1|>
direction = choice([1, -1])
distance = choice([0, 1, 2, 3, 4])
get_step = direction * distance
return get_step
<|end_body_1|>
<|body_start_2|>
... | 一个生成随机漫步的属性 | RandomWalk | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomWalk:
"""一个生成随机漫步的属性"""
def __init__(self, num_points=5000):
"""初始化随机漫步的属性"""
<|body_0|>
def get_step(self):
"""计算漫步如何移动"""
<|body_1|>
def fill_walk(self):
"""计算随机漫步包含的所有点"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_005124 | 1,314 | no_license | [
{
"docstring": "初始化随机漫步的属性",
"name": "__init__",
"signature": "def __init__(self, num_points=5000)"
},
{
"docstring": "计算漫步如何移动",
"name": "get_step",
"signature": "def get_step(self)"
},
{
"docstring": "计算随机漫步包含的所有点",
"name": "fill_walk",
"signature": "def fill_walk(self)... | 3 | null | Implement the Python class `RandomWalk` described below.
Class description:
一个生成随机漫步的属性
Method signatures and docstrings:
- def __init__(self, num_points=5000): 初始化随机漫步的属性
- def get_step(self): 计算漫步如何移动
- def fill_walk(self): 计算随机漫步包含的所有点 | Implement the Python class `RandomWalk` described below.
Class description:
一个生成随机漫步的属性
Method signatures and docstrings:
- def __init__(self, num_points=5000): 初始化随机漫步的属性
- def get_step(self): 计算漫步如何移动
- def fill_walk(self): 计算随机漫步包含的所有点
<|skeleton|>
class RandomWalk:
"""一个生成随机漫步的属性"""
def __init__(self, n... | 968913d7b8b3baba2b755d9edcdacef850ab4b61 | <|skeleton|>
class RandomWalk:
"""一个生成随机漫步的属性"""
def __init__(self, num_points=5000):
"""初始化随机漫步的属性"""
<|body_0|>
def get_step(self):
"""计算漫步如何移动"""
<|body_1|>
def fill_walk(self):
"""计算随机漫步包含的所有点"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RandomWalk:
"""一个生成随机漫步的属性"""
def __init__(self, num_points=5000):
"""初始化随机漫步的属性"""
self.num_points = num_points
self.x_values = [0]
self.y_values = [0]
def get_step(self):
"""计算漫步如何移动"""
direction = choice([1, -1])
distance = choice([0, 1, 2, ... | the_stack_v2_python_sparse | PythonCrashCourse/ch16/matplotlib/random_walk.py | joyc/python-book-test | train | 0 |
3a451d3eff90e90c67e63b2186b30a2b6645f943 | [
"super(NN, self).__init__()\nself.fc1 = nn.Linear(input_size, 50)\nself.fc2 = nn.Linear(50, num_classes)",
"x = F.relu(self.fc1(x))\nx = self.fc2(x)\nreturn x"
] | <|body_start_0|>
super(NN, self).__init__()
self.fc1 = nn.Linear(input_size, 50)
self.fc2 = nn.Linear(50, num_classes)
<|end_body_0|>
<|body_start_1|>
x = F.relu(self.fc1(x))
x = self.fc2(x)
return x
<|end_body_1|>
| NN | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NN:
def __init__(self, input_size, num_classes):
"""Here we define the layers of the network. We create two fully connected layers Parameters: input_size: the size of the input, in this case 784 (28x28) num_classes: the number of classes we want to predict, in this case 10 (0-9)"""
... | stack_v2_sparse_classes_75kplus_train_005125 | 5,621 | permissive | [
{
"docstring": "Here we define the layers of the network. We create two fully connected layers Parameters: input_size: the size of the input, in this case 784 (28x28) num_classes: the number of classes we want to predict, in this case 10 (0-9)",
"name": "__init__",
"signature": "def __init__(self, input... | 2 | stack_v2_sparse_classes_30k_train_030318 | Implement the Python class `NN` described below.
Class description:
Implement the NN class.
Method signatures and docstrings:
- def __init__(self, input_size, num_classes): Here we define the layers of the network. We create two fully connected layers Parameters: input_size: the size of the input, in this case 784 (2... | Implement the Python class `NN` described below.
Class description:
Implement the NN class.
Method signatures and docstrings:
- def __init__(self, input_size, num_classes): Here we define the layers of the network. We create two fully connected layers Parameters: input_size: the size of the input, in this case 784 (2... | 558557c7989f0b10fee6e8d8f953d7269ae43d4f | <|skeleton|>
class NN:
def __init__(self, input_size, num_classes):
"""Here we define the layers of the network. We create two fully connected layers Parameters: input_size: the size of the input, in this case 784 (28x28) num_classes: the number of classes we want to predict, in this case 10 (0-9)"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NN:
def __init__(self, input_size, num_classes):
"""Here we define the layers of the network. We create two fully connected layers Parameters: input_size: the size of the input, in this case 784 (28x28) num_classes: the number of classes we want to predict, in this case 10 (0-9)"""
super(NN, s... | the_stack_v2_python_sparse | ML/Pytorch/Basics/pytorch_simple_fullynet.py | aladdinpersson/Machine-Learning-Collection | train | 5,653 | |
cb9c7b6b5aea5ae03688ce0ff618eb18b7197d6d | [
"if not self.redis_key:\n self.redis_key = '%s:start_urls' % self.name\nservers = from_settings(self.crawler.settings)\nself.crawler.signals.connect(self.spider_idle, signal=signals.spider_idle)\nself.log(\"Reading URLs from redis list '%s'\" % self.redis_key)\nqueue_shard_dist = self.crawler.settings.get('PRIOR... | <|body_start_0|>
if not self.redis_key:
self.redis_key = '%s:start_urls' % self.name
servers = from_settings(self.crawler.settings)
self.crawler.signals.connect(self.spider_idle, signal=signals.spider_idle)
self.log("Reading URLs from redis list '%s'" % self.redis_key)
... | Mixin class to implement reading urls from a redis queue. | RedisMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RedisMixin:
"""Mixin class to implement reading urls from a redis queue."""
def setup_redis(self):
"""Setup redis connection and idle signal. This should be called after the spider has set its crawler object."""
<|body_0|>
def next_request(self):
"""Returns a req... | stack_v2_sparse_classes_75kplus_train_005126 | 2,118 | no_license | [
{
"docstring": "Setup redis connection and idle signal. This should be called after the spider has set its crawler object.",
"name": "setup_redis",
"signature": "def setup_redis(self)"
},
{
"docstring": "Returns a request to be scheduled or none.",
"name": "next_request",
"signature": "d... | 3 | null | Implement the Python class `RedisMixin` described below.
Class description:
Mixin class to implement reading urls from a redis queue.
Method signatures and docstrings:
- def setup_redis(self): Setup redis connection and idle signal. This should be called after the spider has set its crawler object.
- def next_request... | Implement the Python class `RedisMixin` described below.
Class description:
Mixin class to implement reading urls from a redis queue.
Method signatures and docstrings:
- def setup_redis(self): Setup redis connection and idle signal. This should be called after the spider has set its crawler object.
- def next_request... | 0dc40186a1d89da2b00f29d4f4edfdc5470eb4fc | <|skeleton|>
class RedisMixin:
"""Mixin class to implement reading urls from a redis queue."""
def setup_redis(self):
"""Setup redis connection and idle signal. This should be called after the spider has set its crawler object."""
<|body_0|>
def next_request(self):
"""Returns a req... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RedisMixin:
"""Mixin class to implement reading urls from a redis queue."""
def setup_redis(self):
"""Setup redis connection and idle signal. This should be called after the spider has set its crawler object."""
if not self.redis_key:
self.redis_key = '%s:start_urls' % self.na... | the_stack_v2_python_sparse | le_crawler/old_spiders/.svn/text-base/le_spiders.py.svn-base | cash2one/crawl_youtube | train | 0 |
0b83a347d22ecd041522f5ec3328c64d084b3776 | [
"self.addr = range(Uss.ADDR_BASE, Uss.ADDR_BASE + Uss.NUM)\nself.srf = []\nfor x in self.addr:\n self.srf.append(SRF02(x))\nself.vals = [0] * Uss.NUM",
"for srf in self.srf:\n srf.emit()\nsleep(0.055)\n\ndef f(x):\n return x.get()\ntmp = map(f, self.srf)\nself.vals = list(tmp)"
] | <|body_start_0|>
self.addr = range(Uss.ADDR_BASE, Uss.ADDR_BASE + Uss.NUM)
self.srf = []
for x in self.addr:
self.srf.append(SRF02(x))
self.vals = [0] * Uss.NUM
<|end_body_0|>
<|body_start_1|>
for srf in self.srf:
srf.emit()
sleep(0.055)
... | I2Cを介した超音波センサとの通信タスクです。 値の取得はtaskPollからのポーリングで行われます。 taskMainからはvalsにアクセスされ、taskCommからはget()にアクセスされます。 | Uss | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Uss:
"""I2Cを介した超音波センサとの通信タスクです。 値の取得はtaskPollからのポーリングで行われます。 taskMainからはvalsにアクセスされ、taskCommからはget()にアクセスされます。"""
def __init__(self):
"""コンストラクタです。 I2Cオブジェクトを取得し、超音波センサをオープンします。"""
<|body_0|>
def get(self):
"""値を取得します。取得した値はvalsへ格納されます。 :return: None"""
<... | stack_v2_sparse_classes_75kplus_train_005127 | 2,418 | no_license | [
{
"docstring": "コンストラクタです。 I2Cオブジェクトを取得し、超音波センサをオープンします。",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "値を取得します。取得した値はvalsへ格納されます。 :return: None",
"name": "get",
"signature": "def get(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001159 | Implement the Python class `Uss` described below.
Class description:
I2Cを介した超音波センサとの通信タスクです。 値の取得はtaskPollからのポーリングで行われます。 taskMainからはvalsにアクセスされ、taskCommからはget()にアクセスされます。
Method signatures and docstrings:
- def __init__(self): コンストラクタです。 I2Cオブジェクトを取得し、超音波センサをオープンします。
- def get(self): 値を取得します。取得した値はvalsへ格納されます。 :retu... | Implement the Python class `Uss` described below.
Class description:
I2Cを介した超音波センサとの通信タスクです。 値の取得はtaskPollからのポーリングで行われます。 taskMainからはvalsにアクセスされ、taskCommからはget()にアクセスされます。
Method signatures and docstrings:
- def __init__(self): コンストラクタです。 I2Cオブジェクトを取得し、超音波センサをオープンします。
- def get(self): 値を取得します。取得した値はvalsへ格納されます。 :retu... | e8b6d08916841e68171d558356f49ddbf5581ad5 | <|skeleton|>
class Uss:
"""I2Cを介した超音波センサとの通信タスクです。 値の取得はtaskPollからのポーリングで行われます。 taskMainからはvalsにアクセスされ、taskCommからはget()にアクセスされます。"""
def __init__(self):
"""コンストラクタです。 I2Cオブジェクトを取得し、超音波センサをオープンします。"""
<|body_0|>
def get(self):
"""値を取得します。取得した値はvalsへ格納されます。 :return: None"""
<... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Uss:
"""I2Cを介した超音波センサとの通信タスクです。 値の取得はtaskPollからのポーリングで行われます。 taskMainからはvalsにアクセスされ、taskCommからはget()にアクセスされます。"""
def __init__(self):
"""コンストラクタです。 I2Cオブジェクトを取得し、超音波センサをオープンします。"""
self.addr = range(Uss.ADDR_BASE, Uss.ADDR_BASE + Uss.NUM)
self.srf = []
for x in self.addr:
... | the_stack_v2_python_sparse | uss.py | fclef978/MIRS1701_Pi | train | 0 |
507537429a4d2dc2b3c86b6131566fa0f96bcdb1 | [
"ret = super(GroupManagerForm, self).clean()\nif self.instance.user:\n del self._errors['username']\n return ret\nkey = 'username'\nif key not in self.cleaned_data:\n return ret\nusername = self.cleaned_data[key]\nqs = User.objects.filter(username=username)\nif len(qs) != 1:\n msg = \"User '%s' does not... | <|body_start_0|>
ret = super(GroupManagerForm, self).clean()
if self.instance.user:
del self._errors['username']
return ret
key = 'username'
if key not in self.cleaned_data:
return ret
username = self.cleaned_data[key]
qs = User.objects... | GroupManagerForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupManagerForm:
def clean(self):
"""创建表单: 检查username是否是一个存在的User,并且用取得的user填给GroupManager object 修改表单: 不检查username, 并清除username的error :return:"""
<|body_0|>
def validate_unique(self):
"""创建表单:检查user唯一性 修改表单:不检查user唯一性 :return:"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_75kplus_train_005128 | 7,490 | no_license | [
{
"docstring": "创建表单: 检查username是否是一个存在的User,并且用取得的user填给GroupManager object 修改表单: 不检查username, 并清除username的error :return:",
"name": "clean",
"signature": "def clean(self)"
},
{
"docstring": "创建表单:检查user唯一性 修改表单:不检查user唯一性 :return:",
"name": "validate_unique",
"signature": "def validate_... | 2 | null | Implement the Python class `GroupManagerForm` described below.
Class description:
Implement the GroupManagerForm class.
Method signatures and docstrings:
- def clean(self): 创建表单: 检查username是否是一个存在的User,并且用取得的user填给GroupManager object 修改表单: 不检查username, 并清除username的error :return:
- def validate_unique(self): 创建表单:检查us... | Implement the Python class `GroupManagerForm` described below.
Class description:
Implement the GroupManagerForm class.
Method signatures and docstrings:
- def clean(self): 创建表单: 检查username是否是一个存在的User,并且用取得的user填给GroupManager object 修改表单: 不检查username, 并清除username的error :return:
- def validate_unique(self): 创建表单:检查us... | c592d879fd79da4e0816a4f909e5725e385b6160 | <|skeleton|>
class GroupManagerForm:
def clean(self):
"""创建表单: 检查username是否是一个存在的User,并且用取得的user填给GroupManager object 修改表单: 不检查username, 并清除username的error :return:"""
<|body_0|>
def validate_unique(self):
"""创建表单:检查user唯一性 修改表单:不检查user唯一性 :return:"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GroupManagerForm:
def clean(self):
"""创建表单: 检查username是否是一个存在的User,并且用取得的user填给GroupManager object 修改表单: 不检查username, 并清除username的error :return:"""
ret = super(GroupManagerForm, self).clean()
if self.instance.user:
del self._errors['username']
return ret
... | the_stack_v2_python_sparse | leetcode/venv/lib/python2.7/site-packages/pyutil/django/group_manager/admin.py | KqSMea8/PycharmProjects | train | 0 | |
58676c97e7c3e24495bc1f266729a1c811eba10c | [
"if cls.query(cls.original == original, ancestor=source.key).get():\n return\ncls(parent=source.key, original=original, syndication=None).put()",
"if cls.query(cls.syndication == syndication, ancestor=source.key).get():\n return\ncls(parent=source.key, original=None, syndication=syndication).put()",
"dupl... | <|body_start_0|>
if cls.query(cls.original == original, ancestor=source.key).get():
return
cls(parent=source.key, original=original, syndication=None).put()
<|end_body_0|>
<|body_start_1|>
if cls.query(cls.syndication == syndication, ancestor=source.key).get():
return
... | Represents a syndicated post and its discovered original (or not if we found no original post). We discover the relationship by following rel=syndication links on the author's h-feed. See :mod:`original_post_discovery`. When a :class:`SyndicatedPost` entity is about to be stored, :meth:`source.Source.on_new_syndicated_... | SyndicatedPost | [
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SyndicatedPost:
"""Represents a syndicated post and its discovered original (or not if we found no original post). We discover the relationship by following rel=syndication links on the author's h-feed. See :mod:`original_post_discovery`. When a :class:`SyndicatedPost` entity is about to be store... | stack_v2_sparse_classes_75kplus_train_005129 | 40,479 | permissive | [
{
"docstring": "Insert a new original -> None relationship. Does a check-and-set to make sure no previous relationship exists for this original. If there is, nothing will be added. Args: source: :class:`Source` subclass original: string",
"name": "insert_original_blank",
"signature": "def insert_origina... | 3 | null | Implement the Python class `SyndicatedPost` described below.
Class description:
Represents a syndicated post and its discovered original (or not if we found no original post). We discover the relationship by following rel=syndication links on the author's h-feed. See :mod:`original_post_discovery`. When a :class:`Synd... | Implement the Python class `SyndicatedPost` described below.
Class description:
Represents a syndicated post and its discovered original (or not if we found no original post). We discover the relationship by following rel=syndication links on the author's h-feed. See :mod:`original_post_discovery`. When a :class:`Synd... | 1d1fc440a504acb53333121215f00da0ce9af466 | <|skeleton|>
class SyndicatedPost:
"""Represents a syndicated post and its discovered original (or not if we found no original post). We discover the relationship by following rel=syndication links on the author's h-feed. See :mod:`original_post_discovery`. When a :class:`SyndicatedPost` entity is about to be store... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SyndicatedPost:
"""Represents a syndicated post and its discovered original (or not if we found no original post). We discover the relationship by following rel=syndication links on the author's h-feed. See :mod:`original_post_discovery`. When a :class:`SyndicatedPost` entity is about to be stored, :meth:`sou... | the_stack_v2_python_sparse | models.py | snarfed/bridgy | train | 580 |
52cc3921ca2f36049403d97a21b2eba8ed692c39 | [
"if RedisDb.__instance is None:\n RedisDb()\nreturn RedisDb.__instance",
"if RedisDb.__instance is not None:\n raise Exception('This class is a singleton!')\nelse:\n RedisDb.__instance = self\n self.db = StrictRedis(host=config.RD_MANGA_HOST, port=config.RD_MANGA_PORT, db=config.RD_DB_INDEX)"
] | <|body_start_0|>
if RedisDb.__instance is None:
RedisDb()
return RedisDb.__instance
<|end_body_0|>
<|body_start_1|>
if RedisDb.__instance is not None:
raise Exception('This class is a singleton!')
else:
RedisDb.__instance = self
self.db = ... | RedisDb | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RedisDb:
def getInstance():
"""Static access method."""
<|body_0|>
def __init__(self):
"""Virtually private constructor."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if RedisDb.__instance is None:
RedisDb()
return RedisDb.__in... | stack_v2_sparse_classes_75kplus_train_005130 | 1,468 | no_license | [
{
"docstring": "Static access method.",
"name": "getInstance",
"signature": "def getInstance()"
},
{
"docstring": "Virtually private constructor.",
"name": "__init__",
"signature": "def __init__(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009478 | Implement the Python class `RedisDb` described below.
Class description:
Implement the RedisDb class.
Method signatures and docstrings:
- def getInstance(): Static access method.
- def __init__(self): Virtually private constructor. | Implement the Python class `RedisDb` described below.
Class description:
Implement the RedisDb class.
Method signatures and docstrings:
- def getInstance(): Static access method.
- def __init__(self): Virtually private constructor.
<|skeleton|>
class RedisDb:
def getInstance():
"""Static access method."... | c84a57c367a722b293ee947b6fcf0639fc8f295e | <|skeleton|>
class RedisDb:
def getInstance():
"""Static access method."""
<|body_0|>
def __init__(self):
"""Virtually private constructor."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RedisDb:
def getInstance():
"""Static access method."""
if RedisDb.__instance is None:
RedisDb()
return RedisDb.__instance
def __init__(self):
"""Virtually private constructor."""
if RedisDb.__instance is not None:
raise Exception('This clas... | the_stack_v2_python_sparse | database/db.py | DuyThangDecima/MangaWs | train | 0 | |
f1d8a34ac40327513bec8e3691d6983291ec9997 | [
"gameid_list = []\ndepotname_list = []\nroute = data[0]['route']\nparameters = data[0]['parameters']\nparameters = eval(parameters)\nfor parameter in parameters:\n url = ''.join(base.get_url(route) + '?' + 'catId=' + str(parameter))\n header = eval(data[0]['header'])\n kwargs = {'headers': header}\n met... | <|body_start_0|>
gameid_list = []
depotname_list = []
route = data[0]['route']
parameters = data[0]['parameters']
parameters = eval(parameters)
for parameter in parameters:
url = ''.join(base.get_url(route) + '?' + 'catId=' + str(parameter))
header... | 获取所有平台下面的一款游戏,来进行跳转 并判断中心钱包的余额有没有带入到游戏中 | GetGameIdList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetGameIdList:
"""获取所有平台下面的一款游戏,来进行跳转 并判断中心钱包的余额有没有带入到游戏中"""
def get_catDepotList(self):
"""获取真人,体育,棋牌,彩票平台的游戏id和name :return:"""
<|body_0|>
def get_elecDepotList(self):
"""获取电子平台id和name :return:"""
<|body_1|>
def get_gameFishList(self):
"""获... | stack_v2_sparse_classes_75kplus_train_005131 | 3,548 | no_license | [
{
"docstring": "获取真人,体育,棋牌,彩票平台的游戏id和name :return:",
"name": "get_catDepotList",
"signature": "def get_catDepotList(self)"
},
{
"docstring": "获取电子平台id和name :return:",
"name": "get_elecDepotList",
"signature": "def get_elecDepotList(self)"
},
{
"docstring": "获取捕鱼平台的游戏id和name :retu... | 4 | stack_v2_sparse_classes_30k_train_003533 | Implement the Python class `GetGameIdList` described below.
Class description:
获取所有平台下面的一款游戏,来进行跳转 并判断中心钱包的余额有没有带入到游戏中
Method signatures and docstrings:
- def get_catDepotList(self): 获取真人,体育,棋牌,彩票平台的游戏id和name :return:
- def get_elecDepotList(self): 获取电子平台id和name :return:
- def get_gameFishList(self): 获取捕鱼平台的游戏id和name... | Implement the Python class `GetGameIdList` described below.
Class description:
获取所有平台下面的一款游戏,来进行跳转 并判断中心钱包的余额有没有带入到游戏中
Method signatures and docstrings:
- def get_catDepotList(self): 获取真人,体育,棋牌,彩票平台的游戏id和name :return:
- def get_elecDepotList(self): 获取电子平台id和name :return:
- def get_gameFishList(self): 获取捕鱼平台的游戏id和name... | c62a4e9e029fb77a307fe802518f12f1bcb31df1 | <|skeleton|>
class GetGameIdList:
"""获取所有平台下面的一款游戏,来进行跳转 并判断中心钱包的余额有没有带入到游戏中"""
def get_catDepotList(self):
"""获取真人,体育,棋牌,彩票平台的游戏id和name :return:"""
<|body_0|>
def get_elecDepotList(self):
"""获取电子平台id和name :return:"""
<|body_1|>
def get_gameFishList(self):
"""获... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GetGameIdList:
"""获取所有平台下面的一款游戏,来进行跳转 并判断中心钱包的余额有没有带入到游戏中"""
def get_catDepotList(self):
"""获取真人,体育,棋牌,彩票平台的游戏id和name :return:"""
gameid_list = []
depotname_list = []
route = data[0]['route']
parameters = data[0]['parameters']
parameters = eval(parameters)
... | the_stack_v2_python_sparse | java_auto_web/case/game/get_gameidlist.py | evebjayson/test | train | 0 |
1043682a5e707264d78a8103b7468847d2f84f08 | [
"self.objtrimesh0 = trimesh.load_mesh(objpath0)\nself.objnp0 = pg.packpandanp_fn(self.objtrimesh0.vertices, self.objtrimesh.face_normals, self.objtrimesh.faces)\nself.objtrimesh1 = trimesh.load_mesh(objpath1)\nself.objnp1 = pg.packpandanp_fn(self.objtrimesh1.vertices, self.objtrimesh.face_normals, self.objtrimesh.f... | <|body_start_0|>
self.objtrimesh0 = trimesh.load_mesh(objpath0)
self.objnp0 = pg.packpandanp_fn(self.objtrimesh0.vertices, self.objtrimesh.face_normals, self.objtrimesh.faces)
self.objtrimesh1 = trimesh.load_mesh(objpath1)
self.objnp1 = pg.packpandanp_fn(self.objtrimesh1.vertices, self.o... | FloatingPoses | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FloatingPoses:
def __init__(self, objpath0, objpath1):
"""load two objects :param objpath0: :param objpath1: author: weiwei date: 20180613"""
<|body_0|>
def genPandaRotmat4(self, icolevel=1, angles=[0, 45, 90, 135, 180, 225, 270, 315]):
"""generate panda3d rotmat4 us... | stack_v2_sparse_classes_75kplus_train_005132 | 2,665 | no_license | [
{
"docstring": "load two objects :param objpath0: :param objpath1: author: weiwei date: 20180613",
"name": "__init__",
"signature": "def __init__(self, objpath0, objpath1)"
},
{
"docstring": "generate panda3d rotmat4 using icospheres and rotationaangle each origin-vertex vector of the icosphere ... | 2 | null | Implement the Python class `FloatingPoses` described below.
Class description:
Implement the FloatingPoses class.
Method signatures and docstrings:
- def __init__(self, objpath0, objpath1): load two objects :param objpath0: :param objpath1: author: weiwei date: 20180613
- def genPandaRotmat4(self, icolevel=1, angles=... | Implement the Python class `FloatingPoses` described below.
Class description:
Implement the FloatingPoses class.
Method signatures and docstrings:
- def __init__(self, objpath0, objpath1): load two objects :param objpath0: :param objpath1: author: weiwei date: 20180613
- def genPandaRotmat4(self, icolevel=1, angles=... | 3f7492d890bd45c955a0cdf05b13d86a9ea39331 | <|skeleton|>
class FloatingPoses:
def __init__(self, objpath0, objpath1):
"""load two objects :param objpath0: :param objpath1: author: weiwei date: 20180613"""
<|body_0|>
def genPandaRotmat4(self, icolevel=1, angles=[0, 45, 90, 135, 180, 225, 270, 315]):
"""generate panda3d rotmat4 us... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FloatingPoses:
def __init__(self, objpath0, objpath1):
"""load two objects :param objpath0: :param objpath1: author: weiwei date: 20180613"""
self.objtrimesh0 = trimesh.load_mesh(objpath0)
self.objnp0 = pg.packpandanp_fn(self.objtrimesh0.vertices, self.objtrimesh.face_normals, self.obj... | the_stack_v2_python_sparse | manipulation/handover/handover.py | wanweiwei07/pymanipulator | train | 9 | |
de97932b394e3fda4fa7c784466d232c7704a599 | [
"super().__init__()\nself.n = layer_num\nself.linear = nn.ModuleList([nn.Linear(size, size) for _ in range(self.n)])\nself.gate = nn.ModuleList([nn.Linear(size, size) for _ in range(self.n)])\nself.relu = nn.ReLU()",
"for i in range(self.n):\n gate = F.sigmoid(self.gate[i](x))\n nonlinear = self.relu(self.l... | <|body_start_0|>
super().__init__()
self.n = layer_num
self.linear = nn.ModuleList([nn.Linear(size, size) for _ in range(self.n)])
self.gate = nn.ModuleList([nn.Linear(size, size) for _ in range(self.n)])
self.relu = nn.ReLU()
<|end_body_0|>
<|body_start_1|>
for i in ran... | Applies highway transformation to the incoming data. It is like LSTM that uses gates. Highway network is helpful to train very deep neural networks. y = H(x, W_H) * T(x, W_T) + x * C(x, W_C) C = 1 - T :Examples: >>> m = Highway(2, 300) >>> x = torch.randn(32, 20, 300) >>> y = m(x) >>> print(y.size()) | Highway | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Highway:
"""Applies highway transformation to the incoming data. It is like LSTM that uses gates. Highway network is helpful to train very deep neural networks. y = H(x, W_H) * T(x, W_T) + x * C(x, W_C) C = 1 - T :Examples: >>> m = Highway(2, 300) >>> x = torch.randn(32, 20, 300) >>> y = m(x) >>>... | stack_v2_sparse_classes_75kplus_train_005133 | 38,467 | no_license | [
{
"docstring": ":param layer_num: number of highway transform layers :param size: size of the last dimension of input",
"name": "__init__",
"signature": "def __init__(self, layer_num, size)"
},
{
"docstring": ":Input: (N, *, size) * means any number of additional dimensions. :Output: (N, *, size... | 2 | stack_v2_sparse_classes_30k_train_025901 | Implement the Python class `Highway` described below.
Class description:
Applies highway transformation to the incoming data. It is like LSTM that uses gates. Highway network is helpful to train very deep neural networks. y = H(x, W_H) * T(x, W_T) + x * C(x, W_C) C = 1 - T :Examples: >>> m = Highway(2, 300) >>> x = to... | Implement the Python class `Highway` described below.
Class description:
Applies highway transformation to the incoming data. It is like LSTM that uses gates. Highway network is helpful to train very deep neural networks. y = H(x, W_H) * T(x, W_T) + x * C(x, W_C) C = 1 - T :Examples: >>> m = Highway(2, 300) >>> x = to... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class Highway:
"""Applies highway transformation to the incoming data. It is like LSTM that uses gates. Highway network is helpful to train very deep neural networks. y = H(x, W_H) * T(x, W_T) + x * C(x, W_C) C = 1 - T :Examples: >>> m = Highway(2, 300) >>> x = torch.randn(32, 20, 300) >>> y = m(x) >>>... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Highway:
"""Applies highway transformation to the incoming data. It is like LSTM that uses gates. Highway network is helpful to train very deep neural networks. y = H(x, W_H) * T(x, W_T) + x * C(x, W_C) C = 1 - T :Examples: >>> m = Highway(2, 300) >>> x = torch.randn(32, 20, 300) >>> y = m(x) >>> print(y.size... | the_stack_v2_python_sparse | generated/test_BangLiu_QANet_PyTorch.py | jansel/pytorch-jit-paritybench | train | 35 |
ab13cad3d494677b33821e9473c61a533631d073 | [
"pre_order = []\nin_order = []\n\ndef pre_search(root):\n if not root:\n return\n pre_order.append(root.val)\n pre_search(root.left)\n pre_search(root.right)\n\ndef in_search(root):\n if not root:\n return\n in_search(root.left)\n in_order.append(root.val)\n in_search(root.righ... | <|body_start_0|>
pre_order = []
in_order = []
def pre_search(root):
if not root:
return
pre_order.append(root.val)
pre_search(root.left)
pre_search(root.right)
def in_search(root):
if not root:
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_005134 | 4,279 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_016166 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 7ffdb772ad7252f3d4b9aa2689a92cb1f10c8f37 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
pre_order = []
in_order = []
def pre_search(root):
if not root:
return
pre_order.append(root.val)
pre_search(root.lef... | the_stack_v2_python_sparse | 二叉树/297-二叉树的序列化和反序列化.py | zhengsizuo/leetcode-zhs | train | 0 | |
09d6c44ee0c2938ed13e85a04ac9ea2886c4df5c | [
"if random.random() < 0.5:\n img = img.transpose(Image.FLIP_LEFT_RIGHT)\n w = img.width\n xmin = w - boxes[:, 2]\n xmax = w - boxes[:, 0]\n boxes[:, 0] = xmin\n boxes[:, 2] = xmax\nreturn (img, boxes)",
"w, h = img.size\nif isinstance(size, int):\n size_min = min(w, h)\n size_max = max(w, ... | <|body_start_0|>
if random.random() < 0.5:
img = img.transpose(Image.FLIP_LEFT_RIGHT)
w = img.width
xmin = w - boxes[:, 2]
xmax = w - boxes[:, 0]
boxes[:, 0] = xmin
boxes[:, 2] = xmax
return (img, boxes)
<|end_body_0|>
<|body_start... | ImageUtils | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageUtils:
def random_flip(img, boxes):
"""Randomly flip the given PIL Image. Args: img: (PIL Image) image to be flipped. boxes: (tensor) object boxes, sized [#ojb,4]. Returns: img: (PIL.Image) randomly flipped image. boxes: (tensor) randomly flipped boxes."""
<|body_0|>
de... | stack_v2_sparse_classes_75kplus_train_005135 | 13,367 | no_license | [
{
"docstring": "Randomly flip the given PIL Image. Args: img: (PIL Image) image to be flipped. boxes: (tensor) object boxes, sized [#ojb,4]. Returns: img: (PIL.Image) randomly flipped image. boxes: (tensor) randomly flipped boxes.",
"name": "random_flip",
"signature": "def random_flip(img, boxes)"
},
... | 4 | stack_v2_sparse_classes_30k_train_027000 | Implement the Python class `ImageUtils` described below.
Class description:
Implement the ImageUtils class.
Method signatures and docstrings:
- def random_flip(img, boxes): Randomly flip the given PIL Image. Args: img: (PIL Image) image to be flipped. boxes: (tensor) object boxes, sized [#ojb,4]. Returns: img: (PIL.I... | Implement the Python class `ImageUtils` described below.
Class description:
Implement the ImageUtils class.
Method signatures and docstrings:
- def random_flip(img, boxes): Randomly flip the given PIL Image. Args: img: (PIL Image) image to be flipped. boxes: (tensor) object boxes, sized [#ojb,4]. Returns: img: (PIL.I... | e2c06141e2ac1a382a4c7fc043a07e9f69a1f7e0 | <|skeleton|>
class ImageUtils:
def random_flip(img, boxes):
"""Randomly flip the given PIL Image. Args: img: (PIL Image) image to be flipped. boxes: (tensor) object boxes, sized [#ojb,4]. Returns: img: (PIL.Image) randomly flipped image. boxes: (tensor) randomly flipped boxes."""
<|body_0|>
de... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ImageUtils:
def random_flip(img, boxes):
"""Randomly flip the given PIL Image. Args: img: (PIL Image) image to be flipped. boxes: (tensor) object boxes, sized [#ojb,4]. Returns: img: (PIL.Image) randomly flipped image. boxes: (tensor) randomly flipped boxes."""
if random.random() < 0.5:
... | the_stack_v2_python_sparse | lib/pytorch/retinanet/utils.py | eglrp/BeginnerAI | train | 0 | |
c9d23ccbbd241589058809c5c823b47d63d95db3 | [
"self.table_names = []\nself.accepted_tables = []\nself.basic_tables = []\nself.badge_tables = []\nself.type_tables = []\nself.custom_tables = []\nself.pokemonByNumber = {}\nself.pokemonByName = {}\nself.__build_pokemon_list__\nself.__verify_database__\nself.__delete_unused_tables__",
"for pokemon in BOT.schema['... | <|body_start_0|>
self.table_names = []
self.accepted_tables = []
self.basic_tables = []
self.badge_tables = []
self.type_tables = []
self.custom_tables = []
self.pokemonByNumber = {}
self.pokemonByName = {}
self.__build_pokemon_list__
self.... | Validates the database is created with the expected tables | Storage | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Storage:
"""Validates the database is created with the expected tables"""
def __init__(self):
"""Initializes list to validate against"""
<|body_0|>
def __build_pokemon_list__(self):
"""Creates validation with the pokemon"""
<|body_1|>
def __verify_da... | stack_v2_sparse_classes_75kplus_train_005136 | 2,844 | permissive | [
{
"docstring": "Initializes list to validate against",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Creates validation with the pokemon",
"name": "__build_pokemon_list__",
"signature": "def __build_pokemon_list__(self)"
},
{
"docstring": "Creates any t... | 4 | stack_v2_sparse_classes_30k_train_050671 | Implement the Python class `Storage` described below.
Class description:
Validates the database is created with the expected tables
Method signatures and docstrings:
- def __init__(self): Initializes list to validate against
- def __build_pokemon_list__(self): Creates validation with the pokemon
- def __verify_databa... | Implement the Python class `Storage` described below.
Class description:
Validates the database is created with the expected tables
Method signatures and docstrings:
- def __init__(self): Initializes list to validate against
- def __build_pokemon_list__(self): Creates validation with the pokemon
- def __verify_databa... | b28775a348f400a98f54b6521ce57297ba538861 | <|skeleton|>
class Storage:
"""Validates the database is created with the expected tables"""
def __init__(self):
"""Initializes list to validate against"""
<|body_0|>
def __build_pokemon_list__(self):
"""Creates validation with the pokemon"""
<|body_1|>
def __verify_da... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Storage:
"""Validates the database is created with the expected tables"""
def __init__(self):
"""Initializes list to validate against"""
self.table_names = []
self.accepted_tables = []
self.basic_tables = []
self.badge_tables = []
self.type_tables = []
... | the_stack_v2_python_sparse | src/record_keeper/startup/storage.py | williamwissemann/record_keeper | train | 0 |
0ae025197d785c40794b1d6e1bc82989d1651cc7 | [
"self.collection_name = collection_name\nself.vault_secret_path = vault_secret_path\nvault_addr = os.getenv('VAULT_ADDR')\nif not vault_addr:\n raise RuntimeError('VAULT_ADDR not set')\nclient = hvac.Client(vault_addr)\ntoken = os.getenv('VAULT_TOKEN')\nif not token:\n github_token = os.getenv('GITHUB_TOKEN')... | <|body_start_0|>
self.collection_name = collection_name
self.vault_secret_path = vault_secret_path
vault_addr = os.getenv('VAULT_ADDR')
if not vault_addr:
raise RuntimeError('VAULT_ADDR not set')
client = hvac.Client(vault_addr)
token = os.getenv('VAULT_TOKEN'... | Extends MongoStore to read credentials out of Vault server and uses these values to initialize MongoStore instance | VaultStore | [
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-hdf5",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VaultStore:
"""Extends MongoStore to read credentials out of Vault server and uses these values to initialize MongoStore instance"""
def __init__(self, collection_name: str, vault_secret_path: str):
"""Args: collection_name: name of mongo collection vault_secret_path: path on vault s... | stack_v2_sparse_classes_75kplus_train_005137 | 18,118 | permissive | [
{
"docstring": "Args: collection_name: name of mongo collection vault_secret_path: path on vault server with mongo creds object Important: Environment variables that must be set prior to invocation VAULT_ADDR - URL of vault server (eg. https://matgen8.lbl.gov:8200) VAULT_TOKEN or GITHUB_TOKEN - token used to au... | 2 | stack_v2_sparse_classes_30k_train_008000 | Implement the Python class `VaultStore` described below.
Class description:
Extends MongoStore to read credentials out of Vault server and uses these values to initialize MongoStore instance
Method signatures and docstrings:
- def __init__(self, collection_name: str, vault_secret_path: str): Args: collection_name: na... | Implement the Python class `VaultStore` described below.
Class description:
Extends MongoStore to read credentials out of Vault server and uses these values to initialize MongoStore instance
Method signatures and docstrings:
- def __init__(self, collection_name: str, vault_secret_path: str): Args: collection_name: na... | 508c173df5b023f30dd8ebf2d348bd89b07abe7f | <|skeleton|>
class VaultStore:
"""Extends MongoStore to read credentials out of Vault server and uses these values to initialize MongoStore instance"""
def __init__(self, collection_name: str, vault_secret_path: str):
"""Args: collection_name: name of mongo collection vault_secret_path: path on vault s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VaultStore:
"""Extends MongoStore to read credentials out of Vault server and uses these values to initialize MongoStore instance"""
def __init__(self, collection_name: str, vault_secret_path: str):
"""Args: collection_name: name of mongo collection vault_secret_path: path on vault server with mo... | the_stack_v2_python_sparse | src/maggma/stores/advanced_stores.py | materialsproject/maggma | train | 29 |
663c1dbbc294e8c62e3a70a446e3662e3e563040 | [
"self.query = query\nself._query_regex = '.*?'.join((f'({escape(character)})' for character in query))\nself._query_regex_compiled = compile(self._query_regex)\nself._cache: LRUCache[str, float] = LRUCache(1024 * 4)",
"cached = self._cache.get(input)\nif cached is not None:\n return cached\nmatch = self._query... | <|body_start_0|>
self.query = query
self._query_regex = '.*?'.join((f'({escape(character)})' for character in query))
self._query_regex_compiled = compile(self._query_regex)
self._cache: LRUCache[str, float] = LRUCache(1024 * 4)
<|end_body_0|>
<|body_start_1|>
cached = self._cac... | A fuzzy matcher. | Matcher | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Matcher:
"""A fuzzy matcher."""
def __init__(self, query: str) -> None:
"""Args: query: A query as typed in by the user."""
<|body_0|>
def match(self, input: str) -> float:
"""Match the input against the query Args: input: Input string to match against. Returns: ... | stack_v2_sparse_classes_75kplus_train_005138 | 2,294 | permissive | [
{
"docstring": "Args: query: A query as typed in by the user.",
"name": "__init__",
"signature": "def __init__(self, query: str) -> None"
},
{
"docstring": "Match the input against the query Args: input: Input string to match against. Returns: Strength of the match from 0 to 1.",
"name": "ma... | 3 | null | Implement the Python class `Matcher` described below.
Class description:
A fuzzy matcher.
Method signatures and docstrings:
- def __init__(self, query: str) -> None: Args: query: A query as typed in by the user.
- def match(self, input: str) -> float: Match the input against the query Args: input: Input string to mat... | Implement the Python class `Matcher` described below.
Class description:
A fuzzy matcher.
Method signatures and docstrings:
- def __init__(self, query: str) -> None: Args: query: A query as typed in by the user.
- def match(self, input: str) -> float: Match the input against the query Args: input: Input string to mat... | b74ac1e47fdd16133ca567390c99ea19de278c5a | <|skeleton|>
class Matcher:
"""A fuzzy matcher."""
def __init__(self, query: str) -> None:
"""Args: query: A query as typed in by the user."""
<|body_0|>
def match(self, input: str) -> float:
"""Match the input against the query Args: input: Input string to match against. Returns: ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Matcher:
"""A fuzzy matcher."""
def __init__(self, query: str) -> None:
"""Args: query: A query as typed in by the user."""
self.query = query
self._query_regex = '.*?'.join((f'({escape(character)})' for character in query))
self._query_regex_compiled = compile(self._query... | the_stack_v2_python_sparse | src/textual/_fuzzy.py | Textualize/textual | train | 14,818 |
ee3c534ee682148d21573725a6d0d85d5f428acf | [
"res_set = set(A[0])\narr_size = len(A)\ncount_dict = {}\nres = []\nfor i in range(1, arr_size):\n res_set = set(A[i]) & res_set\n if len(res_set) != 0:\n i += 1\nfor char in res_set:\n count = A[0].count(char)\n for i in range(1, arr_size):\n count = min(A[i].count(char), count)\n ... | <|body_start_0|>
res_set = set(A[0])
arr_size = len(A)
count_dict = {}
res = []
for i in range(1, arr_size):
res_set = set(A[i]) & res_set
if len(res_set) != 0:
i += 1
for char in res_set:
count = A[0].count(char)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def commonChars(self, A):
""":type A: List[str] :rtype: List[str]"""
<|body_0|>
def commonChars2(self, words):
""":type words: List[str] :rtype: List[str]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res_set = set(A[0])
arr_size... | stack_v2_sparse_classes_75kplus_train_005139 | 2,410 | no_license | [
{
"docstring": ":type A: List[str] :rtype: List[str]",
"name": "commonChars",
"signature": "def commonChars(self, A)"
},
{
"docstring": ":type words: List[str] :rtype: List[str]",
"name": "commonChars2",
"signature": "def commonChars2(self, words)"
}
] | 2 | stack_v2_sparse_classes_30k_train_024857 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def commonChars(self, A): :type A: List[str] :rtype: List[str]
- def commonChars2(self, words): :type words: List[str] :rtype: List[str] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def commonChars(self, A): :type A: List[str] :rtype: List[str]
- def commonChars2(self, words): :type words: List[str] :rtype: List[str]
<|skeleton|>
class Solution:
def co... | 813235789ce422a3bab198317aafc46fbc61625e | <|skeleton|>
class Solution:
def commonChars(self, A):
""":type A: List[str] :rtype: List[str]"""
<|body_0|>
def commonChars2(self, words):
""":type words: List[str] :rtype: List[str]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def commonChars(self, A):
""":type A: List[str] :rtype: List[str]"""
res_set = set(A[0])
arr_size = len(A)
count_dict = {}
res = []
for i in range(1, arr_size):
res_set = set(A[i]) & res_set
if len(res_set) != 0:
... | the_stack_v2_python_sparse | 2.SET/e1002_Find Common Characters/solution.py | kimmyoo/python_leetcode | train | 1 | |
d475827d8d8f8f7bb532b4e222713b2ba86ecc1f | [
"if n == 1:\n return True\nwhile n:\n n /= 2.0\n print(n)\n if n == 1:\n return True\n elif n < 1:\n break\nreturn False",
"if n != 0 and n & n - 1 == 0:\n return True\nelse:\n return False"
] | <|body_start_0|>
if n == 1:
return True
while n:
n /= 2.0
print(n)
if n == 1:
return True
elif n < 1:
break
return False
<|end_body_0|>
<|body_start_1|>
if n != 0 and n & n - 1 == 0:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isPowerOfTwo(self, n):
""":type n: int :rtype: bool"""
<|body_0|>
def isPowerOfTwo1(self, n):
""":type n: int :rtype: bool 位运算 特点是有且仅有一个位为1的二进制"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if n == 1:
return True
... | stack_v2_sparse_classes_75kplus_train_005140 | 776 | no_license | [
{
"docstring": ":type n: int :rtype: bool",
"name": "isPowerOfTwo",
"signature": "def isPowerOfTwo(self, n)"
},
{
"docstring": ":type n: int :rtype: bool 位运算 特点是有且仅有一个位为1的二进制",
"name": "isPowerOfTwo1",
"signature": "def isPowerOfTwo1(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021067 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPowerOfTwo(self, n): :type n: int :rtype: bool
- def isPowerOfTwo1(self, n): :type n: int :rtype: bool 位运算 特点是有且仅有一个位为1的二进制 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPowerOfTwo(self, n): :type n: int :rtype: bool
- def isPowerOfTwo1(self, n): :type n: int :rtype: bool 位运算 特点是有且仅有一个位为1的二进制
<|skeleton|>
class Solution:
def isPowerOf... | 069bb0b751ef7f469036b9897436eb5d138ffa24 | <|skeleton|>
class Solution:
def isPowerOfTwo(self, n):
""":type n: int :rtype: bool"""
<|body_0|>
def isPowerOfTwo1(self, n):
""":type n: int :rtype: bool 位运算 特点是有且仅有一个位为1的二进制"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def isPowerOfTwo(self, n):
""":type n: int :rtype: bool"""
if n == 1:
return True
while n:
n /= 2.0
print(n)
if n == 1:
return True
elif n < 1:
break
return False
def isPo... | the_stack_v2_python_sparse | 算法/位运算/2的幂.py | RichieSong/algorithm | train | 0 | |
b587cb668f5e1e3ba09761e1bea04d15bcbd72a9 | [
"super().__init__(entry, account, zone, entity_description)\nself._attr_state: StateType = None\nself._old_state: StateType = None",
"if last_state is not None:\n self._attr_state = last_state.state\nif self.state == STATE_UNAVAILABLE:\n self._attr_available = False",
"new_state = None\nif sia_event.code:... | <|body_start_0|>
super().__init__(entry, account, zone, entity_description)
self._attr_state: StateType = None
self._old_state: StateType = None
<|end_body_0|>
<|body_start_1|>
if last_state is not None:
self._attr_state = last_state.state
if self.state == STATE_UNAV... | Class for SIA Alarm Control Panels. | SIAAlarmControlPanel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SIAAlarmControlPanel:
"""Class for SIA Alarm Control Panels."""
def __init__(self, entry: ConfigEntry, account: str, zone: int, entity_description: SIAAlarmControlPanelEntityDescription) -> None:
"""Create SIAAlarmControlPanel object."""
<|body_0|>
def handle_last_state(... | stack_v2_sparse_classes_75kplus_train_005141 | 4,240 | permissive | [
{
"docstring": "Create SIAAlarmControlPanel object.",
"name": "__init__",
"signature": "def __init__(self, entry: ConfigEntry, account: str, zone: int, entity_description: SIAAlarmControlPanelEntityDescription) -> None"
},
{
"docstring": "Handle the last state.",
"name": "handle_last_state",... | 3 | stack_v2_sparse_classes_30k_train_017818 | Implement the Python class `SIAAlarmControlPanel` described below.
Class description:
Class for SIA Alarm Control Panels.
Method signatures and docstrings:
- def __init__(self, entry: ConfigEntry, account: str, zone: int, entity_description: SIAAlarmControlPanelEntityDescription) -> None: Create SIAAlarmControlPanel ... | Implement the Python class `SIAAlarmControlPanel` described below.
Class description:
Class for SIA Alarm Control Panels.
Method signatures and docstrings:
- def __init__(self, entry: ConfigEntry, account: str, zone: int, entity_description: SIAAlarmControlPanelEntityDescription) -> None: Create SIAAlarmControlPanel ... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class SIAAlarmControlPanel:
"""Class for SIA Alarm Control Panels."""
def __init__(self, entry: ConfigEntry, account: str, zone: int, entity_description: SIAAlarmControlPanelEntityDescription) -> None:
"""Create SIAAlarmControlPanel object."""
<|body_0|>
def handle_last_state(... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SIAAlarmControlPanel:
"""Class for SIA Alarm Control Panels."""
def __init__(self, entry: ConfigEntry, account: str, zone: int, entity_description: SIAAlarmControlPanelEntityDescription) -> None:
"""Create SIAAlarmControlPanel object."""
super().__init__(entry, account, zone, entity_descr... | the_stack_v2_python_sparse | homeassistant/components/sia/alarm_control_panel.py | home-assistant/core | train | 35,501 |
4a1792f57ca9ead8c16f0e69bb8fe5a6185a7362 | [
"Variable.__init__(self, program, name, gtype)\nself._size = 0\nself._generic = False",
"if type(data) in (float, int) or (type(data) in (tuple, list) and len(data) in [1, 2, 3, 4]):\n _, _, dtype = gl_typeinfo[self._gtype]\n self._data = np.array(data).astype(dtype)\n self._generic = True\n self._dir... | <|body_start_0|>
Variable.__init__(self, program, name, gtype)
self._size = 0
self._generic = False
<|end_body_0|>
<|body_start_1|>
if type(data) in (float, int) or (type(data) in (tuple, list) and len(data) in [1, 2, 3, 4]):
_, _, dtype = gl_typeinfo[self._gtype]
... | An Attribute represents a program attribute variable. | Attribute | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Attribute:
"""An Attribute represents a program attribute variable."""
def __init__(self, program, name, gtype):
"""Initialize the input into default state"""
<|body_0|>
def set_data(self, data):
"""Set data (no upload)"""
<|body_1|>
def upload_data(... | stack_v2_sparse_classes_75kplus_train_005142 | 13,024 | no_license | [
{
"docstring": "Initialize the input into default state",
"name": "__init__",
"signature": "def __init__(self, program, name, gtype)"
},
{
"docstring": "Set data (no upload)",
"name": "set_data",
"signature": "def set_data(self, data)"
},
{
"docstring": "Actual upload of data to ... | 5 | null | Implement the Python class `Attribute` described below.
Class description:
An Attribute represents a program attribute variable.
Method signatures and docstrings:
- def __init__(self, program, name, gtype): Initialize the input into default state
- def set_data(self, data): Set data (no upload)
- def upload_data(self... | Implement the Python class `Attribute` described below.
Class description:
An Attribute represents a program attribute variable.
Method signatures and docstrings:
- def __init__(self, program, name, gtype): Initialize the input into default state
- def set_data(self, data): Set data (no upload)
- def upload_data(self... | 67c8e5ca533edbd4af884eb5f2db65bb704605a7 | <|skeleton|>
class Attribute:
"""An Attribute represents a program attribute variable."""
def __init__(self, program, name, gtype):
"""Initialize the input into default state"""
<|body_0|>
def set_data(self, data):
"""Set data (no upload)"""
<|body_1|>
def upload_data(... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Attribute:
"""An Attribute represents a program attribute variable."""
def __init__(self, program, name, gtype):
"""Initialize the input into default state"""
Variable.__init__(self, program, name, gtype)
self._size = 0
self._generic = False
def set_data(self, data):
... | the_stack_v2_python_sparse | review/variable.py | tatak/experimental | train | 0 |
598bd8710d798a2f204357b21b063dd2a692bc86 | [
"m = len(nums)\nif not m:\n return False\nif m == 1:\n return nums[0] == target\nreturn self.helper(nums, 0, m - 1, target)",
"if l > h:\n return False\nmid = l + (h - l) // 2\nif nums[mid] == target:\n return True\nif nums[l] < nums[mid]:\n if nums[l] <= target < nums[mid]:\n return self.he... | <|body_start_0|>
m = len(nums)
if not m:
return False
if m == 1:
return nums[0] == target
return self.helper(nums, 0, m - 1, target)
<|end_body_0|>
<|body_start_1|>
if l > h:
return False
mid = l + (h - l) // 2
if nums[mid] == ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def search(self, nums, target):
""":type nums: List[int] :type target: int :rtype: bool"""
<|body_0|>
def helper(self, nums, l, h, target):
"""search nums[l:h+1] for target"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
m = len(nums)
... | stack_v2_sparse_classes_75kplus_train_005143 | 1,191 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: bool",
"name": "search",
"signature": "def search(self, nums, target)"
},
{
"docstring": "search nums[l:h+1] for target",
"name": "helper",
"signature": "def helper(self, nums, l, h, target)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def search(self, nums, target): :type nums: List[int] :type target: int :rtype: bool
- def helper(self, nums, l, h, target): search nums[l:h+1] for target | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def search(self, nums, target): :type nums: List[int] :type target: int :rtype: bool
- def helper(self, nums, l, h, target): search nums[l:h+1] for target
<|skeleton|>
class Sol... | e00cf94c5b86c8cca27e3bee69ad21e727b7679b | <|skeleton|>
class Solution:
def search(self, nums, target):
""":type nums: List[int] :type target: int :rtype: bool"""
<|body_0|>
def helper(self, nums, l, h, target):
"""search nums[l:h+1] for target"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def search(self, nums, target):
""":type nums: List[int] :type target: int :rtype: bool"""
m = len(nums)
if not m:
return False
if m == 1:
return nums[0] == target
return self.helper(nums, 0, m - 1, target)
def helper(self, nums, l... | the_stack_v2_python_sparse | interview/prob81.py | binchen15/leet-python | train | 1 | |
40807440b4d7967388768f4bcfe406339d3994b0 | [
"self._n = n\nif estimator is None:\n if n > 1:\n probdist_factory = lambda fdist, bins, n_train, n_0: NeyProbDist(fdist, bins, n_train, n_0, factor, NeyProbDist.ABSOLUTE)\n else:\n probdist_factory = lambda fdist, bins, *args: LaplaceProbDist(fdist, bins)\nelse:\n probdist_factory = estimato... | <|body_start_0|>
self._n = n
if estimator is None:
if n > 1:
probdist_factory = lambda fdist, bins, n_train, n_0: NeyProbDist(fdist, bins, n_train, n_0, factor, NeyProbDist.ABSOLUTE)
else:
probdist_factory = lambda fdist, bins, *args: LaplaceProbDi... | NgramModel with Simple Linear Interpolation | SLINgramModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SLINgramModel:
"""NgramModel with Simple Linear Interpolation"""
def __init__(self, n, train, estimator=None, factor=0.77):
"""Creates an ngram language model to capture patterns in n consecutive words of training text. An estimator smooths the probabilities derived from the text and... | stack_v2_sparse_classes_75kplus_train_005144 | 5,493 | no_license | [
{
"docstring": "Creates an ngram language model to capture patterns in n consecutive words of training text. An estimator smooths the probabilities derived from the text and may allow generation of ngrams not seen during training. @param n: the order of the language model (ngram size) @type n: C{int} @param tra... | 2 | stack_v2_sparse_classes_30k_train_024357 | Implement the Python class `SLINgramModel` described below.
Class description:
NgramModel with Simple Linear Interpolation
Method signatures and docstrings:
- def __init__(self, n, train, estimator=None, factor=0.77): Creates an ngram language model to capture patterns in n consecutive words of training text. An esti... | Implement the Python class `SLINgramModel` described below.
Class description:
NgramModel with Simple Linear Interpolation
Method signatures and docstrings:
- def __init__(self, n, train, estimator=None, factor=0.77): Creates an ngram language model to capture patterns in n consecutive words of training text. An esti... | ae5e54713648e32d5a8498fc3e7f6e94cddb1b6d | <|skeleton|>
class SLINgramModel:
"""NgramModel with Simple Linear Interpolation"""
def __init__(self, n, train, estimator=None, factor=0.77):
"""Creates an ngram language model to capture patterns in n consecutive words of training text. An estimator smooths the probabilities derived from the text and... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SLINgramModel:
"""NgramModel with Simple Linear Interpolation"""
def __init__(self, n, train, estimator=None, factor=0.77):
"""Creates an ngram language model to capture patterns in n consecutive words of training text. An estimator smooths the probabilities derived from the text and may allow ge... | the_stack_v2_python_sparse | NLP/20ng/src/model.py | tehf0x/gabe-and-joh | train | 0 |
f306310788e9494379a68b27d33292b674a470f7 | [
"super(PostProcessor, self).__init__()\nself.score_thresh = score_thresh\nself.nms = nms\nself.detections_per_img = detections_per_img\nif box_coder is None:\n box_coder = BoxCoder3D(weights=(10.0, 10.0, 5.0, 5.0))\nself.box_coder = box_coder\nself.nms_aug_thickness = nms_aug_thickness",
"class_logits, box_reg... | <|body_start_0|>
super(PostProcessor, self).__init__()
self.score_thresh = score_thresh
self.nms = nms
self.detections_per_img = detections_per_img
if box_coder is None:
box_coder = BoxCoder3D(weights=(10.0, 10.0, 5.0, 5.0))
self.box_coder = box_coder
... | From a set of classification scores, box regression and proposals, computes the post-processed boxes, and applies NMS to obtain the final results | PostProcessor | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PostProcessor:
"""From a set of classification scores, box regression and proposals, computes the post-processed boxes, and applies NMS to obtain the final results"""
def __init__(self, score_thresh=0.05, nms=0.5, nms_aug_thickness=None, detections_per_img=100, box_coder=None):
"""Ar... | stack_v2_sparse_classes_75kplus_train_005145 | 6,867 | permissive | [
{
"docstring": "Arguments: score_thresh (float) nms (float) detections_per_img (int) box_coder (BoxCoder3D)",
"name": "__init__",
"signature": "def __init__(self, score_thresh=0.05, nms=0.5, nms_aug_thickness=None, detections_per_img=100, box_coder=None)"
},
{
"docstring": "Arguments: x (tuple[t... | 4 | stack_v2_sparse_classes_30k_train_040116 | Implement the Python class `PostProcessor` described below.
Class description:
From a set of classification scores, box regression and proposals, computes the post-processed boxes, and applies NMS to obtain the final results
Method signatures and docstrings:
- def __init__(self, score_thresh=0.05, nms=0.5, nms_aug_th... | Implement the Python class `PostProcessor` described below.
Class description:
From a set of classification scores, box regression and proposals, computes the post-processed boxes, and applies NMS to obtain the final results
Method signatures and docstrings:
- def __init__(self, score_thresh=0.05, nms=0.5, nms_aug_th... | 2fead7b8d754912a53fed6c5826d4d898a520237 | <|skeleton|>
class PostProcessor:
"""From a set of classification scores, box regression and proposals, computes the post-processed boxes, and applies NMS to obtain the final results"""
def __init__(self, score_thresh=0.05, nms=0.5, nms_aug_thickness=None, detections_per_img=100, box_coder=None):
"""Ar... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PostProcessor:
"""From a set of classification scores, box regression and proposals, computes the post-processed boxes, and applies NMS to obtain the final results"""
def __init__(self, score_thresh=0.05, nms=0.5, nms_aug_thickness=None, detections_per_img=100, box_coder=None):
"""Arguments: scor... | the_stack_v2_python_sparse | maskrcnn_benchmark/modeling/roi_heads/box_head_3d/inference.py | zhupan007/Detection_3D | train | 1 |
34e6329a748f83783eadd3b3e3209d0023265c6e | [
"self.input_spectrum = input_spectrum\nself.failure = False\nself.tasks_which_failed = []\nself.intermediate_results = []\nself.spectrum_by_task_name = {}\nself.metadata_by_task_name = {}",
"self.intermediate_results.append(output_spectrum)\nself.spectrum_by_task_name[task_name] = output_spectrum\nself.metadata_b... | <|body_start_0|>
self.input_spectrum = input_spectrum
self.failure = False
self.tasks_which_failed = []
self.intermediate_results = []
self.spectrum_by_task_name = {}
self.metadata_by_task_name = {}
<|end_body_0|>
<|body_start_1|>
self.intermediate_results.append... | Class which is created by the `Pipeline` class, and represents the analysis of a particular spectrum. | SpectrumAnalysis | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpectrumAnalysis:
"""Class which is created by the `Pipeline` class, and represents the analysis of a particular spectrum."""
def __init__(self, input_spectrum):
"""Class which represents the analysis of a particular spectrum. :param input_spectrum: The Spectrum object we are to anal... | stack_v2_sparse_classes_75kplus_train_005146 | 2,217 | permissive | [
{
"docstring": "Class which represents the analysis of a particular spectrum. :param input_spectrum: The Spectrum object we are to analyse. :type input_spectrum: Spectrum",
"name": "__init__",
"signature": "def __init__(self, input_spectrum)"
},
{
"docstring": "Store the output from some pipelin... | 3 | stack_v2_sparse_classes_30k_train_027254 | Implement the Python class `SpectrumAnalysis` described below.
Class description:
Class which is created by the `Pipeline` class, and represents the analysis of a particular spectrum.
Method signatures and docstrings:
- def __init__(self, input_spectrum): Class which represents the analysis of a particular spectrum. ... | Implement the Python class `SpectrumAnalysis` described below.
Class description:
Class which is created by the `Pipeline` class, and represents the analysis of a particular spectrum.
Method signatures and docstrings:
- def __init__(self, input_spectrum): Class which represents the analysis of a particular spectrum. ... | 0421d76791315aa3ca8ff9e4bd2e37ad36c0141f | <|skeleton|>
class SpectrumAnalysis:
"""Class which is created by the `Pipeline` class, and represents the analysis of a particular spectrum."""
def __init__(self, input_spectrum):
"""Class which represents the analysis of a particular spectrum. :param input_spectrum: The Spectrum object we are to anal... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SpectrumAnalysis:
"""Class which is created by the `Pipeline` class, and represents the analysis of a particular spectrum."""
def __init__(self, input_spectrum):
"""Class which represents the analysis of a particular spectrum. :param input_spectrum: The Spectrum object we are to analyse. :type in... | the_stack_v2_python_sparse | src/pythonModules/fourgp_pipeline/fourgp_pipeline/spectrum_analysis.py | dcf21/4most-4gp | train | 1 |
d609e01f6e915ca8e050b5c402d04d3fa94858cc | [
"super().__init__(**kwargs)\nself.base_url = 'https://www.filmweb.pl'\nquery_part = '/search?q={title}'\nself.output = output\nself.start_urls.append(self.base_url + query_part.format(title=title))",
"href = response.xpath(\"//div[@id='searchResult']/descendant::a[@class='poster__link'][1]/@href\").get()\nif href... | <|body_start_0|>
super().__init__(**kwargs)
self.base_url = 'https://www.filmweb.pl'
query_part = '/search?q={title}'
self.output = output
self.start_urls.append(self.base_url + query_part.format(title=title))
<|end_body_0|>
<|body_start_1|>
href = response.xpath("//div[... | Movie spider for parsing basic information about movies. Attributes ---------- name : str name of the spider custom_settings : dict custom settings for the spider base_url : str base url of the site from which data will be parsed output : list list for holding parse result start_urls : list list for holding site urls t... | MovieSpider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MovieSpider:
"""Movie spider for parsing basic information about movies. Attributes ---------- name : str name of the spider custom_settings : dict custom settings for the spider base_url : str base url of the site from which data will be parsed output : list list for holding parse result start_u... | stack_v2_sparse_classes_75kplus_train_005147 | 4,494 | no_license | [
{
"docstring": "Constructs all the necessary attributes for the spider. Parameters ---------- title : str title of the movie to be parsed output : list used for storing parse result",
"name": "__init__",
"signature": "def __init__(self, title, output, **kwargs)"
},
{
"docstring": "Parses informa... | 4 | stack_v2_sparse_classes_30k_train_032190 | Implement the Python class `MovieSpider` described below.
Class description:
Movie spider for parsing basic information about movies. Attributes ---------- name : str name of the spider custom_settings : dict custom settings for the spider base_url : str base url of the site from which data will be parsed output : lis... | Implement the Python class `MovieSpider` described below.
Class description:
Movie spider for parsing basic information about movies. Attributes ---------- name : str name of the spider custom_settings : dict custom settings for the spider base_url : str base url of the site from which data will be parsed output : lis... | 16e327e0e4d23f43410ead5426cf5a6caea7a12f | <|skeleton|>
class MovieSpider:
"""Movie spider for parsing basic information about movies. Attributes ---------- name : str name of the spider custom_settings : dict custom settings for the spider base_url : str base url of the site from which data will be parsed output : list list for holding parse result start_u... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MovieSpider:
"""Movie spider for parsing basic information about movies. Attributes ---------- name : str name of the spider custom_settings : dict custom settings for the spider base_url : str base url of the site from which data will be parsed output : list list for holding parse result start_urls : list li... | the_stack_v2_python_sparse | lab-4/util/scraper/movie_spider.py | WuTolas/pjwstk-nai | train | 0 |
652a1e2e8b6505c8509e78e302d308bdd1f23802 | [
"max_texture_size = pyglet.image.get_max_texture_size()\nwidth = min(width, max_texture_size)\nheight = min(height, max_texture_size)\nself.texture = pyglet.image.Texture.create(width, height)\nself.allocator = Allocator(width, height)",
"x, y = self.allocator.alloc(img.width + border * 2, img.height + border * 2... | <|body_start_0|>
max_texture_size = pyglet.image.get_max_texture_size()
width = min(width, max_texture_size)
height = min(height, max_texture_size)
self.texture = pyglet.image.Texture.create(width, height)
self.allocator = Allocator(width, height)
<|end_body_0|>
<|body_start_1|>... | Collection of images within a texture. | TextureAtlas | [
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TextureAtlas:
"""Collection of images within a texture."""
def __init__(self, width: int=2048, height: int=2048) -> None:
"""Create a texture atlas of the given size. :Parameters: `width` : int Width of the underlying texture. `height` : int Height of the underlying texture."""
... | stack_v2_sparse_classes_75kplus_train_005148 | 10,284 | permissive | [
{
"docstring": "Create a texture atlas of the given size. :Parameters: `width` : int Width of the underlying texture. `height` : int Height of the underlying texture.",
"name": "__init__",
"signature": "def __init__(self, width: int=2048, height: int=2048) -> None"
},
{
"docstring": "Add an imag... | 2 | stack_v2_sparse_classes_30k_test_000784 | Implement the Python class `TextureAtlas` described below.
Class description:
Collection of images within a texture.
Method signatures and docstrings:
- def __init__(self, width: int=2048, height: int=2048) -> None: Create a texture atlas of the given size. :Parameters: `width` : int Width of the underlying texture. ... | Implement the Python class `TextureAtlas` described below.
Class description:
Collection of images within a texture.
Method signatures and docstrings:
- def __init__(self, width: int=2048, height: int=2048) -> None: Create a texture atlas of the given size. :Parameters: `width` : int Width of the underlying texture. ... | 094c638f0529fecab4e74556487b92453a78753c | <|skeleton|>
class TextureAtlas:
"""Collection of images within a texture."""
def __init__(self, width: int=2048, height: int=2048) -> None:
"""Create a texture atlas of the given size. :Parameters: `width` : int Width of the underlying texture. `height` : int Height of the underlying texture."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TextureAtlas:
"""Collection of images within a texture."""
def __init__(self, width: int=2048, height: int=2048) -> None:
"""Create a texture atlas of the given size. :Parameters: `width` : int Width of the underlying texture. `height` : int Height of the underlying texture."""
max_textur... | the_stack_v2_python_sparse | pyglet/image/atlas.py | pyglet/pyglet | train | 1,687 |
c7ab3cf0404fe5ac98dc54572ddb24dd26a58afa | [
"self.capacity = capacity\nself.queue = deque()\nself.items = {}",
"if key in self.items:\n self.queue.remove(key)\n self.queue.appendleft(key)\n return self.items[key]\nelse:\n return -1",
"if key in self.items:\n self.queue.remove(key)\nelif len(self.queue) == self.capacity:\n del self.items... | <|body_start_0|>
self.capacity = capacity
self.queue = deque()
self.items = {}
<|end_body_0|>
<|body_start_1|>
if key in self.items:
self.queue.remove(key)
self.queue.appendleft(key)
return self.items[key]
else:
return -1
<|end_bod... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: None"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_75kplus_train_005149 | 1,103 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: None",
"name": "pu... | 3 | stack_v2_sparse_classes_30k_train_047366 | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: None | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: None
<|sk... | 3e66f89e02ade703715237722eda2fa2b135bb79 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: None"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.capacity = capacity
self.queue = deque()
self.items = {}
def get(self, key):
""":type key: int :rtype: int"""
if key in self.items:
self.queue.remove(key)
self.qu... | the_stack_v2_python_sparse | Amazon/Design/LRUCache.py | sameersaini/hackerank | train | 0 | |
d65bec5d7bf6d022f0e3faabb8f4b54a381bde70 | [
"self.head = Node(value) if value else None\nself.tail = self.head if self.head else None\nself.length = 1 if value else 0",
"if not new_value:\n return False\nelif self.tail:\n isAdded = self.tail.add_value(new_value)\n self.tail = self.tail.next_node\n self.length += 1\n return isAdded\nelse:\n ... | <|body_start_0|>
self.head = Node(value) if value else None
self.tail = self.head if self.head else None
self.length = 1 if value else 0
<|end_body_0|>
<|body_start_1|>
if not new_value:
return False
elif self.tail:
isAdded = self.tail.add_value(new_value... | DoublyLinkedList | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DoublyLinkedList:
def __init__(self, value=None):
"""Constructor for instantiating a new Doubly-Linked List"""
<|body_0|>
def add_value(self, new_value=None):
"""Adds a new value to the Doubly-Linked List"""
<|body_1|>
def sort_list(self):
"""Sor... | stack_v2_sparse_classes_75kplus_train_005150 | 4,372 | permissive | [
{
"docstring": "Constructor for instantiating a new Doubly-Linked List",
"name": "__init__",
"signature": "def __init__(self, value=None)"
},
{
"docstring": "Adds a new value to the Doubly-Linked List",
"name": "add_value",
"signature": "def add_value(self, new_value=None)"
},
{
... | 5 | stack_v2_sparse_classes_30k_train_005216 | Implement the Python class `DoublyLinkedList` described below.
Class description:
Implement the DoublyLinkedList class.
Method signatures and docstrings:
- def __init__(self, value=None): Constructor for instantiating a new Doubly-Linked List
- def add_value(self, new_value=None): Adds a new value to the Doubly-Linke... | Implement the Python class `DoublyLinkedList` described below.
Class description:
Implement the DoublyLinkedList class.
Method signatures and docstrings:
- def __init__(self, value=None): Constructor for instantiating a new Doubly-Linked List
- def add_value(self, new_value=None): Adds a new value to the Doubly-Linke... | 27ffb6b32d6d18d279c51cfa45bf305a409be5c2 | <|skeleton|>
class DoublyLinkedList:
def __init__(self, value=None):
"""Constructor for instantiating a new Doubly-Linked List"""
<|body_0|>
def add_value(self, new_value=None):
"""Adds a new value to the Doubly-Linked List"""
<|body_1|>
def sort_list(self):
"""Sor... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DoublyLinkedList:
def __init__(self, value=None):
"""Constructor for instantiating a new Doubly-Linked List"""
self.head = Node(value) if value else None
self.tail = self.head if self.head else None
self.length = 1 if value else 0
def add_value(self, new_value=None):
... | the_stack_v2_python_sparse | src/daily-coding-problem/medium/sort-linked-list/sort_linked_list.py | nwthomas/code-challenges | train | 2 | |
d9b2f806e02e5ff9c3684f81a39433062192827f | [
"if User.objects.filter(username=username).exists():\n return\nuser_info = usermgr.retrieve_user(username)\nuser, is_created = User.objects.get_or_create(id=user_info['id'], defaults={'username': user_info['username'], 'display_name': user_info['display_name'] or user_info['username'], 'staff_status': user_info[... | <|body_start_0|>
if User.objects.filter(username=username).exists():
return
user_info = usermgr.retrieve_user(username)
user, is_created = User.objects.get_or_create(id=user_info['id'], defaults={'username': user_info['username'], 'display_name': user_info['display_name'] or user_inf... | 组织架构同步 需要特别注意同步任务间是否有冲突 | Syncer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Syncer:
"""组织架构同步 需要特别注意同步任务间是否有冲突"""
def sync_single_user(self, username):
"""单一用户同步(后续可以添加with_relation=True参数同步用户的相关部门和leader等) # NOTE:被migration(organization.0004_auto_20201230_1653)调用到了 # 如果有调整,需要注意是否需要调整migration,避免出现循环依赖导致migrate失败 # 目前依赖1张表:User"""
<|body_0|>
def... | stack_v2_sparse_classes_75kplus_train_005151 | 4,204 | permissive | [
{
"docstring": "单一用户同步(后续可以添加with_relation=True参数同步用户的相关部门和leader等) # NOTE:被migration(organization.0004_auto_20201230_1653)调用到了 # 如果有调整,需要注意是否需要调整migration,避免出现循环依赖导致migrate失败 # 目前依赖1张表:User",
"name": "sync_single_user",
"signature": "def sync_single_user(self, username)"
},
{
"docstring": "执行新增... | 2 | stack_v2_sparse_classes_30k_val_001251 | Implement the Python class `Syncer` described below.
Class description:
组织架构同步 需要特别注意同步任务间是否有冲突
Method signatures and docstrings:
- def sync_single_user(self, username): 单一用户同步(后续可以添加with_relation=True参数同步用户的相关部门和leader等) # NOTE:被migration(organization.0004_auto_20201230_1653)调用到了 # 如果有调整,需要注意是否需要调整migration,避免出现循环依赖... | Implement the Python class `Syncer` described below.
Class description:
组织架构同步 需要特别注意同步任务间是否有冲突
Method signatures and docstrings:
- def sync_single_user(self, username): 单一用户同步(后续可以添加with_relation=True参数同步用户的相关部门和leader等) # NOTE:被migration(organization.0004_auto_20201230_1653)调用到了 # 如果有调整,需要注意是否需要调整migration,避免出现循环依赖... | 33c8f4ffe8697081abcfc5771b98a88c0578059f | <|skeleton|>
class Syncer:
"""组织架构同步 需要特别注意同步任务间是否有冲突"""
def sync_single_user(self, username):
"""单一用户同步(后续可以添加with_relation=True参数同步用户的相关部门和leader等) # NOTE:被migration(organization.0004_auto_20201230_1653)调用到了 # 如果有调整,需要注意是否需要调整migration,避免出现循环依赖导致migrate失败 # 目前依赖1张表:User"""
<|body_0|>
def... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Syncer:
"""组织架构同步 需要特别注意同步任务间是否有冲突"""
def sync_single_user(self, username):
"""单一用户同步(后续可以添加with_relation=True参数同步用户的相关部门和leader等) # NOTE:被migration(organization.0004_auto_20201230_1653)调用到了 # 如果有调整,需要注意是否需要调整migration,避免出现循环依赖导致migrate失败 # 目前依赖1张表:User"""
if User.objects.filter(username=... | the_stack_v2_python_sparse | saas/backend/biz/org_sync/syncer.py | robert871126/bk-iam-saas | train | 0 |
95222bd770309a5e6469d00db2b1d4b50e6b8526 | [
"if view.settings().get('calendar_current', None) is not None and view.settings().get('calendar_today', None) is not None:\n if key == 'calendar_view':\n return True\nreturn False",
"if not TOOLTIP_SUPPORT or hover_zone != sublime.HOVER_TEXT or (not sublime.load_settings('quickcal.sublime-settings').get... | <|body_start_0|>
if view.settings().get('calendar_current', None) is not None and view.settings().get('calendar_today', None) is not None:
if key == 'calendar_view':
return True
return False
<|end_body_0|>
<|body_start_1|>
if not TOOLTIP_SUPPORT or hover_zone != subl... | Listen for Calendar shortcuts. | CalendarEventListener | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CalendarEventListener:
"""Listen for Calendar shortcuts."""
def on_query_context(self, view, key, operator, operand, match_all):
"""Handle Calendar shortcuts."""
<|body_0|>
def on_hover(self, view, point, hover_zone):
"""On Hover calendar."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_005152 | 23,985 | permissive | [
{
"docstring": "Handle Calendar shortcuts.",
"name": "on_query_context",
"signature": "def on_query_context(self, view, key, operator, operand, match_all)"
},
{
"docstring": "On Hover calendar.",
"name": "on_hover",
"signature": "def on_hover(self, view, point, hover_zone)"
},
{
... | 5 | null | Implement the Python class `CalendarEventListener` described below.
Class description:
Listen for Calendar shortcuts.
Method signatures and docstrings:
- def on_query_context(self, view, key, operator, operand, match_all): Handle Calendar shortcuts.
- def on_hover(self, view, point, hover_zone): On Hover calendar.
- ... | Implement the Python class `CalendarEventListener` described below.
Class description:
Listen for Calendar shortcuts.
Method signatures and docstrings:
- def on_query_context(self, view, key, operator, operand, match_all): Handle Calendar shortcuts.
- def on_hover(self, view, point, hover_zone): On Hover calendar.
- ... | e22d13dc79a7e3403e4f12ceb2e9c5a98bd853c6 | <|skeleton|>
class CalendarEventListener:
"""Listen for Calendar shortcuts."""
def on_query_context(self, view, key, operator, operand, match_all):
"""Handle Calendar shortcuts."""
<|body_0|>
def on_hover(self, view, point, hover_zone):
"""On Hover calendar."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CalendarEventListener:
"""Listen for Calendar shortcuts."""
def on_query_context(self, view, key, operator, operand, match_all):
"""Handle Calendar shortcuts."""
if view.settings().get('calendar_current', None) is not None and view.settings().get('calendar_today', None) is not None:
... | the_stack_v2_python_sparse | quickcal.py | facelessuser/QuickCal | train | 8 |
5fa30f70e990648178b4b7d54319d16b3ca33f6e | [
"self.paths = paths\nself.recursive = recursive\nif self.paths is None:\n self.paths = []\nsuper(FilesystemCollector, self).__init__()",
"for path in self.paths:\n for base, directories, filenames in os.walk(path):\n for filename in filenames:\n _, extension = os.path.splitext(filename)\n ... | <|body_start_0|>
self.paths = paths
self.recursive = recursive
if self.paths is None:
self.paths = []
super(FilesystemCollector, self).__init__()
<|end_body_0|>
<|body_start_1|>
for path in self.paths:
for base, directories, filenames in os.walk(path):
... | FilesystemCollector | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FilesystemCollector:
def __init__(self, paths=None, recursive=True):
"""Initialise with *paths* to search. If *recursive* is True then all subdirectories of *paths* will also be searched."""
<|body_0|>
def collect(self):
"""Yield collected schemas."""
<|body_... | stack_v2_sparse_classes_75kplus_train_005153 | 1,630 | permissive | [
{
"docstring": "Initialise with *paths* to search. If *recursive* is True then all subdirectories of *paths* will also be searched.",
"name": "__init__",
"signature": "def __init__(self, paths=None, recursive=True)"
},
{
"docstring": "Yield collected schemas.",
"name": "collect",
"signat... | 2 | stack_v2_sparse_classes_30k_train_027203 | Implement the Python class `FilesystemCollector` described below.
Class description:
Implement the FilesystemCollector class.
Method signatures and docstrings:
- def __init__(self, paths=None, recursive=True): Initialise with *paths* to search. If *recursive* is True then all subdirectories of *paths* will also be se... | Implement the Python class `FilesystemCollector` described below.
Class description:
Implement the FilesystemCollector class.
Method signatures and docstrings:
- def __init__(self, paths=None, recursive=True): Initialise with *paths* to search. If *recursive* is True then all subdirectories of *paths* will also be se... | 41039cea452860649f717358fd57a99e73202579 | <|skeleton|>
class FilesystemCollector:
def __init__(self, paths=None, recursive=True):
"""Initialise with *paths* to search. If *recursive* is True then all subdirectories of *paths* will also be searched."""
<|body_0|>
def collect(self):
"""Yield collected schemas."""
<|body_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FilesystemCollector:
def __init__(self, paths=None, recursive=True):
"""Initialise with *paths* to search. If *recursive* is True then all subdirectories of *paths* will also be searched."""
self.paths = paths
self.recursive = recursive
if self.paths is None:
self.p... | the_stack_v2_python_sparse | source/harmony/schema/collector.py | 4degrees/harmony | train | 4 | |
b221bdfc6076c89845c73d36b8bbc78e055507c9 | [
"self.red = red\nself.green = green\nself.blue = blue\nself.led_is_off = True\nGPIO.setmode(GPIO.BCM)\nGPIO.setwarnings(False)\nGPIO.setup(self.green, GPIO.OUT)\nGPIO.setup(self.red, GPIO.OUT)\nGPIO.setup(self.blue, GPIO.OUT)\nself.on = on\nself.time_on = time.time()\nif self.on == 'low':\n self.led_on = GPIO.LO... | <|body_start_0|>
self.red = red
self.green = green
self.blue = blue
self.led_is_off = True
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(self.green, GPIO.OUT)
GPIO.setup(self.red, GPIO.OUT)
GPIO.setup(self.blue, GPIO.OUT)
self.o... | RGB LED - configures an RGB LED. BTW do not forget the current limiting resistors! (will burn out LED and the GPIO pin on board typical values are 220 - 330 ohms. Methods: - change_led : makes the playstate_led red, green, or blue | TriColorLED | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TriColorLED:
"""RGB LED - configures an RGB LED. BTW do not forget the current limiting resistors! (will burn out LED and the GPIO pin on board typical values are 220 - 330 ohms. Methods: - change_led : makes the playstate_led red, green, or blue"""
def __init__(self, green=0, red=0, blue=0,... | stack_v2_sparse_classes_75kplus_train_005154 | 40,088 | no_license | [
{
"docstring": ":param green: GPIO pin number for green playstate_led :type green: integer :param red: GPIO pin for red playstate_led :type red: integer :param blue: GPIO pin for blue playstate_led :type blue: integer :param on: sets whether leds turn on when gpio pin is HIGH or LOW :type on: str",
"name": ... | 2 | stack_v2_sparse_classes_30k_train_030992 | Implement the Python class `TriColorLED` described below.
Class description:
RGB LED - configures an RGB LED. BTW do not forget the current limiting resistors! (will burn out LED and the GPIO pin on board typical values are 220 - 330 ohms. Methods: - change_led : makes the playstate_led red, green, or blue
Method sig... | Implement the Python class `TriColorLED` described below.
Class description:
RGB LED - configures an RGB LED. BTW do not forget the current limiting resistors! (will burn out LED and the GPIO pin on board typical values are 220 - 330 ohms. Methods: - change_led : makes the playstate_led red, green, or blue
Method sig... | 622cc666019753c4736c03be0d41308212c84291 | <|skeleton|>
class TriColorLED:
"""RGB LED - configures an RGB LED. BTW do not forget the current limiting resistors! (will burn out LED and the GPIO pin on board typical values are 220 - 330 ohms. Methods: - change_led : makes the playstate_led red, green, or blue"""
def __init__(self, green=0, red=0, blue=0,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TriColorLED:
"""RGB LED - configures an RGB LED. BTW do not forget the current limiting resistors! (will burn out LED and the GPIO pin on board typical values are 220 - 330 ohms. Methods: - change_led : makes the playstate_led red, green, or blue"""
def __init__(self, green=0, red=0, blue=0, on='low'):
... | the_stack_v2_python_sparse | SonosHW.py | gshorten/SonosController | train | 5 |
4effbd606ee086e0ee261c3a35aa4bc649e42e0b | [
"assert embedding_type in ['skipgram', 'cbow']\nself.embedding_type = embedding_type\nself.model_name = model_name\nself.model_path = os.path.join(MODELS_DIR, '{}_{}'.format(self.embedding_type, model_name))\nself.model = None",
"input_path = os.path.join(DATA_DIR, file_input)\nif self.embedding_type == 'skipgram... | <|body_start_0|>
assert embedding_type in ['skipgram', 'cbow']
self.embedding_type = embedding_type
self.model_name = model_name
self.model_path = os.path.join(MODELS_DIR, '{}_{}'.format(self.embedding_type, model_name))
self.model = None
<|end_body_0|>
<|body_start_1|>
... | FastTextEmbedding | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FastTextEmbedding:
def __init__(self, embedding_type='skipgram', model_name='model'):
""":param embedding_type: :param model_name:"""
<|body_0|>
def train_model(self, file_input='train_text.txt'):
""":param file_input: :return:"""
<|body_1|>
def load_mod... | stack_v2_sparse_classes_75kplus_train_005155 | 4,860 | permissive | [
{
"docstring": ":param embedding_type: :param model_name:",
"name": "__init__",
"signature": "def __init__(self, embedding_type='skipgram', model_name='model')"
},
{
"docstring": ":param file_input: :return:",
"name": "train_model",
"signature": "def train_model(self, file_input='train_t... | 4 | stack_v2_sparse_classes_30k_train_041300 | Implement the Python class `FastTextEmbedding` described below.
Class description:
Implement the FastTextEmbedding class.
Method signatures and docstrings:
- def __init__(self, embedding_type='skipgram', model_name='model'): :param embedding_type: :param model_name:
- def train_model(self, file_input='train_text.txt'... | Implement the Python class `FastTextEmbedding` described below.
Class description:
Implement the FastTextEmbedding class.
Method signatures and docstrings:
- def __init__(self, embedding_type='skipgram', model_name='model'): :param embedding_type: :param model_name:
- def train_model(self, file_input='train_text.txt'... | 281a63732a0994f986529580716f25e4ab67ad20 | <|skeleton|>
class FastTextEmbedding:
def __init__(self, embedding_type='skipgram', model_name='model'):
""":param embedding_type: :param model_name:"""
<|body_0|>
def train_model(self, file_input='train_text.txt'):
""":param file_input: :return:"""
<|body_1|>
def load_mod... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FastTextEmbedding:
def __init__(self, embedding_type='skipgram', model_name='model'):
""":param embedding_type: :param model_name:"""
assert embedding_type in ['skipgram', 'cbow']
self.embedding_type = embedding_type
self.model_name = model_name
self.model_path = os.pat... | the_stack_v2_python_sparse | rpcc/word_embedding.py | gperakis/research-paper-category-classifier | train | 1 | |
46ef82fc24bc8140fe63e8b26b8f7c29c5611b47 | [
"self.strategy = strategy\nself.exchange_hyperparameters = exchange_hyperparameters\nself.weights_names = make_iterable(weights_names)\nself.checkpoint_dir = checkpoint_dir",
"ExchangeStrategyMsg = AlgoProto.RandomPairwiseExchange.ExchangeStrategy\nmsg = ExchangeStrategyMsg()\nmsg.weights_name.extend([n for n in ... | <|body_start_0|>
self.strategy = strategy
self.exchange_hyperparameters = exchange_hyperparameters
self.weights_names = make_iterable(weights_names)
self.checkpoint_dir = checkpoint_dir
<|end_body_0|>
<|body_start_1|>
ExchangeStrategyMsg = AlgoProto.RandomPairwiseExchange.Exchan... | The algorithm for exchanging model data in RandomPairwiseExchange. WARNING: The fate of this class is under consideration. It would be good for it to converge to a single algorithm. Hence, no effort has been made here to mirror the C++ polymorphism in this Python wrapper. There are currently three strategies that are s... | ExchangeStrategy | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExchangeStrategy:
"""The algorithm for exchanging model data in RandomPairwiseExchange. WARNING: The fate of this class is under consideration. It would be good for it to converge to a single algorithm. Hence, no effort has been made here to mirror the C++ polymorphism in this Python wrapper. The... | stack_v2_sparse_classes_75kplus_train_005156 | 18,905 | permissive | [
{
"docstring": "Construct a new exchange strategy. Args: strategy: Which strategy to use (default: \"checkpoint_binary\"). weights_names: A list of weights names that should be exchanged. exchange_hyperparameters: If True, exchange all optimizer state. Only applies to the \"sendrecv_weights\" strategy. checkpoi... | 2 | null | Implement the Python class `ExchangeStrategy` described below.
Class description:
The algorithm for exchanging model data in RandomPairwiseExchange. WARNING: The fate of this class is under consideration. It would be good for it to converge to a single algorithm. Hence, no effort has been made here to mirror the C++ p... | Implement the Python class `ExchangeStrategy` described below.
Class description:
The algorithm for exchanging model data in RandomPairwiseExchange. WARNING: The fate of this class is under consideration. It would be good for it to converge to a single algorithm. Hence, no effort has been made here to mirror the C++ p... | e8cf85eed2acbd3383892bf7cb2d88b44c194f4f | <|skeleton|>
class ExchangeStrategy:
"""The algorithm for exchanging model data in RandomPairwiseExchange. WARNING: The fate of this class is under consideration. It would be good for it to converge to a single algorithm. Hence, no effort has been made here to mirror the C++ polymorphism in this Python wrapper. The... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ExchangeStrategy:
"""The algorithm for exchanging model data in RandomPairwiseExchange. WARNING: The fate of this class is under consideration. It would be good for it to converge to a single algorithm. Hence, no effort has been made here to mirror the C++ polymorphism in this Python wrapper. There are curren... | the_stack_v2_python_sparse | python/lbann/core/training_algorithm.py | LLNL/lbann | train | 225 |
0b4218b7e034e16b1aa487feea1c49c4a82817d8 | [
"cube = to_threshold_inequality(cube, above=False)\nthreshold_coord = find_threshold_coordinate(cube)\nthreshold_coord_idx = cube.dim_coords.index(threshold_coord)\nthresholds = threshold_coord.points\nif np.any(np.diff(thresholds) <= 0.0):\n raise ValueError('threshold coordinate in decreasing order')\neps = np... | <|body_start_0|>
cube = to_threshold_inequality(cube, above=False)
threshold_coord = find_threshold_coordinate(cube)
threshold_coord_idx = cube.dim_coords.index(threshold_coord)
thresholds = threshold_coord.points
if np.any(np.diff(thresholds) <= 0.0):
raise ValueErro... | Calculation of expected value from a probability distribution | ExpectedValue | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExpectedValue:
"""Calculation of expected value from a probability distribution"""
def integrate_over_thresholds(cube: Cube) -> Cube:
"""Calculation of expected value for threshold data by converting from cumulative distribution (CDF) to probability density (PDF), then integrating ov... | stack_v2_sparse_classes_75kplus_train_005157 | 6,910 | permissive | [
{
"docstring": "Calculation of expected value for threshold data by converting from cumulative distribution (CDF) to probability density (PDF), then integrating over the threshold dimension. Args: cube: Probabilistic data with a threshold coordinate. Returns: Expected value of probability distribution. Same sha... | 2 | null | Implement the Python class `ExpectedValue` described below.
Class description:
Calculation of expected value from a probability distribution
Method signatures and docstrings:
- def integrate_over_thresholds(cube: Cube) -> Cube: Calculation of expected value for threshold data by converting from cumulative distributio... | Implement the Python class `ExpectedValue` described below.
Class description:
Calculation of expected value from a probability distribution
Method signatures and docstrings:
- def integrate_over_thresholds(cube: Cube) -> Cube: Calculation of expected value for threshold data by converting from cumulative distributio... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class ExpectedValue:
"""Calculation of expected value from a probability distribution"""
def integrate_over_thresholds(cube: Cube) -> Cube:
"""Calculation of expected value for threshold data by converting from cumulative distribution (CDF) to probability density (PDF), then integrating ov... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ExpectedValue:
"""Calculation of expected value from a probability distribution"""
def integrate_over_thresholds(cube: Cube) -> Cube:
"""Calculation of expected value for threshold data by converting from cumulative distribution (CDF) to probability density (PDF), then integrating over the thresh... | the_stack_v2_python_sparse | improver/expected_value.py | metoppv/improver | train | 101 |
4b4e7277606bf97672736ffe0a2e2cdb68e1f5fc | [
"self.strike = kwargs['strike']\nself.rate = kwargs['rate']\nself.dividend = kwargs['dividend']\nself.maturity = kwargs['maturity']\nself.volatility = kwargs['volatility']\nself.cp = kwargs['cp']\nself.date_type = kwargs['date_type']\nself.nominal_num = kwargs['nominal_num']\nself.factor_name = '{}:strike_{}'.forma... | <|body_start_0|>
self.strike = kwargs['strike']
self.rate = kwargs['rate']
self.dividend = kwargs['dividend']
self.maturity = kwargs['maturity']
self.volatility = kwargs['volatility']
self.cp = kwargs['cp']
self.date_type = kwargs['date_type']
self.nominal... | 示例正向对冲买入择时类,混入BuyCallMixin,即向上突破触发买入event, 适用于看涨期权 | AbuFactorBuyEuroOptionHedge | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AbuFactorBuyEuroOptionHedge:
"""示例正向对冲买入择时类,混入BuyCallMixin,即向上突破触发买入event, 适用于看涨期权"""
def _init_self(self, **kwargs):
"""kwargs中必须包含: 期权各参数"""
<|body_0|>
def fit_day(self, today, holding_cnt):
"""针对每一个交易日拟合买入交易策略,寻找向上突破买入机会 :param today: 当前驱动的交易日金融时间序列数据 :param h... | stack_v2_sparse_classes_75kplus_train_005158 | 3,898 | no_license | [
{
"docstring": "kwargs中必须包含: 期权各参数",
"name": "_init_self",
"signature": "def _init_self(self, **kwargs)"
},
{
"docstring": "针对每一个交易日拟合买入交易策略,寻找向上突破买入机会 :param today: 当前驱动的交易日金融时间序列数据 :param holding_cnt: 交易发生之前的持仓量 :return:",
"name": "fit_day",
"signature": "def fit_day(self, today, holdi... | 2 | stack_v2_sparse_classes_30k_train_004066 | Implement the Python class `AbuFactorBuyEuroOptionHedge` described below.
Class description:
示例正向对冲买入择时类,混入BuyCallMixin,即向上突破触发买入event, 适用于看涨期权
Method signatures and docstrings:
- def _init_self(self, **kwargs): kwargs中必须包含: 期权各参数
- def fit_day(self, today, holding_cnt): 针对每一个交易日拟合买入交易策略,寻找向上突破买入机会 :param today: 当前驱动... | Implement the Python class `AbuFactorBuyEuroOptionHedge` described below.
Class description:
示例正向对冲买入择时类,混入BuyCallMixin,即向上突破触发买入event, 适用于看涨期权
Method signatures and docstrings:
- def _init_self(self, **kwargs): kwargs中必须包含: 期权各参数
- def fit_day(self, today, holding_cnt): 针对每一个交易日拟合买入交易策略,寻找向上突破买入机会 :param today: 当前驱动... | 6f9dabecb17b65a02a370134e178722c169b2cd2 | <|skeleton|>
class AbuFactorBuyEuroOptionHedge:
"""示例正向对冲买入择时类,混入BuyCallMixin,即向上突破触发买入event, 适用于看涨期权"""
def _init_self(self, **kwargs):
"""kwargs中必须包含: 期权各参数"""
<|body_0|>
def fit_day(self, today, holding_cnt):
"""针对每一个交易日拟合买入交易策略,寻找向上突破买入机会 :param today: 当前驱动的交易日金融时间序列数据 :param h... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AbuFactorBuyEuroOptionHedge:
"""示例正向对冲买入择时类,混入BuyCallMixin,即向上突破触发买入event, 适用于看涨期权"""
def _init_self(self, **kwargs):
"""kwargs中必须包含: 期权各参数"""
self.strike = kwargs['strike']
self.rate = kwargs['rate']
self.dividend = kwargs['dividend']
self.maturity = kwargs['matur... | the_stack_v2_python_sparse | abupy/FactorBuyBu/ABuFactorBuyEuroOptionHedge.py | Leo70kg/Backtesting | train | 1 |
c11acba97f2c7613636fd7a3701b449dcca903db | [
"lq_sms_key = get_lq_sms_key(tid)\nlq_interval_key = get_lq_interval_key(tid)\nself.redis.setvalue(lq_interval_key, int(time.time()), interval * 60 - 160)\nif not self.redis.getvalue(lq_sms_key):\n sms = SMSCode.SMS_LQ % interval\n biz_type = QueryHelper.get_biz_type_by_tmobile(sim, self.db)\n if biz_type ... | <|body_start_0|>
lq_sms_key = get_lq_sms_key(tid)
lq_interval_key = get_lq_interval_key(tid)
self.redis.setvalue(lq_interval_key, int(time.time()), interval * 60 - 160)
if not self.redis.getvalue(lq_sms_key):
sms = SMSCode.SMS_LQ % interval
biz_type = QueryHelper.... | BaseMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseMixin:
def send_lq_sms(self, sim, tid, interval):
"""Send LQ Message to terminal. lq_sms_key: when send lq sms to terminal, keep it in redis for 3 minutes. in 3 minutes, do not send lq sms twice. lq_interval_key: when send lq sms to terminal, keep it in redis for interval. in the per... | stack_v2_sparse_classes_75kplus_train_005159 | 4,444 | no_license | [
{
"docstring": "Send LQ Message to terminal. lq_sms_key: when send lq sms to terminal, keep it in redis for 3 minutes. in 3 minutes, do not send lq sms twice. lq_interval_key: when send lq sms to terminal, keep it in redis for interval. in the period of interval, terminal is been awaken. when the period of inte... | 3 | stack_v2_sparse_classes_30k_train_022681 | Implement the Python class `BaseMixin` described below.
Class description:
Implement the BaseMixin class.
Method signatures and docstrings:
- def send_lq_sms(self, sim, tid, interval): Send LQ Message to terminal. lq_sms_key: when send lq sms to terminal, keep it in redis for 3 minutes. in 3 minutes, do not send lq s... | Implement the Python class `BaseMixin` described below.
Class description:
Implement the BaseMixin class.
Method signatures and docstrings:
- def send_lq_sms(self, sim, tid, interval): Send LQ Message to terminal. lq_sms_key: when send lq sms to terminal, keep it in redis for 3 minutes. in 3 minutes, do not send lq s... | 3b095a325581b1fc48497c234f0ad55e928586a1 | <|skeleton|>
class BaseMixin:
def send_lq_sms(self, sim, tid, interval):
"""Send LQ Message to terminal. lq_sms_key: when send lq sms to terminal, keep it in redis for 3 minutes. in 3 minutes, do not send lq sms twice. lq_interval_key: when send lq sms to terminal, keep it in redis for interval. in the per... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaseMixin:
def send_lq_sms(self, sim, tid, interval):
"""Send LQ Message to terminal. lq_sms_key: when send lq sms to terminal, keep it in redis for 3 minutes. in 3 minutes, do not send lq sms twice. lq_interval_key: when send lq sms to terminal, keep it in redis for interval. in the period of interva... | the_stack_v2_python_sparse | apps/uweb/mixin/base.py | jcsy521/ydws | train | 0 | |
4a0521e733d7580ef3eba6519f3e26a369b68637 | [
"super().__init__()\nself.pooling = pooling\nself.spherical_cheb = SphericalChebConv(in_channels, out_channels, lap, kernel_size)",
"x = self.pooling(x)\nx = self.spherical_cheb(x)\nreturn x"
] | <|body_start_0|>
super().__init__()
self.pooling = pooling
self.spherical_cheb = SphericalChebConv(in_channels, out_channels, lap, kernel_size)
<|end_body_0|>
<|body_start_1|>
x = self.pooling(x)
x = self.spherical_cheb(x)
return x
<|end_body_1|>
| Building Block with a pooling/unpooling and a Chebyshev Convolution. | SphericalChebPool | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SphericalChebPool:
"""Building Block with a pooling/unpooling and a Chebyshev Convolution."""
def __init__(self, in_channels, out_channels, lap, pooling, kernel_size):
"""Initialization. Args: in_channels (int): initial number of channels. out_channels (int): output number of channel... | stack_v2_sparse_classes_75kplus_train_005160 | 41,403 | no_license | [
{
"docstring": "Initialization. Args: in_channels (int): initial number of channels. out_channels (int): output number of channels. lap (:obj:`torch.sparse.FloatTensor`): laplacian. pooling (:obj:`torch.nn.Module`): pooling/unpooling module. kernel_size (int, optional): polynomial degree.",
"name": "__init_... | 2 | stack_v2_sparse_classes_30k_train_002182 | Implement the Python class `SphericalChebPool` described below.
Class description:
Building Block with a pooling/unpooling and a Chebyshev Convolution.
Method signatures and docstrings:
- def __init__(self, in_channels, out_channels, lap, pooling, kernel_size): Initialization. Args: in_channels (int): initial number ... | Implement the Python class `SphericalChebPool` described below.
Class description:
Building Block with a pooling/unpooling and a Chebyshev Convolution.
Method signatures and docstrings:
- def __init__(self, in_channels, out_channels, lap, pooling, kernel_size): Initialization. Args: in_channels (int): initial number ... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class SphericalChebPool:
"""Building Block with a pooling/unpooling and a Chebyshev Convolution."""
def __init__(self, in_channels, out_channels, lap, pooling, kernel_size):
"""Initialization. Args: in_channels (int): initial number of channels. out_channels (int): output number of channel... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SphericalChebPool:
"""Building Block with a pooling/unpooling and a Chebyshev Convolution."""
def __init__(self, in_channels, out_channels, lap, pooling, kernel_size):
"""Initialization. Args: in_channels (int): initial number of channels. out_channels (int): output number of channels. lap (:obj:... | the_stack_v2_python_sparse | generated/test_deepsphere_deepsphere_pytorch.py | jansel/pytorch-jit-paritybench | train | 35 |
a9f35547fd929285bbc97074203e4ed8c7bb14b0 | [
"super().__init__()\nself.cat = ops.Concat(axis=1)\nself.unsqueeze = ops.ExpandDims()",
"attention_mask = word_attention_mask\nif entity_attention_mask is not None:\n attention_mask = self.cat((attention_mask, entity_attention_mask))\nextended_attention_mask = self.unsqueeze(self.unsqueeze(attention_mask, 1), ... | <|body_start_0|>
super().__init__()
self.cat = ops.Concat(axis=1)
self.unsqueeze = ops.ExpandDims()
<|end_body_0|>
<|body_start_1|>
attention_mask = word_attention_mask
if entity_attention_mask is not None:
attention_mask = self.cat((attention_mask, entity_attention_... | compute extended attention mask | ComputeExtendedAttentionMask | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ComputeExtendedAttentionMask:
"""compute extended attention mask"""
def __init__(self):
"""init fun"""
<|body_0|>
def construct(self, word_attention_mask, entity_attention_mask):
"""construct fun"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
s... | stack_v2_sparse_classes_75kplus_train_005161 | 14,686 | permissive | [
{
"docstring": "init fun",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "construct fun",
"name": "construct",
"signature": "def construct(self, word_attention_mask, entity_attention_mask)"
}
] | 2 | null | Implement the Python class `ComputeExtendedAttentionMask` described below.
Class description:
compute extended attention mask
Method signatures and docstrings:
- def __init__(self): init fun
- def construct(self, word_attention_mask, entity_attention_mask): construct fun | Implement the Python class `ComputeExtendedAttentionMask` described below.
Class description:
compute extended attention mask
Method signatures and docstrings:
- def __init__(self): init fun
- def construct(self, word_attention_mask, entity_attention_mask): construct fun
<|skeleton|>
class ComputeExtendedAttentionMa... | eab643f51336dbf7d711f02d27e6516e5affee59 | <|skeleton|>
class ComputeExtendedAttentionMask:
"""compute extended attention mask"""
def __init__(self):
"""init fun"""
<|body_0|>
def construct(self, word_attention_mask, entity_attention_mask):
"""construct fun"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ComputeExtendedAttentionMask:
"""compute extended attention mask"""
def __init__(self):
"""init fun"""
super().__init__()
self.cat = ops.Concat(axis=1)
self.unsqueeze = ops.ExpandDims()
def construct(self, word_attention_mask, entity_attention_mask):
"""constr... | the_stack_v2_python_sparse | research/nlp/luke/src/luke/tacred_model.py | mindspore-ai/models | train | 301 |
29891f0c7456a0b9d60f918d9da19ac9311e258f | [
"slist = list(s)\nsdict = {}\ncount = 1\nfor i in range(len(slist)):\n if slist[i] not in sdict.keys():\n sdict[slist[i]] = count\n else:\n sdict[slist[i]] = sdict[slist[i]] + 1\nfor i, v in sdict.items():\n if v == 1:\n return s.index(i)\nreturn -1",
"count = collections.Counter(s)\... | <|body_start_0|>
slist = list(s)
sdict = {}
count = 1
for i in range(len(slist)):
if slist[i] not in sdict.keys():
sdict[slist[i]] = count
else:
sdict[slist[i]] = sdict[slist[i]] + 1
for i, v in sdict.items():
if... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def firstUniqChar(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def firstUniqChar2(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
slist = list(s)
sdict = {}
count = 1
for... | stack_v2_sparse_classes_75kplus_train_005162 | 1,473 | no_license | [
{
"docstring": ":type s: str :rtype: int",
"name": "firstUniqChar",
"signature": "def firstUniqChar(self, s)"
},
{
"docstring": ":type s: str :rtype: int",
"name": "firstUniqChar2",
"signature": "def firstUniqChar2(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_038464 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def firstUniqChar(self, s): :type s: str :rtype: int
- def firstUniqChar2(self, s): :type s: str :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def firstUniqChar(self, s): :type s: str :rtype: int
- def firstUniqChar2(self, s): :type s: str :rtype: int
<|skeleton|>
class Solution:
def firstUniqChar(self, s):
... | 786075e0f9f61cf062703bc0b41cc3191d77f033 | <|skeleton|>
class Solution:
def firstUniqChar(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def firstUniqChar2(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def firstUniqChar(self, s):
""":type s: str :rtype: int"""
slist = list(s)
sdict = {}
count = 1
for i in range(len(slist)):
if slist[i] not in sdict.keys():
sdict[slist[i]] = count
else:
sdict[slist[i]] =... | the_stack_v2_python_sparse | firstUniqChar.py | Anirban2404/LeetCodePractice | train | 1 | |
2e47d752f9bf2ecdc25c130fda839a5ce5509f72 | [
"self.view = view\nself.codeWindow = codeWindow\nself.actionWindow = actionWindow",
"self.view.hide()\nself.codeWindow.hide()\nself.actionWindow.hide()\nM3Launcher().launch(code)\nself.view.show()\nself.codeWindow.show()\nself.actionWindow.show()",
"self.view.hide()\nself.codeWindow.hide()\nself.actionWindow.hi... | <|body_start_0|>
self.view = view
self.codeWindow = codeWindow
self.actionWindow = actionWindow
<|end_body_0|>
<|body_start_1|>
self.view.hide()
self.codeWindow.hide()
self.actionWindow.hide()
M3Launcher().launch(code)
self.view.show()
self.codeWi... | controller used for launching other applications | LauncherController | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LauncherController:
"""controller used for launching other applications"""
def __init__(self, view, codeWindow, actionWindow):
"""constructor"""
<|body_0|>
def launchMach3(self, code):
"""launches mach3 with the current G-code"""
<|body_1|>
def launc... | stack_v2_sparse_classes_75kplus_train_005163 | 1,035 | no_license | [
{
"docstring": "constructor",
"name": "__init__",
"signature": "def __init__(self, view, codeWindow, actionWindow)"
},
{
"docstring": "launches mach3 with the current G-code",
"name": "launchMach3",
"signature": "def launchMach3(self, code)"
},
{
"docstring": "launches a text edi... | 3 | null | Implement the Python class `LauncherController` described below.
Class description:
controller used for launching other applications
Method signatures and docstrings:
- def __init__(self, view, codeWindow, actionWindow): constructor
- def launchMach3(self, code): launches mach3 with the current G-code
- def launchTex... | Implement the Python class `LauncherController` described below.
Class description:
controller used for launching other applications
Method signatures and docstrings:
- def __init__(self, view, codeWindow, actionWindow): constructor
- def launchMach3(self, code): launches mach3 with the current G-code
- def launchTex... | 5f14b90d8fe0d528683ac0b48c7c3c088433ec6f | <|skeleton|>
class LauncherController:
"""controller used for launching other applications"""
def __init__(self, view, codeWindow, actionWindow):
"""constructor"""
<|body_0|>
def launchMach3(self, code):
"""launches mach3 with the current G-code"""
<|body_1|>
def launc... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LauncherController:
"""controller used for launching other applications"""
def __init__(self, view, codeWindow, actionWindow):
"""constructor"""
self.view = view
self.codeWindow = codeWindow
self.actionWindow = actionWindow
def launchMach3(self, code):
"""laun... | the_stack_v2_python_sparse | objects/controller/launchers/launcherController.py | daniel321/fresaGl | train | 0 |
5f674cf87c5b696d0f292ad2d1570cd440d33f8b | [
"if hasattr(root, 'prepare_for_quant'):\n return root.prepare_for_quant()\nprep_fn = prepare_qat_fx if isinstance(self, QuantizationAwareTraining) else prepare_fx\nold_attrs = {attr: rgetattr(root, attr) for attr in attrs if rhasattr(root, attr)}\nprepared = root\nif '' in configs:\n prepared = prep_fn(root, ... | <|body_start_0|>
if hasattr(root, 'prepare_for_quant'):
return root.prepare_for_quant()
prep_fn = prepare_qat_fx if isinstance(self, QuantizationAwareTraining) else prepare_fx
old_attrs = {attr: rgetattr(root, attr) for attr in attrs if rhasattr(root, attr)}
prepared = root
... | Mixin defining an overrideable API for quantization customization. For example, suppose our model contains traceable and non-traceable modules: >>> class MyNonTraceableModel(LightningModule): ... def __init__(self): ... self.traceable = ... ... self.non_traceable = ... ... ... def forward(self, x): ... x = self.traceab... | QuantizationMixin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuantizationMixin:
"""Mixin defining an overrideable API for quantization customization. For example, suppose our model contains traceable and non-traceable modules: >>> class MyNonTraceableModel(LightningModule): ... def __init__(self): ... self.traceable = ... ... self.non_traceable = ... ... .... | stack_v2_sparse_classes_75kplus_train_005164 | 24,037 | permissive | [
{
"docstring": "Prepares the root user modules for quantization. By default, this tries to prepare the entire LightningModule. If this is not possible (eg, due to traceability, etc.), the recommended method to use is to override the `prepare` method to prepare the root as appropriate, and also override the `qua... | 2 | stack_v2_sparse_classes_30k_train_030641 | Implement the Python class `QuantizationMixin` described below.
Class description:
Mixin defining an overrideable API for quantization customization. For example, suppose our model contains traceable and non-traceable modules: >>> class MyNonTraceableModel(LightningModule): ... def __init__(self): ... self.traceable =... | Implement the Python class `QuantizationMixin` described below.
Class description:
Mixin defining an overrideable API for quantization customization. For example, suppose our model contains traceable and non-traceable modules: >>> class MyNonTraceableModel(LightningModule): ... def __init__(self): ... self.traceable =... | 23a644a1213ff19f32b3f106b271d41ff3148bd1 | <|skeleton|>
class QuantizationMixin:
"""Mixin defining an overrideable API for quantization customization. For example, suppose our model contains traceable and non-traceable modules: >>> class MyNonTraceableModel(LightningModule): ... def __init__(self): ... self.traceable = ... ... self.non_traceable = ... ... .... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class QuantizationMixin:
"""Mixin defining an overrideable API for quantization customization. For example, suppose our model contains traceable and non-traceable modules: >>> class MyNonTraceableModel(LightningModule): ... def __init__(self): ... self.traceable = ... ... self.non_traceable = ... ... ... def forwar... | the_stack_v2_python_sparse | d2go/runner/callbacks/quantization.py | pankajkumar9797/d2go | train | 3 |
a2d1244e76b19fd87ff7cb7d1636a56fd77e5b2b | [
"self.infolder, self.outfolder = (infolder, outfolder)\nself.collection_name = collection_name\nself.files = glob.glob('%s/*.%s' % (infolder, imagetype))\nn = len(self.files)\nself.type = imagetype\nself.files.sort()\nif n == 0:\n raise InvalidParameter('no %s files found in folder \"%s\"' % (imagetype, infolder... | <|body_start_0|>
self.infolder, self.outfolder = (infolder, outfolder)
self.collection_name = collection_name
self.files = glob.glob('%s/*.%s' % (infolder, imagetype))
n = len(self.files)
self.type = imagetype
self.files.sort()
if n == 0:
raise Invalid... | Create a DeepZoom collection, converting a set of images. Usage: mc = dz_collection.MakeCollection('uw93/combined', '/phys/users/tburnett/pivot/24M_uw93') mc.convert() mc.collect() Note that the convert step time is order(number of images) and can be parallized by passing an optional IPython.parallel.Client object | MakeCollection | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MakeCollection:
"""Create a DeepZoom collection, converting a set of images. Usage: mc = dz_collection.MakeCollection('uw93/combined', '/phys/users/tburnett/pivot/24M_uw93') mc.convert() mc.collect() Note that the convert step time is order(number of images) and can be parallized by passing an op... | stack_v2_sparse_classes_75kplus_train_005165 | 5,986 | permissive | [
{
"docstring": "infolder : path to a folder containing a bunch of images (jpg by default) to convert outfolder : where to set up the collection keyword parameters collection_name: ['dzc'] name to apply to the deep zoom collection: will be the name of a xml file and the folder name containing the DZ images image... | 4 | stack_v2_sparse_classes_30k_test_002097 | Implement the Python class `MakeCollection` described below.
Class description:
Create a DeepZoom collection, converting a set of images. Usage: mc = dz_collection.MakeCollection('uw93/combined', '/phys/users/tburnett/pivot/24M_uw93') mc.convert() mc.collect() Note that the convert step time is order(number of images)... | Implement the Python class `MakeCollection` described below.
Class description:
Create a DeepZoom collection, converting a set of images. Usage: mc = dz_collection.MakeCollection('uw93/combined', '/phys/users/tburnett/pivot/24M_uw93') mc.convert() mc.collect() Note that the convert step time is order(number of images)... | edcdc696c3300e2f26ff3efa92a1bd9790074247 | <|skeleton|>
class MakeCollection:
"""Create a DeepZoom collection, converting a set of images. Usage: mc = dz_collection.MakeCollection('uw93/combined', '/phys/users/tburnett/pivot/24M_uw93') mc.convert() mc.collect() Note that the convert step time is order(number of images) and can be parallized by passing an op... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MakeCollection:
"""Create a DeepZoom collection, converting a set of images. Usage: mc = dz_collection.MakeCollection('uw93/combined', '/phys/users/tburnett/pivot/24M_uw93') mc.convert() mc.collect() Note that the convert step time is order(number of images) and can be parallized by passing an optional IPytho... | the_stack_v2_python_sparse | python/uw/like2/pub/dz_collection.py | fermi-lat/pointlike | train | 1 |
5d9a2ccb056543a92dd2643ad2c23814c12060cd | [
"fields_to_save = []\nfor idx, field_id in enumerate(order):\n field = self.fields.get(pk=field_id)\n field.order = idx\n fields_to_save.append(field)\nfor field in fields_to_save:\n field.save()",
"queries = ['(category_id = %s)' % self.id]\nif 'min_date' in rule:\n queries.append('(\"contribution... | <|body_start_0|>
fields_to_save = []
for idx, field_id in enumerate(order):
field = self.fields.get(pk=field_id)
field.order = idx
fields_to_save.append(field)
for field in fields_to_save:
field.save()
<|end_body_0|>
<|body_start_1|>
queri... | Defines the data structure of a certain type of features. | Category | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Category:
"""Defines the data structure of a certain type of features."""
def reorder_fields(self, order):
"""Changes the order in which fields are displayed on client side. Parameters ------- order : List IDs of fields, ordered according to new display order"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_005166 | 29,149 | permissive | [
{
"docstring": "Changes the order in which fields are displayed on client side. Parameters ------- order : List IDs of fields, ordered according to new display order",
"name": "reorder_fields",
"signature": "def reorder_fields(self, order)"
},
{
"docstring": "Returns the SQL where clause for the... | 3 | stack_v2_sparse_classes_30k_train_008464 | Implement the Python class `Category` described below.
Class description:
Defines the data structure of a certain type of features.
Method signatures and docstrings:
- def reorder_fields(self, order): Changes the order in which fields are displayed on client side. Parameters ------- order : List IDs of fields, ordere... | Implement the Python class `Category` described below.
Class description:
Defines the data structure of a certain type of features.
Method signatures and docstrings:
- def reorder_fields(self, order): Changes the order in which fields are displayed on client side. Parameters ------- order : List IDs of fields, ordere... | 16d31b5207de9f699fc01054baad1fe65ad1c3ca | <|skeleton|>
class Category:
"""Defines the data structure of a certain type of features."""
def reorder_fields(self, order):
"""Changes the order in which fields are displayed on client side. Parameters ------- order : List IDs of fields, ordered according to new display order"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Category:
"""Defines the data structure of a certain type of features."""
def reorder_fields(self, order):
"""Changes the order in which fields are displayed on client side. Parameters ------- order : List IDs of fields, ordered according to new display order"""
fields_to_save = []
... | the_stack_v2_python_sparse | geokey/categories/models.py | NeolithEra/geokey | train | 0 |
d1fb3045734530558371a85ef74dcc52bf517ebe | [
"self.data_path = data_path\nself.wiki = wiki_data\nself.contexts = [v['text'] for v in self.wiki.values()]\nprint(f'Lengths of unique contexts : {len(self.contexts)}')\nself.ids = list(range(len(self.contexts)))\nself.tokenize_fn = tokenize_fn\nself.bm25 = None",
"bm25_name = f'bm25.bin'\nbm25_path = os.path.joi... | <|body_start_0|>
self.data_path = data_path
self.wiki = wiki_data
self.contexts = [v['text'] for v in self.wiki.values()]
print(f'Lengths of unique contexts : {len(self.contexts)}')
self.ids = list(range(len(self.contexts)))
self.tokenize_fn = tokenize_fn
self.bm2... | BM25Data | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BM25Data:
def __init__(self, tokenize_fn, wiki_data=None, data_path: Optional[str]='/opt/ml/data/', context_path: Optional[str]='wikipedia_documents.json') -> NoReturn:
"""Arguments: tokenize_fn: 기본 text를 tokenize해주는 함수입니다. 아래와 같은 함수들을 사용할 수 있습니다. - lambda x: x.split(' ') - Huggingface T... | stack_v2_sparse_classes_75kplus_train_005167 | 9,247 | no_license | [
{
"docstring": "Arguments: tokenize_fn: 기본 text를 tokenize해주는 함수입니다. 아래와 같은 함수들을 사용할 수 있습니다. - lambda x: x.split(' ') - Huggingface Tokenizer - konlpy.tag의 Mecab data_path: 데이터가 보관되어 있는 경로입니다. context_path: Passage들이 묶여있는 파일명입니다. data_path/context_path가 존재해야합니다.",
"name": "__init__",
"signature": "def __... | 5 | stack_v2_sparse_classes_30k_train_044509 | Implement the Python class `BM25Data` described below.
Class description:
Implement the BM25Data class.
Method signatures and docstrings:
- def __init__(self, tokenize_fn, wiki_data=None, data_path: Optional[str]='/opt/ml/data/', context_path: Optional[str]='wikipedia_documents.json') -> NoReturn: Arguments: tokenize... | Implement the Python class `BM25Data` described below.
Class description:
Implement the BM25Data class.
Method signatures and docstrings:
- def __init__(self, tokenize_fn, wiki_data=None, data_path: Optional[str]='/opt/ml/data/', context_path: Optional[str]='wikipedia_documents.json') -> NoReturn: Arguments: tokenize... | 25a539d3e934e426450d74cd4223d903875af533 | <|skeleton|>
class BM25Data:
def __init__(self, tokenize_fn, wiki_data=None, data_path: Optional[str]='/opt/ml/data/', context_path: Optional[str]='wikipedia_documents.json') -> NoReturn:
"""Arguments: tokenize_fn: 기본 text를 tokenize해주는 함수입니다. 아래와 같은 함수들을 사용할 수 있습니다. - lambda x: x.split(' ') - Huggingface T... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BM25Data:
def __init__(self, tokenize_fn, wiki_data=None, data_path: Optional[str]='/opt/ml/data/', context_path: Optional[str]='wikipedia_documents.json') -> NoReturn:
"""Arguments: tokenize_fn: 기본 text를 tokenize해주는 함수입니다. 아래와 같은 함수들을 사용할 수 있습니다. - lambda x: x.split(' ') - Huggingface Tokenizer - kon... | the_stack_v2_python_sparse | code/retrieval/dense/dpr/dpr_dataset.py | didwodnr123/mrc-level2-nlp-12 | train | 0 | |
1552058a422fc9bce65570bbf0469dc7c96cdb92 | [
"queue = None\nsession = get_current_session()\napp = ReEngageShopify.get_by_url(session.get('shop'))\nqueue = get_list_item(app.queues, 0)\nqueue_uuid = self.request.get('queue_uuid', '')\nif queue_uuid:\n queue = ReEngageQueue.get(queue_uuid)\npage = self.render_page('reengage/queue.html', {'debug': USING_DEV_... | <|body_start_0|>
queue = None
session = get_current_session()
app = ReEngageShopify.get_by_url(session.get('shop'))
queue = get_list_item(app.queues, 0)
queue_uuid = self.request.get('queue_uuid', '')
if queue_uuid:
queue = ReEngageQueue.get(queue_uuid)
... | A resource for accessing queues using HTML | ReEngageQueueHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReEngageQueueHandler:
"""A resource for accessing queues using HTML"""
def get(self):
"""Get all queued elements for a shop"""
<|body_0|>
def post(self):
"""Create a new post element in the queue"""
<|body_1|>
def delete(self):
"""Delete all ... | stack_v2_sparse_classes_75kplus_train_005168 | 12,697 | no_license | [
{
"docstring": "Get all queued elements for a shop",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Create a new post element in the queue",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "Delete all post elements in this queue",
"name": "dele... | 3 | stack_v2_sparse_classes_30k_train_032642 | Implement the Python class `ReEngageQueueHandler` described below.
Class description:
A resource for accessing queues using HTML
Method signatures and docstrings:
- def get(self): Get all queued elements for a shop
- def post(self): Create a new post element in the queue
- def delete(self): Delete all post elements i... | Implement the Python class `ReEngageQueueHandler` described below.
Class description:
A resource for accessing queues using HTML
Method signatures and docstrings:
- def get(self): Get all queued elements for a shop
- def post(self): Create a new post element in the queue
- def delete(self): Delete all post elements i... | d1e046d5b7bf1ba0febb337a31ec04f5888fb341 | <|skeleton|>
class ReEngageQueueHandler:
"""A resource for accessing queues using HTML"""
def get(self):
"""Get all queued elements for a shop"""
<|body_0|>
def post(self):
"""Create a new post element in the queue"""
<|body_1|>
def delete(self):
"""Delete all ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ReEngageQueueHandler:
"""A resource for accessing queues using HTML"""
def get(self):
"""Get all queued elements for a shop"""
queue = None
session = get_current_session()
app = ReEngageShopify.get_by_url(session.get('shop'))
queue = get_list_item(app.queues, 0)
... | the_stack_v2_python_sparse | apps/reengage/resources.py | bbarclay/Willet-Referrals | train | 0 |
0510b7b92de218233c6649a7fa3f4ae176eea17b | [
"if arr is None:\n return arr\nn = len(arr)\nif n <= 1:\n return arr\nfor i in range(0, n):\n for j in range(0, n - i - 1):\n if arr[j] > arr[j + 1]:\n arr[j + 1], arr[j] = (arr[j], arr[j + 1])\nreturn arr",
"if arr is None:\n return arr\nn = len(arr)\nif n <= 1:\n return arr\nfor... | <|body_start_0|>
if arr is None:
return arr
n = len(arr)
if n <= 1:
return arr
for i in range(0, n):
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j + 1], arr[j] = (arr[j], arr[j + 1])
return arr
... | BubbleSort | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BubbleSort:
def bubble_sort(arr):
"""Bubble sort. :param arr: List[int], list to be sorted :return: List[int], sorted list"""
<|body_0|>
def bubble_sort_optimized(arr):
"""Optimized bubble sort. :param arr: List[int], list to be sorted :return: List[int], sorted list... | stack_v2_sparse_classes_75kplus_train_005169 | 2,435 | permissive | [
{
"docstring": "Bubble sort. :param arr: List[int], list to be sorted :return: List[int], sorted list",
"name": "bubble_sort",
"signature": "def bubble_sort(arr)"
},
{
"docstring": "Optimized bubble sort. :param arr: List[int], list to be sorted :return: List[int], sorted list",
"name": "bub... | 2 | stack_v2_sparse_classes_30k_train_025522 | Implement the Python class `BubbleSort` described below.
Class description:
Implement the BubbleSort class.
Method signatures and docstrings:
- def bubble_sort(arr): Bubble sort. :param arr: List[int], list to be sorted :return: List[int], sorted list
- def bubble_sort_optimized(arr): Optimized bubble sort. :param ar... | Implement the Python class `BubbleSort` described below.
Class description:
Implement the BubbleSort class.
Method signatures and docstrings:
- def bubble_sort(arr): Bubble sort. :param arr: List[int], list to be sorted :return: List[int], sorted list
- def bubble_sort_optimized(arr): Optimized bubble sort. :param ar... | 8504db89a3f6a1596c0bb7343a4936884b44e6ea | <|skeleton|>
class BubbleSort:
def bubble_sort(arr):
"""Bubble sort. :param arr: List[int], list to be sorted :return: List[int], sorted list"""
<|body_0|>
def bubble_sort_optimized(arr):
"""Optimized bubble sort. :param arr: List[int], list to be sorted :return: List[int], sorted list... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BubbleSort:
def bubble_sort(arr):
"""Bubble sort. :param arr: List[int], list to be sorted :return: List[int], sorted list"""
if arr is None:
return arr
n = len(arr)
if n <= 1:
return arr
for i in range(0, n):
for j in range(0, n - i ... | the_stack_v2_python_sparse | sorting/bubble_sort.py | fimh/dsa-py | train | 2 | |
46f324c5e26717807963c5ebe1bd34e28eacbc0e | [
"worlds = World.objects.all()\nserializer = WorldListSerializer(worlds, many=True)\nreturn Response(serializer.data)",
"queryset = World.objects.all()\nworld = get_object_or_404(queryset, pk=pk)\nserializer = WorldSerializer(world)\nreturn Response(serializer.data)"
] | <|body_start_0|>
worlds = World.objects.all()
serializer = WorldListSerializer(worlds, many=True)
return Response(serializer.data)
<|end_body_0|>
<|body_start_1|>
queryset = World.objects.all()
world = get_object_or_404(queryset, pk=pk)
serializer = WorldSerializer(world... | WorldsView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorldsView:
def list(self, request):
"""Получение списка миров"""
<|body_0|>
def retrieve(self, request, pk=None):
"""Получение мира по идентификатору pk = идентификатор мира"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
worlds = World.objects.all... | stack_v2_sparse_classes_75kplus_train_005170 | 12,404 | no_license | [
{
"docstring": "Получение списка миров",
"name": "list",
"signature": "def list(self, request)"
},
{
"docstring": "Получение мира по идентификатору pk = идентификатор мира",
"name": "retrieve",
"signature": "def retrieve(self, request, pk=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_028753 | Implement the Python class `WorldsView` described below.
Class description:
Implement the WorldsView class.
Method signatures and docstrings:
- def list(self, request): Получение списка миров
- def retrieve(self, request, pk=None): Получение мира по идентификатору pk = идентификатор мира | Implement the Python class `WorldsView` described below.
Class description:
Implement the WorldsView class.
Method signatures and docstrings:
- def list(self, request): Получение списка миров
- def retrieve(self, request, pk=None): Получение мира по идентификатору pk = идентификатор мира
<|skeleton|>
class WorldsVie... | be47a0a6f50bf8680b22e0b9cae3e3b34a198a3d | <|skeleton|>
class WorldsView:
def list(self, request):
"""Получение списка миров"""
<|body_0|>
def retrieve(self, request, pk=None):
"""Получение мира по идентификатору pk = идентификатор мира"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WorldsView:
def list(self, request):
"""Получение списка миров"""
worlds = World.objects.all()
serializer = WorldListSerializer(worlds, many=True)
return Response(serializer.data)
def retrieve(self, request, pk=None):
"""Получение мира по идентификатору pk = иденти... | the_stack_v2_python_sparse | StarfinderBack/starfinder/views.py | Skirgus/StarfinderMasterAssistant | train | 0 | |
972f907c31c70f3290858d086c6d52e3081225b5 | [
"try:\n cur.execute('INSERT INTO tbl_offices(name,type) VALUES(%s ,%s) RETURNING *', (office_name, office_type))\n office_data = cur.fetchall()\n return make_response(jsonify({'status': 201, 'message': 'Office added successfully', 'data': office_data}), 201)\nexcept (Exception, psycopg2.DatabaseError) as e... | <|body_start_0|>
try:
cur.execute('INSERT INTO tbl_offices(name,type) VALUES(%s ,%s) RETURNING *', (office_name, office_type))
office_data = cur.fetchall()
return make_response(jsonify({'status': 201, 'message': 'Office added successfully', 'data': office_data}), 201)
... | Office | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Office:
def add_office(office_name, office_type):
"""This method saves Office data and adds it to the offices table"""
<|body_0|>
def get_all_offices(self):
"""querying the database to get all users"""
<|body_1|>
def get_office(self, office_id):
... | stack_v2_sparse_classes_75kplus_train_005171 | 3,191 | permissive | [
{
"docstring": "This method saves Office data and adds it to the offices table",
"name": "add_office",
"signature": "def add_office(office_name, office_type)"
},
{
"docstring": "querying the database to get all users",
"name": "get_all_offices",
"signature": "def get_all_offices(self)"
... | 5 | stack_v2_sparse_classes_30k_val_000912 | Implement the Python class `Office` described below.
Class description:
Implement the Office class.
Method signatures and docstrings:
- def add_office(office_name, office_type): This method saves Office data and adds it to the offices table
- def get_all_offices(self): querying the database to get all users
- def get... | Implement the Python class `Office` described below.
Class description:
Implement the Office class.
Method signatures and docstrings:
- def add_office(office_name, office_type): This method saves Office data and adds it to the offices table
- def get_all_offices(self): querying the database to get all users
- def get... | e2b8f4c3f027520ae6294bc1df24599ebe23f86d | <|skeleton|>
class Office:
def add_office(office_name, office_type):
"""This method saves Office data and adds it to the offices table"""
<|body_0|>
def get_all_offices(self):
"""querying the database to get all users"""
<|body_1|>
def get_office(self, office_id):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Office:
def add_office(office_name, office_type):
"""This method saves Office data and adds it to the offices table"""
try:
cur.execute('INSERT INTO tbl_offices(name,type) VALUES(%s ,%s) RETURNING *', (office_name, office_type))
office_data = cur.fetchall()
... | the_stack_v2_python_sparse | app/api/v2/office/Office_Model.py | kiariepeter/politicov1 | train | 1 | |
2bd0b4cb6b1f05c859fa785caa8b292446bf9bed | [
"Drawable.__init__(self, RIDE_SPRITE)\nself.start, self.end = (start, end)\nself.start_time, self.end_time = (times[0], times[1])",
"initial_longitude = self.start.location[0]\ninitial_latitude = self.start.location[1]\nfinal_longitude = self.end.location[0]\nfinal_latitude = self.end.location[1]\ntime_difference... | <|body_start_0|>
Drawable.__init__(self, RIDE_SPRITE)
self.start, self.end = (start, end)
self.start_time, self.end_time = (times[0], times[1])
<|end_body_0|>
<|body_start_1|>
initial_longitude = self.start.location[0]
initial_latitude = self.start.location[1]
final_long... | A ride using a Bixi bike. === Attributes === start: the station where this ride starts end: the station where this ride ends start_time: the time this ride starts end_time: the time this ride ends === Representation Invariants === - start_time < end_time | Ride | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ride:
"""A ride using a Bixi bike. === Attributes === start: the station where this ride starts end: the station where this ride ends start_time: the time this ride starts end_time: the time this ride ends === Representation Invariants === - start_time < end_time"""
def __init__(self, start:... | stack_v2_sparse_classes_75kplus_train_005172 | 9,715 | no_license | [
{
"docstring": "Initialize a ride object with the given start and end information.",
"name": "__init__",
"signature": "def __init__(self, start: Station, end: Station, times: Tuple[datetime, datetime]) -> None"
},
{
"docstring": "Return the (long, lat) position of this ride for the given time. A... | 3 | stack_v2_sparse_classes_30k_train_010444 | Implement the Python class `Ride` described below.
Class description:
A ride using a Bixi bike. === Attributes === start: the station where this ride starts end: the station where this ride ends start_time: the time this ride starts end_time: the time this ride ends === Representation Invariants === - start_time < end... | Implement the Python class `Ride` described below.
Class description:
A ride using a Bixi bike. === Attributes === start: the station where this ride starts end: the station where this ride ends start_time: the time this ride starts end_time: the time this ride ends === Representation Invariants === - start_time < end... | 01185e1eab994b42d7e0ec33223eed742b83233e | <|skeleton|>
class Ride:
"""A ride using a Bixi bike. === Attributes === start: the station where this ride starts end: the station where this ride ends start_time: the time this ride starts end_time: the time this ride ends === Representation Invariants === - start_time < end_time"""
def __init__(self, start:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Ride:
"""A ride using a Bixi bike. === Attributes === start: the station where this ride starts end: the station where this ride ends start_time: the time this ride starts end_time: the time this ride ends === Representation Invariants === - start_time < end_time"""
def __init__(self, start: Station, end... | the_stack_v2_python_sparse | CSC148/assignments/a1/backup/bikeshare.py | rcase31/UofTCourses | train | 1 |
86b4d576315d9603c2b98d08eb40655ff2e2695b | [
"if self.default != '':\n if self.value == '':\n self.value = self.default\nelif self.value == '' and self.required:\n raise ValidationError('Required.')\nif self.value != '' and self.type == self.TYPE_FLOAT:\n try:\n float(self.value)\n except Exception:\n raise ValidationError('Va... | <|body_start_0|>
if self.default != '':
if self.value == '':
self.value = self.default
elif self.value == '' and self.required:
raise ValidationError('Required.')
if self.value != '' and self.type == self.TYPE_FLOAT:
try:
float(... | Used to define a Custom Simple Setting. Attributes: name(str): Unique name used to identify the setting. type(enum): The type of the custom setting. Either CustomSetting.TYPE_STRING, CustomSetting.TYPE_INTEGER, CustomSetting.TYPE_FLOAT, CustomSetting.TYPE_BOOLEAN, CustomSetting.TYPE_UUID description(str): Short descrip... | CustomSetting | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomSetting:
"""Used to define a Custom Simple Setting. Attributes: name(str): Unique name used to identify the setting. type(enum): The type of the custom setting. Either CustomSetting.TYPE_STRING, CustomSetting.TYPE_INTEGER, CustomSetting.TYPE_FLOAT, CustomSetting.TYPE_BOOLEAN, CustomSetting.... | stack_v2_sparse_classes_75kplus_train_005173 | 45,827 | permissive | [
{
"docstring": "Validate prior to saving changes.",
"name": "clean",
"signature": "def clean(self)"
},
{
"docstring": "Get the value, automatically casting it to the correct type.",
"name": "get_value",
"signature": "def get_value(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_034581 | Implement the Python class `CustomSetting` described below.
Class description:
Used to define a Custom Simple Setting. Attributes: name(str): Unique name used to identify the setting. type(enum): The type of the custom setting. Either CustomSetting.TYPE_STRING, CustomSetting.TYPE_INTEGER, CustomSetting.TYPE_FLOAT, Cus... | Implement the Python class `CustomSetting` described below.
Class description:
Used to define a Custom Simple Setting. Attributes: name(str): Unique name used to identify the setting. type(enum): The type of the custom setting. Either CustomSetting.TYPE_STRING, CustomSetting.TYPE_INTEGER, CustomSetting.TYPE_FLOAT, Cus... | e9365fa55ec25d7658a75ca7fb0632013374d876 | <|skeleton|>
class CustomSetting:
"""Used to define a Custom Simple Setting. Attributes: name(str): Unique name used to identify the setting. type(enum): The type of the custom setting. Either CustomSetting.TYPE_STRING, CustomSetting.TYPE_INTEGER, CustomSetting.TYPE_FLOAT, CustomSetting.TYPE_BOOLEAN, CustomSetting.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CustomSetting:
"""Used to define a Custom Simple Setting. Attributes: name(str): Unique name used to identify the setting. type(enum): The type of the custom setting. Either CustomSetting.TYPE_STRING, CustomSetting.TYPE_INTEGER, CustomSetting.TYPE_FLOAT, CustomSetting.TYPE_BOOLEAN, CustomSetting.TYPE_UUID des... | the_stack_v2_python_sparse | tethys_apps/models.py | tethysplatform/tethys | train | 95 |
b126f8e87108275baf753efd34d56892c87f405e | [
"if not s:\n return s\nlow, high = (-1, -1)\nfor i in range(len(s)):\n strlen = max(self.expandFromPivot(s, i, i), self.expandFromPivot(s, i, i + 1))\n if strlen > high - low:\n if strlen % 2 == 0:\n low = i - strlen // 2 + 1\n high = i + 1 + strlen // 2\n else:\n ... | <|body_start_0|>
if not s:
return s
low, high = (-1, -1)
for i in range(len(s)):
strlen = max(self.expandFromPivot(s, i, i), self.expandFromPivot(s, i, i + 1))
if strlen > high - low:
if strlen % 2 == 0:
low = i - strlen // ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestPalindrome(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def expandFromPivot(self, s, l, r):
"""Expand palindrome substring from a pivot. `l` and `r` are valid string indices of string `s`, from which to expand the palindrome substring."""
... | stack_v2_sparse_classes_75kplus_train_005174 | 5,738 | no_license | [
{
"docstring": ":type s: str :rtype: str",
"name": "longestPalindrome",
"signature": "def longestPalindrome(self, s)"
},
{
"docstring": "Expand palindrome substring from a pivot. `l` and `r` are valid string indices of string `s`, from which to expand the palindrome substring.",
"name": "exp... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome(self, s): :type s: str :rtype: str
- def expandFromPivot(self, s, l, r): Expand palindrome substring from a pivot. `l` and `r` are valid string indices of s... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome(self, s): :type s: str :rtype: str
- def expandFromPivot(self, s, l, r): Expand palindrome substring from a pivot. `l` and `r` are valid string indices of s... | 69a960dd8f39e9c8435a3678852071e1085fcb72 | <|skeleton|>
class Solution:
def longestPalindrome(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def expandFromPivot(self, s, l, r):
"""Expand palindrome substring from a pivot. `l` and `r` are valid string indices of string `s`, from which to expand the palindrome substring."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def longestPalindrome(self, s):
""":type s: str :rtype: str"""
if not s:
return s
low, high = (-1, -1)
for i in range(len(s)):
strlen = max(self.expandFromPivot(s, i, i), self.expandFromPivot(s, i, i + 1))
if strlen > high - low:
... | the_stack_v2_python_sparse | python/dp/2d_string/lc5.py | chao-ji/LeetCode | train | 1 | |
c260f98429f2a4ac80419689c1f658c1bd8179b8 | [
"self.assertTrue(anagram('cinema', 'iceman'))\nself.assertTrue(anagram('dormitory', 'dirtyroom'))\nself.assertFalse(anagram('hello', 'lohae'))\nself.assertFalse(anagram('ill', 'like'))\nself.assertFalse(anagram('illness', 'nes'))",
"self.assertTrue(anagram_dd('cinema', 'iceman'))\nself.assertTrue(anagram_dd('dorm... | <|body_start_0|>
self.assertTrue(anagram('cinema', 'iceman'))
self.assertTrue(anagram('dormitory', 'dirtyroom'))
self.assertFalse(anagram('hello', 'lohae'))
self.assertFalse(anagram('ill', 'like'))
self.assertFalse(anagram('illness', 'nes'))
<|end_body_0|>
<|body_start_1|>
... | verify that functions works fine | FunctionTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FunctionTest:
"""verify that functions works fine"""
def test_anagram(self):
"""verify anagram works fine"""
<|body_0|>
def test_anagram_dd(self):
"""verify anagram_dd works fine"""
<|body_1|>
def test_book_index(self):
"""verify that book_in... | stack_v2_sparse_classes_75kplus_train_005175 | 2,565 | no_license | [
{
"docstring": "verify anagram works fine",
"name": "test_anagram",
"signature": "def test_anagram(self)"
},
{
"docstring": "verify anagram_dd works fine",
"name": "test_anagram_dd",
"signature": "def test_anagram_dd(self)"
},
{
"docstring": "verify that book_index works fine",
... | 3 | stack_v2_sparse_classes_30k_test_000679 | Implement the Python class `FunctionTest` described below.
Class description:
verify that functions works fine
Method signatures and docstrings:
- def test_anagram(self): verify anagram works fine
- def test_anagram_dd(self): verify anagram_dd works fine
- def test_book_index(self): verify that book_index works fine | Implement the Python class `FunctionTest` described below.
Class description:
verify that functions works fine
Method signatures and docstrings:
- def test_anagram(self): verify anagram works fine
- def test_anagram_dd(self): verify anagram_dd works fine
- def test_book_index(self): verify that book_index works fine
... | f45bd7c20e91584428c90a332173ee9c8fa66a4c | <|skeleton|>
class FunctionTest:
"""verify that functions works fine"""
def test_anagram(self):
"""verify anagram works fine"""
<|body_0|>
def test_anagram_dd(self):
"""verify anagram_dd works fine"""
<|body_1|>
def test_book_index(self):
"""verify that book_in... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FunctionTest:
"""verify that functions works fine"""
def test_anagram(self):
"""verify anagram works fine"""
self.assertTrue(anagram('cinema', 'iceman'))
self.assertTrue(anagram('dormitory', 'dirtyroom'))
self.assertFalse(anagram('hello', 'lohae'))
self.assertFalse... | the_stack_v2_python_sparse | HanrunLiHW07.py | obleevious/SSW810Final_repo | train | 0 |
d4aeea5cb4217bc6e19be85636d60f4a7ff15b07 | [
"ret = []\nfor x in self:\n ret.append(x)\nreturn ret",
"ret = None\ntry:\n cur = self.__iter__()\n ret = cur.next()\nexcept StopIteration:\n ret = None\nreturn ret",
"self._arguments = arguments\nself._query = query\nself._connection = connection",
"if self._arguments != None:\n return scon_it... | <|body_start_0|>
ret = []
for x in self:
ret.append(x)
return ret
<|end_body_0|>
<|body_start_1|>
ret = None
try:
cur = self.__iter__()
ret = cur.next()
except StopIteration:
ret = None
return ret
<|end_body_1|>
<|... | rief cursor to iterate on sqltie query result. Iteration will return hash tables with key = field name and value = value | scon_cursor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class scon_cursor:
"""rief cursor to iterate on sqltie query result. Iteration will return hash tables with key = field name and value = value"""
def fetchall(self):
"""fetch all hash tables"""
<|body_0|>
def fetchone(self):
"""rief fetch one argument or return None ... | stack_v2_sparse_classes_75kplus_train_005176 | 6,787 | no_license | [
{
"docstring": "fetch all hash tables",
"name": "fetchall",
"signature": "def fetchall(self)"
},
{
"docstring": "\brief fetch one argument or return None if no one exists",
"name": "fetchone",
"signature": "def fetchone(self)"
},
{
"docstring": "initializes cursor \\\\param curso... | 4 | null | Implement the Python class `scon_cursor` described below.
Class description:
rief cursor to iterate on sqltie query result. Iteration will return hash tables with key = field name and value = value
Method signatures and docstrings:
- def fetchall(self): fetch all hash tables
- def fetchone(self): rief fetch one arg... | Implement the Python class `scon_cursor` described below.
Class description:
rief cursor to iterate on sqltie query result. Iteration will return hash tables with key = field name and value = value
Method signatures and docstrings:
- def fetchall(self): fetch all hash tables
- def fetchone(self): rief fetch one arg... | eb151afa9ee939ed7943da9eeed1e976ac816fec | <|skeleton|>
class scon_cursor:
"""rief cursor to iterate on sqltie query result. Iteration will return hash tables with key = field name and value = value"""
def fetchall(self):
"""fetch all hash tables"""
<|body_0|>
def fetchone(self):
"""rief fetch one argument or return None ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class scon_cursor:
"""rief cursor to iterate on sqltie query result. Iteration will return hash tables with key = field name and value = value"""
def fetchall(self):
"""fetch all hash tables"""
ret = []
for x in self:
ret.append(x)
return ret
def fetchone(self)... | the_stack_v2_python_sparse | src/sconnection.py | s9gf4ult/track-deal | train | 1 |
79399614e4ebc9bd0e28f9c11794a691e82e30b8 | [
"super().__init__(openmm_pdf_state=openmm_pdf_state, integrator=integrator, record_state_work_interval=record_state_work_interval, context_cache=context_cache, reassign_velocities=reassign_velocities, n_restart_attempts=n_restart_attempts)\nself._write_trajectory = False if reporter is None else True\nself.reporter... | <|body_start_0|>
super().__init__(openmm_pdf_state=openmm_pdf_state, integrator=integrator, record_state_work_interval=record_state_work_interval, context_cache=context_cache, reassign_velocities=reassign_velocities, n_restart_attempts=n_restart_attempts)
self._write_trajectory = False if reporter is No... | OpenMMAISP Reportable OMMAISP is a simple subclass of OMMAISP that equips an OpenMMReporter object and writes a trajectory to disk at specified iterations | OMMAISPR | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OMMAISPR:
"""OpenMMAISP Reportable OMMAISP is a simple subclass of OMMAISP that equips an OpenMMReporter object and writes a trajectory to disk at specified iterations"""
def __init__(self, openmm_pdf_state, integrator, record_state_work_interval=None, reporter=None, trajectory_write_interva... | stack_v2_sparse_classes_75kplus_train_005177 | 20,910 | permissive | [
{
"docstring": "see super (i.e. OMMAISP) arguments (new): reporter : coddiwomple.openmm.reporter.OpenMMReporter, default None a reporter object to write trajectories trajectory_write_interval : int, default 1 write the trajectory every trajectory_write_interval intervals",
"name": "__init__",
"signature... | 4 | stack_v2_sparse_classes_30k_train_027091 | Implement the Python class `OMMAISPR` described below.
Class description:
OpenMMAISP Reportable OMMAISP is a simple subclass of OMMAISP that equips an OpenMMReporter object and writes a trajectory to disk at specified iterations
Method signatures and docstrings:
- def __init__(self, openmm_pdf_state, integrator, reco... | Implement the Python class `OMMAISPR` described below.
Class description:
OpenMMAISP Reportable OMMAISP is a simple subclass of OMMAISP that equips an OpenMMReporter object and writes a trajectory to disk at specified iterations
Method signatures and docstrings:
- def __init__(self, openmm_pdf_state, integrator, reco... | 841ac56314b8979b999b847216dd2475509dcc1f | <|skeleton|>
class OMMAISPR:
"""OpenMMAISP Reportable OMMAISP is a simple subclass of OMMAISP that equips an OpenMMReporter object and writes a trajectory to disk at specified iterations"""
def __init__(self, openmm_pdf_state, integrator, record_state_work_interval=None, reporter=None, trajectory_write_interva... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OMMAISPR:
"""OpenMMAISP Reportable OMMAISP is a simple subclass of OMMAISP that equips an OpenMMReporter object and writes a trajectory to disk at specified iterations"""
def __init__(self, openmm_pdf_state, integrator, record_state_work_interval=None, reporter=None, trajectory_write_interval=1, context_... | the_stack_v2_python_sparse | coddiwomple/openmm/propagators.py | LaYeqa/coddiwomple | train | 0 |
3dd0d8edb17023d24740181a00f06d6ec22ff317 | [
"visit_func = getattr(self, f'visit_{type(node).__name__}', None)\nif visit_func is not None:\n retval = visit_func(node)\nelse:\n retval = True\nreturn False if retval is False else True",
"leave_func = getattr(self, f'leave_{type(original_node).__name__}', None)\nif leave_func is not None:\n updated_no... | <|body_start_0|>
visit_func = getattr(self, f'visit_{type(node).__name__}', None)
if visit_func is not None:
retval = visit_func(node)
else:
retval = True
return False if retval is False else True
<|end_body_0|>
<|body_start_1|>
leave_func = getattr(self,... | The low-level base visitor class for traversing a CST and creating an updated copy of the original CST. This should be used in conjunction with the :func:`~libcst.CSTNode.visit` method on a :class:`~libcst.CSTNode` to visit each element in a tree starting with that node, and possibly returning a new node in its place. ... | CSTTransformer | [
"Python-2.0",
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CSTTransformer:
"""The low-level base visitor class for traversing a CST and creating an updated copy of the original CST. This should be used in conjunction with the :func:`~libcst.CSTNode.visit` method on a :class:`~libcst.CSTNode` to visit each element in a tree starting with that node, and po... | stack_v2_sparse_classes_75kplus_train_005178 | 6,835 | permissive | [
{
"docstring": "Called every time a node is visited, before we've visited its children. Returns ``True`` if children should be visited, and returns ``False`` otherwise.",
"name": "on_visit",
"signature": "def on_visit(self, node: 'CSTNode') -> bool"
},
{
"docstring": "Called every time we leave ... | 4 | stack_v2_sparse_classes_30k_train_025924 | Implement the Python class `CSTTransformer` described below.
Class description:
The low-level base visitor class for traversing a CST and creating an updated copy of the original CST. This should be used in conjunction with the :func:`~libcst.CSTNode.visit` method on a :class:`~libcst.CSTNode` to visit each element in... | Implement the Python class `CSTTransformer` described below.
Class description:
The low-level base visitor class for traversing a CST and creating an updated copy of the original CST. This should be used in conjunction with the :func:`~libcst.CSTNode.visit` method on a :class:`~libcst.CSTNode` to visit each element in... | 9286446f889f1778b8f11451a68107052b2930b3 | <|skeleton|>
class CSTTransformer:
"""The low-level base visitor class for traversing a CST and creating an updated copy of the original CST. This should be used in conjunction with the :func:`~libcst.CSTNode.visit` method on a :class:`~libcst.CSTNode` to visit each element in a tree starting with that node, and po... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CSTTransformer:
"""The low-level base visitor class for traversing a CST and creating an updated copy of the original CST. This should be used in conjunction with the :func:`~libcst.CSTNode.visit` method on a :class:`~libcst.CSTNode` to visit each element in a tree starting with that node, and possibly return... | the_stack_v2_python_sparse | libcst/_visitors.py | Instagram/LibCST | train | 1,300 |
e5d1fbd725e3dcfa1fa4c667e06a871641547634 | [
"user = User.objects.create_user(username='some_username', password='some_password', email='some_email@gmail.com')\nProfile.objects.create_player(username='some_username')\ndata = {'username': 'some_username', 'password': 'some_password'}\nresponse = self.client.post(self.url, data)\nself.assertEqual(response.statu... | <|body_start_0|>
user = User.objects.create_user(username='some_username', password='some_password', email='some_email@gmail.com')
Profile.objects.create_player(username='some_username')
data = {'username': 'some_username', 'password': 'some_password'}
response = self.client.post(self.ur... | UserAuthenticationTests | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserAuthenticationTests:
def test_valid_user_auth(self):
"""Ensure we get token in case of correct credentials"""
<|body_0|>
def test_invalid_user_auth(self):
"""Ensure we do not get token in case of wrong credentials"""
<|body_1|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_75kplus_train_005179 | 13,549 | permissive | [
{
"docstring": "Ensure we get token in case of correct credentials",
"name": "test_valid_user_auth",
"signature": "def test_valid_user_auth(self)"
},
{
"docstring": "Ensure we do not get token in case of wrong credentials",
"name": "test_invalid_user_auth",
"signature": "def test_invalid... | 2 | stack_v2_sparse_classes_30k_train_006514 | Implement the Python class `UserAuthenticationTests` described below.
Class description:
Implement the UserAuthenticationTests class.
Method signatures and docstrings:
- def test_valid_user_auth(self): Ensure we get token in case of correct credentials
- def test_invalid_user_auth(self): Ensure we do not get token in... | Implement the Python class `UserAuthenticationTests` described below.
Class description:
Implement the UserAuthenticationTests class.
Method signatures and docstrings:
- def test_valid_user_auth(self): Ensure we get token in case of correct credentials
- def test_invalid_user_auth(self): Ensure we do not get token in... | 9fa31e01c8fc3496f92540081a8c078474d59c0f | <|skeleton|>
class UserAuthenticationTests:
def test_valid_user_auth(self):
"""Ensure we get token in case of correct credentials"""
<|body_0|>
def test_invalid_user_auth(self):
"""Ensure we do not get token in case of wrong credentials"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserAuthenticationTests:
def test_valid_user_auth(self):
"""Ensure we get token in case of correct credentials"""
user = User.objects.create_user(username='some_username', password='some_password', email='some_email@gmail.com')
Profile.objects.create_player(username='some_username')
... | the_stack_v2_python_sparse | player/tests.py | apoorvaeternity/DirectMe | train | 1 | |
2fd698728d8764cb138d2d7b7ea0d806c07c08e4 | [
"self.rewardval = 1.5\nactions = [('left', [1, 0, 0]), ('middle', [0, 1, 0]), ('right', [0, 0, 1])]\nself.num_orientations = 3\nself.num_shapes = 3\nself.num_colours = 2\nself.presentationtime = 0.5\nself.rewardtime = 0.1\nself.presentationperiod = [0, self.presentationtime]\nself.rewardperiod = [self.presentationt... | <|body_start_0|>
self.rewardval = 1.5
actions = [('left', [1, 0, 0]), ('middle', [0, 1, 0]), ('right', [0, 0, 1])]
self.num_orientations = 3
self.num_shapes = 3
self.num_colours = 2
self.presentationtime = 0.5
self.rewardtime = 0.1
self.presentationperiod ... | Environment to recreate the task from Badre et al. (2010) 'Frontal cortex and the discovery of abstract action rules.' :input action: vector representing action selected by agent :output state: vector representing current state :output reward: reward value | BadreEnvironment | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BadreEnvironment:
"""Environment to recreate the task from Badre et al. (2010) 'Frontal cortex and the discovery of abstract action rules.' :input action: vector representing action selected by agent :output state: vector representing current state :output reward: reward value"""
def __init_... | stack_v2_sparse_classes_75kplus_train_005180 | 6,838 | no_license | [
{
"docstring": "Set up task parameters. :param flat: if True, no hierarchical relationship between stimuli and reward; if False, stimuli-response rewards will be dependent on colour",
"name": "__init__",
"signature": "def __init__(self, flat=False)"
},
{
"docstring": "Update state/reward each ti... | 4 | null | Implement the Python class `BadreEnvironment` described below.
Class description:
Environment to recreate the task from Badre et al. (2010) 'Frontal cortex and the discovery of abstract action rules.' :input action: vector representing action selected by agent :output state: vector representing current state :output r... | Implement the Python class `BadreEnvironment` described below.
Class description:
Environment to recreate the task from Badre et al. (2010) 'Frontal cortex and the discovery of abstract action rules.' :input action: vector representing action selected by agent :output state: vector representing current state :output r... | c9511b40ffa1f70bc924ee578bf4e4d45013ba71 | <|skeleton|>
class BadreEnvironment:
"""Environment to recreate the task from Badre et al. (2010) 'Frontal cortex and the discovery of abstract action rules.' :input action: vector representing action selected by agent :output state: vector representing current state :output reward: reward value"""
def __init_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BadreEnvironment:
"""Environment to recreate the task from Badre et al. (2010) 'Frontal cortex and the discovery of abstract action rules.' :input action: vector representing action selected by agent :output state: vector representing current state :output reward: reward value"""
def __init__(self, flat=... | the_stack_v2_python_sparse | HRLproject/hrlproject/environment/badreenvironment.py | Seanny123/HRL_1.0 | train | 0 |
975296a4650182c30efa9be0b715349428d05f5b | [
"lst = []\nfor i in range(1, n + 1):\n s = str(i)\n for j in s:\n lst.append(j)\nreturn int(lst[n - 1])",
"groups = [9, 180, 2700, 36000, 450000, 5400000, 63000000, 720000000, 8100000000]\ng = bisect.bisect_left(groups, n)\nnth = n - sum(groups[:g]) - 1\nd, m = divmod(nth, g + 1)\nnumber = d + pow(10... | <|body_start_0|>
lst = []
for i in range(1, n + 1):
s = str(i)
for j in s:
lst.append(j)
return int(lst[n - 1])
<|end_body_0|>
<|body_start_1|>
groups = [9, 180, 2700, 36000, 450000, 5400000, 63000000, 720000000, 8100000000]
g = bisect.bis... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findNthDigit1(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def findNthDigit(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
lst = []
for i in range(1, n + 1):
s = str(i)
... | stack_v2_sparse_classes_75kplus_train_005181 | 3,069 | no_license | [
{
"docstring": ":type n: int :rtype: int",
"name": "findNthDigit1",
"signature": "def findNthDigit1(self, n)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "findNthDigit",
"signature": "def findNthDigit(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006575 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findNthDigit1(self, n): :type n: int :rtype: int
- def findNthDigit(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 findNthDigit1(self, n): :type n: int :rtype: int
- def findNthDigit(self, n): :type n: int :rtype: int
<|skeleton|>
class Solution:
def findNthDigit1(self, n):
... | a57282895fb213b68e5d81db301903721a92d80f | <|skeleton|>
class Solution:
def findNthDigit1(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def findNthDigit(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findNthDigit1(self, n):
""":type n: int :rtype: int"""
lst = []
for i in range(1, n + 1):
s = str(i)
for j in s:
lst.append(j)
return int(lst[n - 1])
def findNthDigit(self, n):
""":type n: int :rtype: int"""
... | the_stack_v2_python_sparse | Python/400_nth-digit.py | antonylu/leetcode2 | train | 0 | |
b39795708d4d5963a24f4d4d564ecaca3d3cfd45 | [
"is_unenrolled_access_enabled = COURSE_ENABLE_UNENROLLED_ACCESS_FLAG.is_enabled(self.course_key)\nis_course_outline_publicly_visible = full_course_outline.course_visibility in [CourseVisibility.PUBLIC, CourseVisibility.PUBLIC_OUTLINE]\nif is_unenrolled_access_enabled and is_course_outline_publicly_visible:\n ret... | <|body_start_0|>
is_unenrolled_access_enabled = COURSE_ENABLE_UNENROLLED_ACCESS_FLAG.is_enabled(self.course_key)
is_course_outline_publicly_visible = full_course_outline.course_visibility in [CourseVisibility.PUBLIC, CourseVisibility.PUBLIC_OUTLINE]
if is_unenrolled_access_enabled and is_course_... | Simple OutlineProcessor that removes items based on Enrollment and course visibility setting. | EnrollmentOutlineProcessor | [
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EnrollmentOutlineProcessor:
"""Simple OutlineProcessor that removes items based on Enrollment and course visibility setting."""
def usage_keys_to_remove(self, full_course_outline):
"""Return sequences/sections to be removed"""
<|body_0|>
def inaccessible_sequences(self, ... | stack_v2_sparse_classes_75kplus_train_005182 | 1,997 | permissive | [
{
"docstring": "Return sequences/sections to be removed",
"name": "usage_keys_to_remove",
"signature": "def usage_keys_to_remove(self, full_course_outline)"
},
{
"docstring": "Return a set/frozenset of Sequence UsageKeys that are not accessible.",
"name": "inaccessible_sequences",
"signa... | 2 | stack_v2_sparse_classes_30k_train_020091 | Implement the Python class `EnrollmentOutlineProcessor` described below.
Class description:
Simple OutlineProcessor that removes items based on Enrollment and course visibility setting.
Method signatures and docstrings:
- def usage_keys_to_remove(self, full_course_outline): Return sequences/sections to be removed
- d... | Implement the Python class `EnrollmentOutlineProcessor` described below.
Class description:
Simple OutlineProcessor that removes items based on Enrollment and course visibility setting.
Method signatures and docstrings:
- def usage_keys_to_remove(self, full_course_outline): Return sequences/sections to be removed
- d... | 5809eaca7079a15ee56b0b7fcfea425337046c97 | <|skeleton|>
class EnrollmentOutlineProcessor:
"""Simple OutlineProcessor that removes items based on Enrollment and course visibility setting."""
def usage_keys_to_remove(self, full_course_outline):
"""Return sequences/sections to be removed"""
<|body_0|>
def inaccessible_sequences(self, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EnrollmentOutlineProcessor:
"""Simple OutlineProcessor that removes items based on Enrollment and course visibility setting."""
def usage_keys_to_remove(self, full_course_outline):
"""Return sequences/sections to be removed"""
is_unenrolled_access_enabled = COURSE_ENABLE_UNENROLLED_ACCESS... | the_stack_v2_python_sparse | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/openedx/core/djangoapps/content/learning_sequences/api/processors/enrollment.py | luque/better-ways-of-thinking-about-software | train | 3 |
64e933d44698cf023c0a1cb2064ded12f2a7a2cb | [
"if requests is not None and responses is not None:\n responses.add(**{'method': responses.GET, 'url': BASE_API_URL, 'body': '{\"Blueliv_error\": \"Fake error\"}', 'status': 404, 'content_type': 'application/json', 'adding_headers': {'X-Blueliv-Fake-Header': 'Fake'}})\n response = requests.get(BASE_API_URL)\n... | <|body_start_0|>
if requests is not None and responses is not None:
responses.add(**{'method': responses.GET, 'url': BASE_API_URL, 'body': '{"Blueliv_error": "Fake error"}', 'status': 404, 'content_type': 'application/json', 'adding_headers': {'X-Blueliv-Fake-Header': 'Fake'}})
response ... | Tests oriented to verify the remote API endpoint is working fine. | RemoteEndpointTests | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RemoteEndpointTests:
"""Tests oriented to verify the remote API endpoint is working fine."""
def test_fake_request_and_response(self):
"""This is a fake connection test (using responses package). :return: nothing as this is a test case."""
<|body_0|>
def test_remote_endp... | stack_v2_sparse_classes_75kplus_train_005183 | 8,568 | permissive | [
{
"docstring": "This is a fake connection test (using responses package). :return: nothing as this is a test case.",
"name": "test_fake_request_and_response",
"signature": "def test_fake_request_and_response(self)"
},
{
"docstring": "This is a real connection test (using requests package). As we... | 2 | stack_v2_sparse_classes_30k_train_029982 | Implement the Python class `RemoteEndpointTests` described below.
Class description:
Tests oriented to verify the remote API endpoint is working fine.
Method signatures and docstrings:
- def test_fake_request_and_response(self): This is a fake connection test (using responses package). :return: nothing as this is a t... | Implement the Python class `RemoteEndpointTests` described below.
Class description:
Tests oriented to verify the remote API endpoint is working fine.
Method signatures and docstrings:
- def test_fake_request_and_response(self): This is a fake connection test (using responses package). :return: nothing as this is a t... | c2a3c919096d25ad148e9e1d91e7399e11e5fa3a | <|skeleton|>
class RemoteEndpointTests:
"""Tests oriented to verify the remote API endpoint is working fine."""
def test_fake_request_and_response(self):
"""This is a fake connection test (using responses package). :return: nothing as this is a test case."""
<|body_0|>
def test_remote_endp... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RemoteEndpointTests:
"""Tests oriented to verify the remote API endpoint is working fine."""
def test_fake_request_and_response(self):
"""This is a fake connection test (using responses package). :return: nothing as this is a test case."""
if requests is not None and responses is not None... | the_stack_v2_python_sparse | tests.py | patowc/blueliv | train | 3 |
51268626e17402dd27ff8f3f689c3fbf1e94cad0 | [
"m_bin = bin(m)[2:]\ndiff = n - m\nans = 0\nfor i in range(len(m_bin)):\n if m_bin[-1 - i] == '1':\n cur = int(m_bin[-1 - i:], 2)\n moves_to_change = (1 << i + 1) - cur\n if moves_to_change > diff:\n ans |= 1 << i\nreturn ans",
"digit = 1\nwhile m != n:\n digit <<= 1\n m >... | <|body_start_0|>
m_bin = bin(m)[2:]
diff = n - m
ans = 0
for i in range(len(m_bin)):
if m_bin[-1 - i] == '1':
cur = int(m_bin[-1 - i:], 2)
moves_to_change = (1 << i + 1) - cur
if moves_to_change > diff:
ans |... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rangeBitwiseAnd(self, m, n):
""":type m: int :type n: int :rtype: int"""
<|body_0|>
def rangeBitwiseAnd2(self, m, n):
""":type m: int :type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
m_bin = bin(m)[2:]
d... | stack_v2_sparse_classes_75kplus_train_005184 | 853 | no_license | [
{
"docstring": ":type m: int :type n: int :rtype: int",
"name": "rangeBitwiseAnd",
"signature": "def rangeBitwiseAnd(self, m, n)"
},
{
"docstring": ":type m: int :type n: int :rtype: int",
"name": "rangeBitwiseAnd2",
"signature": "def rangeBitwiseAnd2(self, m, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_043346 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rangeBitwiseAnd(self, m, n): :type m: int :type n: int :rtype: int
- def rangeBitwiseAnd2(self, m, n): :type m: int :type n: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rangeBitwiseAnd(self, m, n): :type m: int :type n: int :rtype: int
- def rangeBitwiseAnd2(self, m, n): :type m: int :type n: int :rtype: int
<|skeleton|>
class Solution:
... | 0da45559271d3dba687858b8945b3e361ecc813c | <|skeleton|>
class Solution:
def rangeBitwiseAnd(self, m, n):
""":type m: int :type n: int :rtype: int"""
<|body_0|>
def rangeBitwiseAnd2(self, m, n):
""":type m: int :type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def rangeBitwiseAnd(self, m, n):
""":type m: int :type n: int :rtype: int"""
m_bin = bin(m)[2:]
diff = n - m
ans = 0
for i in range(len(m_bin)):
if m_bin[-1 - i] == '1':
cur = int(m_bin[-1 - i:], 2)
moves_to_change =... | the_stack_v2_python_sparse | 201-bitwise-and-numbers-range/solution.py | katryo/leetcode | train | 0 | |
7bf4c7ef6eb124b895dc09f382a7e84a92f0e50f | [
"self.goal = goal\nself.min_step = min_step\nself.max_step = max_step\nself.current = 0\nself.players = players\nself.turn = 0",
"while self.current < self.goal:\n self.play_one_turn()\nwinner = self.whose_turn(self.turn - 1)\nreturn winner.name",
"if turn % 2 == 0:\n return self.players[0]\nelse:\n re... | <|body_start_0|>
self.goal = goal
self.min_step = min_step
self.max_step = max_step
self.current = 0
self.players = players
self.turn = 0
<|end_body_0|>
<|body_start_1|>
while self.current < self.goal:
self.play_one_turn()
winner = self.whose_... | A number game for two players. A count starts at 0. On a player's turn, they add to the count an amount between a set minimum and a set maximum. The player who brings the count to a set goal amount is the winner. The game can have multiple rounds. === Attributes === goal: The amount to reach in order to win the game. m... | NumberGame | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumberGame:
"""A number game for two players. A count starts at 0. On a player's turn, they add to the count an amount between a set minimum and a set maximum. The player who brings the count to a set goal amount is the winner. The game can have multiple rounds. === Attributes === goal: The amoun... | stack_v2_sparse_classes_75kplus_train_005185 | 5,954 | no_license | [
{
"docstring": "Initialize this NumberGame. Preconditions: 0 < min_step <= max_step <= goal",
"name": "__init__",
"signature": "def __init__(self, goal: int, min_step: int, max_step: int, players: Tuple[Player, Player]) -> None"
},
{
"docstring": "Play one round of this NumberGame. Return the na... | 4 | stack_v2_sparse_classes_30k_train_017532 | Implement the Python class `NumberGame` described below.
Class description:
A number game for two players. A count starts at 0. On a player's turn, they add to the count an amount between a set minimum and a set maximum. The player who brings the count to a set goal amount is the winner. The game can have multiple rou... | Implement the Python class `NumberGame` described below.
Class description:
A number game for two players. A count starts at 0. On a player's turn, they add to the count an amount between a set minimum and a set maximum. The player who brings the count to a set goal amount is the winner. The game can have multiple rou... | c4f1a983c18a152de17201b1070cf09be532ce2a | <|skeleton|>
class NumberGame:
"""A number game for two players. A count starts at 0. On a player's turn, they add to the count an amount between a set minimum and a set maximum. The player who brings the count to a set goal amount is the winner. The game can have multiple rounds. === Attributes === goal: The amoun... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NumberGame:
"""A number game for two players. A count starts at 0. On a player's turn, they add to the count an amount between a set minimum and a set maximum. The player who brings the count to a set goal amount is the winner. The game can have multiple rounds. === Attributes === goal: The amount to reach in... | the_stack_v2_python_sparse | csc148/labs/lab3/lab3.py | Kartik-Sangwan/CSC148 | train | 2 |
b1ed43f8249a785d44eb4780d07405a5523ce87a | [
"self.clickLogin()\ntime.sleep(2)\ntest = self.driver.find_element_by_xpath('//*[@id=\"login-form\"]/div[1]/p').text\nself.assertEqual(test, '用户名不能为空。')",
"self.Logins()\ntitle = self.driver.find_element_by_class_name('text-center').text\nself.assertEqual(title, '优装汇')"
] | <|body_start_0|>
self.clickLogin()
time.sleep(2)
test = self.driver.find_element_by_xpath('//*[@id="login-form"]/div[1]/p').text
self.assertEqual(test, '用户名不能为空。')
<|end_body_0|>
<|body_start_1|>
self.Logins()
title = self.driver.find_element_by_class_name('text-center')... | Login | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Login:
def test_login_null(self):
"""验证用户名密码为空"""
<|body_0|>
def test_login_success(self):
"""验证登录成功"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.clickLogin()
time.sleep(2)
test = self.driver.find_element_by_xpath('//*[@id="l... | stack_v2_sparse_classes_75kplus_train_005186 | 644 | no_license | [
{
"docstring": "验证用户名密码为空",
"name": "test_login_null",
"signature": "def test_login_null(self)"
},
{
"docstring": "验证登录成功",
"name": "test_login_success",
"signature": "def test_login_success(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_051735 | Implement the Python class `Login` described below.
Class description:
Implement the Login class.
Method signatures and docstrings:
- def test_login_null(self): 验证用户名密码为空
- def test_login_success(self): 验证登录成功 | Implement the Python class `Login` described below.
Class description:
Implement the Login class.
Method signatures and docstrings:
- def test_login_null(self): 验证用户名密码为空
- def test_login_success(self): 验证登录成功
<|skeleton|>
class Login:
def test_login_null(self):
"""验证用户名密码为空"""
<|body_0|>
d... | 9f8358a53465210dc32e2e61ec7d12a098d3a86e | <|skeleton|>
class Login:
def test_login_null(self):
"""验证用户名密码为空"""
<|body_0|>
def test_login_success(self):
"""验证登录成功"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Login:
def test_login_null(self):
"""验证用户名密码为空"""
self.clickLogin()
time.sleep(2)
test = self.driver.find_element_by_xpath('//*[@id="login-form"]/div[1]/p').text
self.assertEqual(test, '用户名不能为空。')
def test_login_success(self):
"""验证登录成功"""
self.Logi... | the_stack_v2_python_sparse | TestCase/test_login.py | lishuaibin1/UI | train | 0 | |
3ed3271ee557eab71bd20744e2844954fe54f01a | [
"super().__init__(coordinator)\nself.entity_description = description\nself._attr_unique_id = f'{DOMAIN}_{coordinator.data.agreement.agreement_id}_binary_sensor_{description.key}'",
"section = getattr(self.coordinator.data, self.entity_description.section)\nvalue = getattr(section, self.entity_description.measure... | <|body_start_0|>
super().__init__(coordinator)
self.entity_description = description
self._attr_unique_id = f'{DOMAIN}_{coordinator.data.agreement.agreement_id}_binary_sensor_{description.key}'
<|end_body_0|>
<|body_start_1|>
section = getattr(self.coordinator.data, self.entity_descript... | Defines an Toon binary sensor. | ToonBinarySensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ToonBinarySensor:
"""Defines an Toon binary sensor."""
def __init__(self, coordinator: ToonDataUpdateCoordinator, description: ToonBinarySensorEntityDescription) -> None:
"""Initialize the Toon sensor."""
<|body_0|>
def is_on(self) -> bool | None:
"""Return the s... | stack_v2_sparse_classes_75kplus_train_005187 | 5,719 | permissive | [
{
"docstring": "Initialize the Toon sensor.",
"name": "__init__",
"signature": "def __init__(self, coordinator: ToonDataUpdateCoordinator, description: ToonBinarySensorEntityDescription) -> None"
},
{
"docstring": "Return the status of the binary sensor.",
"name": "is_on",
"signature": "... | 2 | stack_v2_sparse_classes_30k_train_033070 | Implement the Python class `ToonBinarySensor` described below.
Class description:
Defines an Toon binary sensor.
Method signatures and docstrings:
- def __init__(self, coordinator: ToonDataUpdateCoordinator, description: ToonBinarySensorEntityDescription) -> None: Initialize the Toon sensor.
- def is_on(self) -> bool... | Implement the Python class `ToonBinarySensor` described below.
Class description:
Defines an Toon binary sensor.
Method signatures and docstrings:
- def __init__(self, coordinator: ToonDataUpdateCoordinator, description: ToonBinarySensorEntityDescription) -> None: Initialize the Toon sensor.
- def is_on(self) -> bool... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class ToonBinarySensor:
"""Defines an Toon binary sensor."""
def __init__(self, coordinator: ToonDataUpdateCoordinator, description: ToonBinarySensorEntityDescription) -> None:
"""Initialize the Toon sensor."""
<|body_0|>
def is_on(self) -> bool | None:
"""Return the s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ToonBinarySensor:
"""Defines an Toon binary sensor."""
def __init__(self, coordinator: ToonDataUpdateCoordinator, description: ToonBinarySensorEntityDescription) -> None:
"""Initialize the Toon sensor."""
super().__init__(coordinator)
self.entity_description = description
... | the_stack_v2_python_sparse | homeassistant/components/toon/binary_sensor.py | home-assistant/core | train | 35,501 |
289bfbd8a5a3e481667a159ca5c66e3c93dfe5fe | [
"self.assertRaises(TypeError, sco.StealthCircuitObject, None)\nself.assertRaises(TypeError, sco.StealthCircuitObject, 1)\nself.assertRaises(AssertionError, sco.StealthCircuitObject, '')",
"co1_name = 'object1'\nco1 = sco.StealthCircuitObject(co1_name)\nself.assertEqual(co1.get_name(), co1_name)",
"co1_name = 'o... | <|body_start_0|>
self.assertRaises(TypeError, sco.StealthCircuitObject, None)
self.assertRaises(TypeError, sco.StealthCircuitObject, 1)
self.assertRaises(AssertionError, sco.StealthCircuitObject, '')
<|end_body_0|>
<|body_start_1|>
co1_name = 'object1'
co1 = sco.StealthCircuitOb... | TestCircuitObject | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCircuitObject:
def test_bad_init(self):
"""Tests that initializing a circuit object with a None, an integer, or an empty string as a displayname throws an error."""
<|body_0|>
def test_get_name(self):
"""Tests that get_name returns the name of the object correctl... | stack_v2_sparse_classes_75kplus_train_005188 | 3,519 | permissive | [
{
"docstring": "Tests that initializing a circuit object with a None, an integer, or an empty string as a displayname throws an error.",
"name": "test_bad_init",
"signature": "def test_bad_init(self)"
},
{
"docstring": "Tests that get_name returns the name of the object correctly.",
"name": ... | 4 | stack_v2_sparse_classes_30k_train_005021 | Implement the Python class `TestCircuitObject` described below.
Class description:
Implement the TestCircuitObject class.
Method signatures and docstrings:
- def test_bad_init(self): Tests that initializing a circuit object with a None, an integer, or an empty string as a displayname throws an error.
- def test_get_n... | Implement the Python class `TestCircuitObject` described below.
Class description:
Implement the TestCircuitObject class.
Method signatures and docstrings:
- def test_bad_init(self): Tests that initializing a circuit object with a None, an integer, or an empty string as a displayname throws an error.
- def test_get_n... | 264459a8fa1480c7b65d946f88d94af1a038fbf1 | <|skeleton|>
class TestCircuitObject:
def test_bad_init(self):
"""Tests that initializing a circuit object with a None, an integer, or an empty string as a displayname throws an error."""
<|body_0|>
def test_get_name(self):
"""Tests that get_name returns the name of the object correctl... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestCircuitObject:
def test_bad_init(self):
"""Tests that initializing a circuit object with a None, an integer, or an empty string as a displayname throws an error."""
self.assertRaises(TypeError, sco.StealthCircuitObject, None)
self.assertRaises(TypeError, sco.StealthCircuitObject, 1... | the_stack_v2_python_sparse | hetest/python/circuit_generation/stealth/stealth_circuit_object_test.py | y4n9squared/HEtest | train | 7 | |
ca2b91019a92a165f1446c65db307735f9a2bcf4 | [
"s = str(x)\nl = len(s)\nif '-' == s[0]:\n return False\nfor i in range(l // 2):\n if s[i] != s[-(i + 1)]:\n return False\nreturn True",
"s = str(x)\nif '-' == s[0]:\n return False\nreturn s == s[::-1]"
] | <|body_start_0|>
s = str(x)
l = len(s)
if '-' == s[0]:
return False
for i in range(l // 2):
if s[i] != s[-(i + 1)]:
return False
return True
<|end_body_0|>
<|body_start_1|>
s = str(x)
if '-' == s[0]:
return Fals... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isPalindrome(self, x):
""":type: x: int :rtype: bool"""
<|body_0|>
def isPalindrome2(self, x):
""":type: x: int :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
s = str(x)
l = len(s)
if '-' == s[0]:
... | stack_v2_sparse_classes_75kplus_train_005189 | 513 | no_license | [
{
"docstring": ":type: x: int :rtype: bool",
"name": "isPalindrome",
"signature": "def isPalindrome(self, x)"
},
{
"docstring": ":type: x: int :rtype: bool",
"name": "isPalindrome2",
"signature": "def isPalindrome2(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_030686 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome(self, x): :type: x: int :rtype: bool
- def isPalindrome2(self, x): :type: x: int :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome(self, x): :type: x: int :rtype: bool
- def isPalindrome2(self, x): :type: x: int :rtype: bool
<|skeleton|>
class Solution:
def isPalindrome(self, x):
... | 885a9af8a7bee3c228c7ae4e295dca810bd91d01 | <|skeleton|>
class Solution:
def isPalindrome(self, x):
""":type: x: int :rtype: bool"""
<|body_0|>
def isPalindrome2(self, x):
""":type: x: int :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def isPalindrome(self, x):
""":type: x: int :rtype: bool"""
s = str(x)
l = len(s)
if '-' == s[0]:
return False
for i in range(l // 2):
if s[i] != s[-(i + 1)]:
return False
return True
def isPalindrome2(self,... | the_stack_v2_python_sparse | Python/9.py | kevin851066/Leetcode | train | 0 | |
eac63c2e39d0a980342fd685f6b3f69e7d5c4ce2 | [
"log.debug('POST request from user %s to create a new issue' % request.user)\nproj = Project.objects.get(project_number=project_number)\nif not check_project_write_acl(proj, request.user):\n log.debug('Refusing POST request for project %s from user %s' % (project_number, request.user))\n return rc.FORBIDDEN\n... | <|body_start_0|>
log.debug('POST request from user %s to create a new issue' % request.user)
proj = Project.objects.get(project_number=project_number)
if not check_project_write_acl(proj, request.user):
log.debug('Refusing POST request for project %s from user %s' % (project_number, ... | URI: /api/issues/%project_number%/ VERBS: GET, POST Returns a list of issues associated with a project | IssueListHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IssueListHandler:
"""URI: /api/issues/%project_number%/ VERBS: GET, POST Returns a list of issues associated with a project"""
def create(self, request, project_number):
"""Create a new Issue"""
<|body_0|>
def read(self, request, project_number):
"""Return a list... | stack_v2_sparse_classes_75kplus_train_005190 | 5,440 | no_license | [
{
"docstring": "Create a new Issue",
"name": "create",
"signature": "def create(self, request, project_number)"
},
{
"docstring": "Return a list of issues associated with projects filtered by ACL",
"name": "read",
"signature": "def read(self, request, project_number)"
}
] | 2 | null | Implement the Python class `IssueListHandler` described below.
Class description:
URI: /api/issues/%project_number%/ VERBS: GET, POST Returns a list of issues associated with a project
Method signatures and docstrings:
- def create(self, request, project_number): Create a new Issue
- def read(self, request, project_n... | Implement the Python class `IssueListHandler` described below.
Class description:
URI: /api/issues/%project_number%/ VERBS: GET, POST Returns a list of issues associated with a project
Method signatures and docstrings:
- def create(self, request, project_number): Create a new Issue
- def read(self, request, project_n... | 106a96307612318fb66246486e7226069e5508ac | <|skeleton|>
class IssueListHandler:
"""URI: /api/issues/%project_number%/ VERBS: GET, POST Returns a list of issues associated with a project"""
def create(self, request, project_number):
"""Create a new Issue"""
<|body_0|>
def read(self, request, project_number):
"""Return a list... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IssueListHandler:
"""URI: /api/issues/%project_number%/ VERBS: GET, POST Returns a list of issues associated with a project"""
def create(self, request, project_number):
"""Create a new Issue"""
log.debug('POST request from user %s to create a new issue' % request.user)
proj = Pro... | the_stack_v2_python_sparse | api-example/issues/api_views.py | NhaTrang/django-project-management | train | 0 |
42f01cdb3965a605aa65d951c785f13c20ccb531 | [
"A = np.copy(A)\nself.n = A.shape[0]\nif type(labels) == type(None):\n self.labels = np.arange(self.n)\nelif len(labels) != self.n:\n raise ValueError(\"Number of labels doesn't match size of A\")\nelse:\n self.labels = labels\nfor j in range(self.n):\n if np.all(A[:, j] == 0):\n A[:, j] = 1\nsel... | <|body_start_0|>
A = np.copy(A)
self.n = A.shape[0]
if type(labels) == type(None):
self.labels = np.arange(self.n)
elif len(labels) != self.n:
raise ValueError("Number of labels doesn't match size of A")
else:
self.labels = labels
for j... | A class for representing directed graphs via their adjacency matrices. Attributes: (fill this out after completing DiGraph.__init__().) | DiGraph | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DiGraph:
"""A class for representing directed graphs via their adjacency matrices. Attributes: (fill this out after completing DiGraph.__init__().)"""
def __init__(self, A, labels=None):
"""Modify A so that there are no sinks in the corresponding graph, then calculate Ahat. Save Ahat... | stack_v2_sparse_classes_75kplus_train_005191 | 10,086 | no_license | [
{
"docstring": "Modify A so that there are no sinks in the corresponding graph, then calculate Ahat. Save Ahat and the labels as attributes. Parameters: A ((n,n) ndarray): the adjacency matrix of a directed graph. A[i,j] is the weight of the edge from node j to node i. labels (list(str)): labels for the n nodes... | 4 | stack_v2_sparse_classes_30k_train_020083 | Implement the Python class `DiGraph` described below.
Class description:
A class for representing directed graphs via their adjacency matrices. Attributes: (fill this out after completing DiGraph.__init__().)
Method signatures and docstrings:
- def __init__(self, A, labels=None): Modify A so that there are no sinks i... | Implement the Python class `DiGraph` described below.
Class description:
A class for representing directed graphs via their adjacency matrices. Attributes: (fill this out after completing DiGraph.__init__().)
Method signatures and docstrings:
- def __init__(self, A, labels=None): Modify A so that there are no sinks i... | 48b9f811181f50d6efeeaa3842c7adde1a10c3bb | <|skeleton|>
class DiGraph:
"""A class for representing directed graphs via their adjacency matrices. Attributes: (fill this out after completing DiGraph.__init__().)"""
def __init__(self, A, labels=None):
"""Modify A so that there are no sinks in the corresponding graph, then calculate Ahat. Save Ahat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DiGraph:
"""A class for representing directed graphs via their adjacency matrices. Attributes: (fill this out after completing DiGraph.__init__().)"""
def __init__(self, A, labels=None):
"""Modify A so that there are no sinks in the corresponding graph, then calculate Ahat. Save Ahat and the labe... | the_stack_v2_python_sparse | pagerank/pagerank.py | kameronlightheart14/projects | train | 0 |
8fbafaa5b4c0a2592951132ecfc7a0c664818c9e | [
"from past.builtins import basestring\nif isinstance(data, basestring):\n return str(data)\nif isinstance(data, collections.Mapping):\n return dict(map(format_utils.convert_from_unicode, data.iteritems()))\nif isinstance(data, collections.Iterable):\n return type(data)(map(format_utils.convert_from_unicode... | <|body_start_0|>
from past.builtins import basestring
if isinstance(data, basestring):
return str(data)
if isinstance(data, collections.Mapping):
return dict(map(format_utils.convert_from_unicode, data.iteritems()))
if isinstance(data, collections.Iterable):
... | Useful functions to format strings | format_utils | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class format_utils:
"""Useful functions to format strings"""
def convert_from_unicode(data):
"""Converts from unicode to string. Parameters ---------- data : str or collection Input object in unicode"""
<|body_0|>
def nice(reso):
"""Function to nicely format resolution... | stack_v2_sparse_classes_75kplus_train_005192 | 7,205 | permissive | [
{
"docstring": "Converts from unicode to string. Parameters ---------- data : str or collection Input object in unicode",
"name": "convert_from_unicode",
"signature": "def convert_from_unicode(data)"
},
{
"docstring": "Function to nicely format resolution in Mb or Kb",
"name": "nice",
"s... | 2 | null | Implement the Python class `format_utils` described below.
Class description:
Useful functions to format strings
Method signatures and docstrings:
- def convert_from_unicode(data): Converts from unicode to string. Parameters ---------- data : str or collection Input object in unicode
- def nice(reso): Function to nic... | Implement the Python class `format_utils` described below.
Class description:
Useful functions to format strings
Method signatures and docstrings:
- def convert_from_unicode(data): Converts from unicode to string. Parameters ---------- data : str or collection Input object in unicode
- def nice(reso): Function to nic... | 50c7115c0c1a6af48dc34f275e469d1b9eb02999 | <|skeleton|>
class format_utils:
"""Useful functions to format strings"""
def convert_from_unicode(data):
"""Converts from unicode to string. Parameters ---------- data : str or collection Input object in unicode"""
<|body_0|>
def nice(reso):
"""Function to nicely format resolution... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class format_utils:
"""Useful functions to format strings"""
def convert_from_unicode(data):
"""Converts from unicode to string. Parameters ---------- data : str or collection Input object in unicode"""
from past.builtins import basestring
if isinstance(data, basestring):
re... | the_stack_v2_python_sparse | tool/common.py | Multiscale-Genomics/mg-process-fastq | train | 2 |
01184dd87055227e72a38bc35abb773d764ebf7f | [
"self.name = name.upper()\nself.log = logging.getLogger('hiicart.gateway.' + self.name)\nself.settings = default_settings or {}\nself.settings.update(cart.hiicart_settings)\nif self.name in self.settings:\n self.settings.update(cart.hiicart_settings[self.name])\nself._settings_base = self.settings.copy()\nself.c... | <|body_start_0|>
self.name = name.upper()
self.log = logging.getLogger('hiicart.gateway.' + self.name)
self.settings = default_settings or {}
self.settings.update(cart.hiicart_settings)
if self.name in self.settings:
self.settings.update(cart.hiicart_settings[self.nam... | Shared base class between IPNs and Gateways Created because they have significant overlapping functionality. | _SharedBase | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _SharedBase:
"""Shared base class between IPNs and Gateways Created because they have significant overlapping functionality."""
def __init__(self, name, cart, default_settings=None):
"""Initalize logger and settings. Duplicate settings are overwritten according to priority according ... | stack_v2_sparse_classes_75kplus_train_005193 | 7,634 | permissive | [
{
"docstring": "Initalize logger and settings. Duplicate settings are overwritten according to priority according to the following ascending priority: default_settings -> global -> gateway defined in HIICART_SETTINGS",
"name": "__init__",
"signature": "def __init__(self, name, cart, default_settings=Non... | 6 | stack_v2_sparse_classes_30k_train_032874 | Implement the Python class `_SharedBase` described below.
Class description:
Shared base class between IPNs and Gateways Created because they have significant overlapping functionality.
Method signatures and docstrings:
- def __init__(self, name, cart, default_settings=None): Initalize logger and settings. Duplicate ... | Implement the Python class `_SharedBase` described below.
Class description:
Shared base class between IPNs and Gateways Created because they have significant overlapping functionality.
Method signatures and docstrings:
- def __init__(self, name, cart, default_settings=None): Initalize logger and settings. Duplicate ... | 424ee64b5f298c377df35a59cc8b5c4b05c885f0 | <|skeleton|>
class _SharedBase:
"""Shared base class between IPNs and Gateways Created because they have significant overlapping functionality."""
def __init__(self, name, cart, default_settings=None):
"""Initalize logger and settings. Duplicate settings are overwritten according to priority according ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _SharedBase:
"""Shared base class between IPNs and Gateways Created because they have significant overlapping functionality."""
def __init__(self, name, cart, default_settings=None):
"""Initalize logger and settings. Duplicate settings are overwritten according to priority according to the follow... | the_stack_v2_python_sparse | hiicart/gateway/base.py | hiidef/hiicart | train | 18 |
af0fae2561b51608b518588cd1fe2dc9bf05786a | [
"A_words = {}\nB_words = {}\nfor word_a in A.split():\n A_words[word_a] = A_words.get(word_a, 0) + 1\nfor word_b in B.split():\n B_words[word_b] = B_words.get(word_b, 0) + 1\nuncommon = []\nfor word in A_words.keys():\n if A_words.get(word, 0) == 1 and B_words.get(word, 0) == 0:\n uncommon.append(wo... | <|body_start_0|>
A_words = {}
B_words = {}
for word_a in A.split():
A_words[word_a] = A_words.get(word_a, 0) + 1
for word_b in B.split():
B_words[word_b] = B_words.get(word_b, 0) + 1
uncommon = []
for word in A_words.keys():
if A_words.... | Strat: Use Dict Stats: O(n + m) time, O(n + m) space | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""Strat: Use Dict Stats: O(n + m) time, O(n + m) space"""
def uncommonFromSentences(self, A, B):
""":type A: str :type B: str :rtype: List[str]"""
<|body_0|>
def uncommonFromSentences(self, A, B):
""":type A: str :type B: str :rtype: List[str]"""
... | stack_v2_sparse_classes_75kplus_train_005194 | 1,879 | no_license | [
{
"docstring": ":type A: str :type B: str :rtype: List[str]",
"name": "uncommonFromSentences",
"signature": "def uncommonFromSentences(self, A, B)"
},
{
"docstring": ":type A: str :type B: str :rtype: List[str]",
"name": "uncommonFromSentences",
"signature": "def uncommonFromSentences(se... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Strat: Use Dict Stats: O(n + m) time, O(n + m) space
Method signatures and docstrings:
- def uncommonFromSentences(self, A, B): :type A: str :type B: str :rtype: List[str]
- def uncommonFromSentences(self, A, B): :type A: str :type B: str :rtyp... | Implement the Python class `Solution` described below.
Class description:
Strat: Use Dict Stats: O(n + m) time, O(n + m) space
Method signatures and docstrings:
- def uncommonFromSentences(self, A, B): :type A: str :type B: str :rtype: List[str]
- def uncommonFromSentences(self, A, B): :type A: str :type B: str :rtyp... | 844f502da4d6fb9cd69cf0a1ef71da3385a4d2b4 | <|skeleton|>
class Solution:
"""Strat: Use Dict Stats: O(n + m) time, O(n + m) space"""
def uncommonFromSentences(self, A, B):
""":type A: str :type B: str :rtype: List[str]"""
<|body_0|>
def uncommonFromSentences(self, A, B):
""":type A: str :type B: str :rtype: List[str]"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
"""Strat: Use Dict Stats: O(n + m) time, O(n + m) space"""
def uncommonFromSentences(self, A, B):
""":type A: str :type B: str :rtype: List[str]"""
A_words = {}
B_words = {}
for word_a in A.split():
A_words[word_a] = A_words.get(word_a, 0) + 1
... | the_stack_v2_python_sparse | 884-uncommon_words_from_two_sentences.py | stevestar888/leetcode-problems | train | 2 |
7c083965d9c593cc5611e07778410c8f0e3bf067 | [
"super().__init__(listRef.localControlRef)\nfor varOwner, varName in varList:\n value = varOwner.__dict__[varName]\n self.dataList.append((varOwner, varName, value))\nlistRef.addUndoObj(self, notRedo)",
"if redoRef != None:\n ParamUndo(redoRef, [item[:2] for item in self.dataList], False)\nfor varOwner, ... | <|body_start_0|>
super().__init__(listRef.localControlRef)
for varOwner, varName in varList:
value = varOwner.__dict__[varName]
self.dataList.append((varOwner, varName, value))
listRef.addUndoObj(self, notRedo)
<|end_body_0|>
<|body_start_1|>
if redoRef != None:
... | Info for undo/redo of any variable parameter. | ParamUndo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParamUndo:
"""Info for undo/redo of any variable parameter."""
def __init__(self, listRef, varList, notRedo=True):
"""Create the data undo class and add it to the undoStore. Arguments: listRef -- a ref to the undo/redo list this gets added to varList - list of tuples, variable's owne... | stack_v2_sparse_classes_75kplus_train_005195 | 17,816 | no_license | [
{
"docstring": "Create the data undo class and add it to the undoStore. Arguments: listRef -- a ref to the undo/redo list this gets added to varList - list of tuples, variable's owner and variable's name notRedo -- if True, clear redo list (after changes)",
"name": "__init__",
"signature": "def __init__... | 2 | stack_v2_sparse_classes_30k_train_024034 | Implement the Python class `ParamUndo` described below.
Class description:
Info for undo/redo of any variable parameter.
Method signatures and docstrings:
- def __init__(self, listRef, varList, notRedo=True): Create the data undo class and add it to the undoStore. Arguments: listRef -- a ref to the undo/redo list thi... | Implement the Python class `ParamUndo` described below.
Class description:
Info for undo/redo of any variable parameter.
Method signatures and docstrings:
- def __init__(self, listRef, varList, notRedo=True): Create the data undo class and add it to the undoStore. Arguments: listRef -- a ref to the undo/redo list thi... | c9429496e8ed15116746a23f3a90f262cf54f755 | <|skeleton|>
class ParamUndo:
"""Info for undo/redo of any variable parameter."""
def __init__(self, listRef, varList, notRedo=True):
"""Create the data undo class and add it to the undoStore. Arguments: listRef -- a ref to the undo/redo list this gets added to varList - list of tuples, variable's owne... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ParamUndo:
"""Info for undo/redo of any variable parameter."""
def __init__(self, listRef, varList, notRedo=True):
"""Create the data undo class and add it to the undoStore. Arguments: listRef -- a ref to the undo/redo list this gets added to varList - list of tuples, variable's owner and variabl... | the_stack_v2_python_sparse | source/undo.py | doug-101/TreeLine | train | 121 |
948ff0c7f12e269d2431db353c5ac4b3fd7ce052 | [
"result = await _booru(ctx.bot.session, BASE_URLS['safebooru']['api'], f'maid {tags}')\nif isinstance(result, str):\n await ctx.send(result)\nelse:\n embed = _process_post(result, BASE_URLS['safebooru']['post'])\n await ctx.send(embed=embed)",
"result = await _booru(ctx.bot.session, BASE_URLS['safebooru'... | <|body_start_0|>
result = await _booru(ctx.bot.session, BASE_URLS['safebooru']['api'], f'maid {tags}')
if isinstance(result, str):
await ctx.send(result)
else:
embed = _process_post(result, BASE_URLS['safebooru']['post'])
await ctx.send(embed=embed)
<|end_body... | Imageboard lookup commands. | Booru | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Booru:
"""Imageboard lookup commands."""
async def maid(self, ctx, *, tags=''):
"""Find a random maid. Optional tags."""
<|body_0|>
async def animeme(self, ctx, *, tags=''):
"""Find a random anime meme. Optional tags."""
<|body_1|>
async def colonles... | stack_v2_sparse_classes_75kplus_train_005196 | 4,323 | permissive | [
{
"docstring": "Find a random maid. Optional tags.",
"name": "maid",
"signature": "async def maid(self, ctx, *, tags='')"
},
{
"docstring": "Find a random anime meme. Optional tags.",
"name": "animeme",
"signature": "async def animeme(self, ctx, *, tags='')"
},
{
"docstring": ":<... | 4 | stack_v2_sparse_classes_30k_train_047535 | Implement the Python class `Booru` described below.
Class description:
Imageboard lookup commands.
Method signatures and docstrings:
- async def maid(self, ctx, *, tags=''): Find a random maid. Optional tags.
- async def animeme(self, ctx, *, tags=''): Find a random anime meme. Optional tags.
- async def colonlesstha... | Implement the Python class `Booru` described below.
Class description:
Imageboard lookup commands.
Method signatures and docstrings:
- async def maid(self, ctx, *, tags=''): Find a random maid. Optional tags.
- async def animeme(self, ctx, *, tags=''): Find a random anime meme. Optional tags.
- async def colonlesstha... | 9bf3f2125939b66bd1894e509c1b1fa1ab413a6a | <|skeleton|>
class Booru:
"""Imageboard lookup commands."""
async def maid(self, ctx, *, tags=''):
"""Find a random maid. Optional tags."""
<|body_0|>
async def animeme(self, ctx, *, tags=''):
"""Find a random anime meme. Optional tags."""
<|body_1|>
async def colonles... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Booru:
"""Imageboard lookup commands."""
async def maid(self, ctx, *, tags=''):
"""Find a random maid. Optional tags."""
result = await _booru(ctx.bot.session, BASE_URLS['safebooru']['api'], f'maid {tags}')
if isinstance(result, str):
await ctx.send(result)
els... | the_stack_v2_python_sparse | cogs/imgboards/booru.py | DasWolke/kitsuchan-2 | train | 1 |
e19d06468961ddd874ce80b7f184289568b3c5cf | [
"Iso.__init__(self, label, number_stock_racks, rack_layout, iso_type=ISO_TYPES.LAB, **kw)\nself.library_plates = []\nself.requested_library_plates = requested_library_plates",
"if len(self.library_plates) > 0:\n result = self.library_plates\nelse:\n result = self.iso_aliquot_plates\nreturn result"
] | <|body_start_0|>
Iso.__init__(self, label, number_stock_racks, rack_layout, iso_type=ISO_TYPES.LAB, **kw)
self.library_plates = []
self.requested_library_plates = requested_library_plates
<|end_body_0|>
<|body_start_1|>
if len(self.library_plates) > 0:
result = self.library_... | This special kind of :class:`Iso` generates plates for experiments in the lab. The :attr:`rack_layout` is a :class:IsoPlateLayout`, the :attr:`molecule_design_pool_set` is optional an only contains pools specific to this ISOs (floating position pools). | LabIso | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LabIso:
"""This special kind of :class:`Iso` generates plates for experiments in the lab. The :attr:`rack_layout` is a :class:IsoPlateLayout`, the :attr:`molecule_design_pool_set` is optional an only contains pools specific to this ISOs (floating position pools)."""
def __init__(self, label,... | stack_v2_sparse_classes_75kplus_train_005197 | 31,121 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, label, number_stock_racks, rack_layout, requested_library_plates=None, **kw)"
},
{
"docstring": "Returns either the ISO aliquot or the library plates assigned to this ISO (depending on what sort of plates is assoc... | 2 | null | Implement the Python class `LabIso` described below.
Class description:
This special kind of :class:`Iso` generates plates for experiments in the lab. The :attr:`rack_layout` is a :class:IsoPlateLayout`, the :attr:`molecule_design_pool_set` is optional an only contains pools specific to this ISOs (floating position po... | Implement the Python class `LabIso` described below.
Class description:
This special kind of :class:`Iso` generates plates for experiments in the lab. The :attr:`rack_layout` is a :class:IsoPlateLayout`, the :attr:`molecule_design_pool_set` is optional an only contains pools specific to this ISOs (floating position po... | d2dc7a478ee5d24ccf3cc680888e712d482321d0 | <|skeleton|>
class LabIso:
"""This special kind of :class:`Iso` generates plates for experiments in the lab. The :attr:`rack_layout` is a :class:IsoPlateLayout`, the :attr:`molecule_design_pool_set` is optional an only contains pools specific to this ISOs (floating position pools)."""
def __init__(self, label,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LabIso:
"""This special kind of :class:`Iso` generates plates for experiments in the lab. The :attr:`rack_layout` is a :class:IsoPlateLayout`, the :attr:`molecule_design_pool_set` is optional an only contains pools specific to this ISOs (floating position pools)."""
def __init__(self, label, number_stock... | the_stack_v2_python_sparse | thelma/entities/iso.py | papagr/TheLMA | train | 1 |
94880096830b0a08809de5820f30b32d920b04f0 | [
"self.size = size\nself.dq = deque([])\nself.acum = 0",
"self.dq.append(val)\nself.acum += val\nif len(self.dq) > self.size:\n left = self.dq.popleft()\n self.suma -= left\nreturn float(self.suma) / len(self.dq)"
] | <|body_start_0|>
self.size = size
self.dq = deque([])
self.acum = 0
<|end_body_0|>
<|body_start_1|>
self.dq.append(val)
self.acum += val
if len(self.dq) > self.size:
left = self.dq.popleft()
self.suma -= left
return float(self.suma) / len(... | MovingAverage | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
<|body_0|>
def next(self, val):
""":type val: int :rtype: float"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.size = size
self.dq = de... | stack_v2_sparse_classes_75kplus_train_005198 | 1,478 | permissive | [
{
"docstring": "Initialize your data structure here. :type size: int",
"name": "__init__",
"signature": "def __init__(self, size)"
},
{
"docstring": ":type val: int :rtype: float",
"name": "next",
"signature": "def next(self, val)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001002 | 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:
... | ffe317f9a984319fbb3c1811e2a438306fc4eee9 | <|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_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
self.size = size
self.dq = deque([])
self.acum = 0
def next(self, val):
""":type val: int :rtype: float"""
self.dq.append(val)
self.acum += val
... | the_stack_v2_python_sparse | LeetCode/01_Easy/lc_346.py | zubie7a/Algorithms | train | 10 | |
c0caddc9ff1afdf2ecb131ec7e5b87a105366235 | [
"assert isinstance(values, list) and len(values) > 0, 'Please provide a list of possible stretching factors to choose from (randomly)'\nself.values = values\nself.debug_time = debug_time\nself.name = name",
"if value is None:\n value = np.random.choice(self.values)\npreprocessed_clip = librosa.effects.time_str... | <|body_start_0|>
assert isinstance(values, list) and len(values) > 0, 'Please provide a list of possible stretching factors to choose from (randomly)'
self.values = values
self.debug_time = debug_time
self.name = name
<|end_body_0|>
<|body_start_1|>
if value is None:
... | TimeStretch | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TimeStretch:
def __init__(self, values, debug_time=False, name='TimeStretch'):
"""Implements the TimeStretch transformation Args: - values: iterable dataset that provides the samples OPTIONAL: - debug_time: boolean to set debug mode"""
<|body_0|>
def __call__(self, clip, val... | stack_v2_sparse_classes_75kplus_train_005199 | 7,597 | no_license | [
{
"docstring": "Implements the TimeStretch transformation Args: - values: iterable dataset that provides the samples OPTIONAL: - debug_time: boolean to set debug mode",
"name": "__init__",
"signature": "def __init__(self, values, debug_time=False, name='TimeStretch')"
},
{
"docstring": "Implemen... | 2 | null | Implement the Python class `TimeStretch` described below.
Class description:
Implement the TimeStretch class.
Method signatures and docstrings:
- def __init__(self, values, debug_time=False, name='TimeStretch'): Implements the TimeStretch transformation Args: - values: iterable dataset that provides the samples OPTIO... | Implement the Python class `TimeStretch` described below.
Class description:
Implement the TimeStretch class.
Method signatures and docstrings:
- def __init__(self, values, debug_time=False, name='TimeStretch'): Implements the TimeStretch transformation Args: - values: iterable dataset that provides the samples OPTIO... | efaf7c637e8387116d0eea37a0a173bb65bbccc9 | <|skeleton|>
class TimeStretch:
def __init__(self, values, debug_time=False, name='TimeStretch'):
"""Implements the TimeStretch transformation Args: - values: iterable dataset that provides the samples OPTIONAL: - debug_time: boolean to set debug mode"""
<|body_0|>
def __call__(self, clip, val... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TimeStretch:
def __init__(self, values, debug_time=False, name='TimeStretch'):
"""Implements the TimeStretch transformation Args: - values: iterable dataset that provides the samples OPTIONAL: - debug_time: boolean to set debug mode"""
assert isinstance(values, list) and len(values) > 0, 'Plea... | the_stack_v2_python_sparse | core/data_augmentation/audio_transformations.py | EmanueleMusumeci/UrbanSound8K-CNN-sound-classification | train | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.