blob_id
stringlengths
40
40
bodies
listlengths
2
6
bodies_text
stringlengths
196
6.73k
class_docstring
stringlengths
0
700
class_name
stringlengths
1
86
detected_licenses
listlengths
0
45
format_version
stringclasses
1 value
full_text
stringlengths
438
7.52k
id
stringlengths
40
40
length_bytes
int64
506
50k
license_type
stringclasses
2 values
methods
listlengths
2
6
n_methods
int64
2
6
original_id
stringlengths
38
40
prompt
stringlengths
153
4.25k
prompted_full_text
stringlengths
645
10.7k
revision_id
stringlengths
40
40
skeleton
stringlengths
162
4.34k
snapshot_name
stringclasses
1 value
snapshot_source_dir
stringclasses
1 value
solution
stringlengths
302
7.33k
source
stringclasses
1 value
source_path
stringlengths
4
177
source_repo
stringlengths
6
110
split
stringclasses
1 value
star_events_count
int64
0
209k
168aac522698d2205063d34b6284e590943bff4b
[ "self.DTYPE = 'float32'\nself.n_negative_samples_batch = config['n_negative_samples_batch']\nself.n_tokens_vocab = config['n_tokens_vocab']\nself.projection_dim = config['dim']\nwith tf.variable_scope('softmax'), tf.device('/cpu:0'):\n softmax_init = tf.random_normal_initializer(0.0, 1.0 / np.sqrt(self.projectio...
<|body_start_0|> self.DTYPE = 'float32' self.n_negative_samples_batch = config['n_negative_samples_batch'] self.n_tokens_vocab = config['n_tokens_vocab'] self.projection_dim = config['dim'] with tf.variable_scope('softmax'), tf.device('/cpu:0'): softmax_init = tf.rand...
a layer class: sampled softmax loss
BiSampledSoftmaxLoss
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BiSampledSoftmaxLoss: """a layer class: sampled softmax loss""" def __init__(self, config=None): """init function""" <|body_0|> def ops(self, input_tensors, next_ids): """an op to calculate losses loss for each direction of the LSTM Args: input_tensors: outputs o...
stack_v2_sparse_classes_36k_train_003300
3,677
no_license
[ { "docstring": "init function", "name": "__init__", "signature": "def __init__(self, config=None)" }, { "docstring": "an op to calculate losses loss for each direction of the LSTM Args: input_tensors: outputs of elmo embedding next_ids = [self.next_token_id, self.next_token_id_reverse] Returns: ...
2
stack_v2_sparse_classes_30k_train_017243
Implement the Python class `BiSampledSoftmaxLoss` described below. Class description: a layer class: sampled softmax loss Method signatures and docstrings: - def __init__(self, config=None): init function - def ops(self, input_tensors, next_ids): an op to calculate losses loss for each direction of the LSTM Args: inp...
Implement the Python class `BiSampledSoftmaxLoss` described below. Class description: a layer class: sampled softmax loss Method signatures and docstrings: - def __init__(self, config=None): init function - def ops(self, input_tensors, next_ids): an op to calculate losses loss for each direction of the LSTM Args: inp...
598b5b08f9e365beca032fcb2d75c0723b77d3cb
<|skeleton|> class BiSampledSoftmaxLoss: """a layer class: sampled softmax loss""" def __init__(self, config=None): """init function""" <|body_0|> def ops(self, input_tensors, next_ids): """an op to calculate losses loss for each direction of the LSTM Args: input_tensors: outputs o...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BiSampledSoftmaxLoss: """a layer class: sampled softmax loss""" def __init__(self, config=None): """init function""" self.DTYPE = 'float32' self.n_negative_samples_batch = config['n_negative_samples_batch'] self.n_tokens_vocab = config['n_tokens_vocab'] self.projec...
the_stack_v2_python_sparse
tfnlp/layers/loss_layer.py
RipperLom/AssembleNet
train
1
ab6eadf4d4ed56277cfad8d0a263621568213259
[ "size = (size[1], size[0])\nassert isinstance(size, int) or (isinstance(size, collections.Iterable) and len(size) == 2)\nself.size = size\nself.interA = interA\nself.interB = interB", "if A.shape[2] == 1:\n return (cv2.resize(A, self.size, interpolation=self.interA)[:, :, np.newaxis], cv2.resize(B, self.size, ...
<|body_start_0|> size = (size[1], size[0]) assert isinstance(size, int) or (isinstance(size, collections.Iterable) and len(size) == 2) self.size = size self.interA = interA self.interB = interB <|end_body_0|> <|body_start_1|> if A.shape[2] == 1: return (cv2.r...
ResizeAB
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ResizeAB: def __init__(self, size, interA=cv2.INTER_NEAREST, interB=cv2.INTER_NEAREST): """Resize two images to size. Args: size (tuple): (height, weight) interA (cv2.INTER...): Aに適用する補完手法. interB (cv2.INTER...): Aに適用する補完手法. 入力側には cv2.INTER_NEAREST がかけられる.Defaults to cv2.INTER_CUBIC. Ret...
stack_v2_sparse_classes_36k_train_003301
8,128
no_license
[ { "docstring": "Resize two images to size. Args: size (tuple): (height, weight) interA (cv2.INTER...): Aに適用する補完手法. interB (cv2.INTER...): Aに適用する補完手法. 入力側には cv2.INTER_NEAREST がかけられる.Defaults to cv2.INTER_CUBIC. Returns: A, B", "name": "__init__", "signature": "def __init__(self, size, interA=cv2.INTER_NE...
2
stack_v2_sparse_classes_30k_train_003624
Implement the Python class `ResizeAB` described below. Class description: Implement the ResizeAB class. Method signatures and docstrings: - def __init__(self, size, interA=cv2.INTER_NEAREST, interB=cv2.INTER_NEAREST): Resize two images to size. Args: size (tuple): (height, weight) interA (cv2.INTER...): Aに適用する補完手法. i...
Implement the Python class `ResizeAB` described below. Class description: Implement the ResizeAB class. Method signatures and docstrings: - def __init__(self, size, interA=cv2.INTER_NEAREST, interB=cv2.INTER_NEAREST): Resize two images to size. Args: size (tuple): (height, weight) interA (cv2.INTER...): Aに適用する補完手法. i...
3e4cfd28bb9ef0fd3bb9ed64c435d183236a0b72
<|skeleton|> class ResizeAB: def __init__(self, size, interA=cv2.INTER_NEAREST, interB=cv2.INTER_NEAREST): """Resize two images to size. Args: size (tuple): (height, weight) interA (cv2.INTER...): Aに適用する補完手法. interB (cv2.INTER...): Aに適用する補完手法. 入力側には cv2.INTER_NEAREST がかけられる.Defaults to cv2.INTER_CUBIC. Ret...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ResizeAB: def __init__(self, size, interA=cv2.INTER_NEAREST, interB=cv2.INTER_NEAREST): """Resize two images to size. Args: size (tuple): (height, weight) interA (cv2.INTER...): Aに適用する補完手法. interB (cv2.INTER...): Aに適用する補完手法. 入力側には cv2.INTER_NEAREST がかけられる.Defaults to cv2.INTER_CUBIC. Returns: A, B""" ...
the_stack_v2_python_sparse
data/opencv_transforms.py
haru-256/pix2pix.pytorch
train
1
798e39fc0e3fa23d70b9e33b299c29724744ba72
[ "license_pool = self.license_pool\nif not license_pool:\n return None\nif license_pool.work:\n return license_pool.work\nif license_pool.presentation_edition and license_pool.presentation_edition.work:\n return license_pool.presentation_edition.work\nreturn None", "if self.patron:\n return self.patron...
<|body_start_0|> license_pool = self.license_pool if not license_pool: return None if license_pool.work: return license_pool.work if license_pool.presentation_edition and license_pool.presentation_edition.work: return license_pool.presentation_edition....
LoanAndHoldMixin
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LoanAndHoldMixin: def work(self): """Try to find the corresponding work for this Loan/Hold.""" <|body_0|> def library(self): """Try to find the corresponding library for this Loan/Hold.""" <|body_1|> <|end_skeleton|> <|body_start_0|> license_pool = ...
stack_v2_sparse_classes_36k_train_003302
28,382
permissive
[ { "docstring": "Try to find the corresponding work for this Loan/Hold.", "name": "work", "signature": "def work(self)" }, { "docstring": "Try to find the corresponding library for this Loan/Hold.", "name": "library", "signature": "def library(self)" } ]
2
null
Implement the Python class `LoanAndHoldMixin` described below. Class description: Implement the LoanAndHoldMixin class. Method signatures and docstrings: - def work(self): Try to find the corresponding work for this Loan/Hold. - def library(self): Try to find the corresponding library for this Loan/Hold.
Implement the Python class `LoanAndHoldMixin` described below. Class description: Implement the LoanAndHoldMixin class. Method signatures and docstrings: - def work(self): Try to find the corresponding work for this Loan/Hold. - def library(self): Try to find the corresponding library for this Loan/Hold. <|skeleton|...
662cc7e0721d0153857c8c17a37e2a6df86f8ce6
<|skeleton|> class LoanAndHoldMixin: def work(self): """Try to find the corresponding work for this Loan/Hold.""" <|body_0|> def library(self): """Try to find the corresponding library for this Loan/Hold.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LoanAndHoldMixin: def work(self): """Try to find the corresponding work for this Loan/Hold.""" license_pool = self.license_pool if not license_pool: return None if license_pool.work: return license_pool.work if license_pool.presentation_edition a...
the_stack_v2_python_sparse
core/model/patron.py
NYPL-Simplified/circulation
train
20
1f10cbfee33fcf8038a7802820604761e2cb9b2c
[ "if not self.inherited:\n self.inherited = added\n return\nself.inherited.min_version = min(self.inherited.min_version, added.min_version, key=parse_semver)\nfor workload, added_version in added.min_version_per_workload.items():\n v = self.inherited.min_version_per_workload.get(workload, added_version)\n ...
<|body_start_0|> if not self.inherited: self.inherited = added return self.inherited.min_version = min(self.inherited.min_version, added.min_version, key=parse_semver) for workload, added_version in added.min_version_per_workload.items(): v = self.inherited.mi...
Stats is a part of VersionData. It provides basic statistics on the OCM organization current cluster versions. Currently only the minimum version, globally in the org and per workload, is being stored. This class also has a `inherited` field which will contain at runtime a computation of the same statistics for `inheri...
Stats
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Stats: """Stats is a part of VersionData. It provides basic statistics on the OCM organization current cluster versions. Currently only the minimum version, globally in the org and per workload, is being stored. This class also has a `inherited` field which will contain at runtime a computation o...
stack_v2_sparse_classes_36k_train_003303
7,126
permissive
[ { "docstring": "adds the provided stats to our inherited data If we already have inherited data, we will merge the stats data: compute new minimums and add missing data", "name": "inherit", "signature": "def inherit(self, added: 'Stats') -> None" }, { "docstring": "Returns True only if version i...
2
null
Implement the Python class `Stats` described below. Class description: Stats is a part of VersionData. It provides basic statistics on the OCM organization current cluster versions. Currently only the minimum version, globally in the org and per workload, is being stored. This class also has a `inherited` field which ...
Implement the Python class `Stats` described below. Class description: Stats is a part of VersionData. It provides basic statistics on the OCM organization current cluster versions. Currently only the minimum version, globally in the org and per workload, is being stored. This class also has a `inherited` field which ...
91734756b84d646ac1e4b5c4d8de2cc812ea6e46
<|skeleton|> class Stats: """Stats is a part of VersionData. It provides basic statistics on the OCM organization current cluster versions. Currently only the minimum version, globally in the org and per workload, is being stored. This class also has a `inherited` field which will contain at runtime a computation o...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Stats: """Stats is a part of VersionData. It provides basic statistics on the OCM organization current cluster versions. Currently only the minimum version, globally in the org and per workload, is being stored. This class also has a `inherited` field which will contain at runtime a computation of the same st...
the_stack_v2_python_sparse
reconcile/aus/cluster_version_data.py
app-sre/qontract-reconcile
train
33
8bf0b83201a493179a273db5372f82e287190faa
[ "if not head:\n return True\nself.h = head\n\ndef travel(tail):\n if tail.next:\n t = travel(tail.next)\n self.h = self.h.next\n return t and self.h.val == tail.val\n else:\n return self.h.val == tail.val\nreturn travel(head)", "if not head:\n return True\nr = []\nt = head\...
<|body_start_0|> if not head: return True self.h = head def travel(tail): if tail.next: t = travel(tail.next) self.h = self.h.next return t and self.h.val == tail.val else: return self.h.val == t...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def isPalindrome1(self, head): """:type head: ListNode :rtype: bool""" <|body_0|> def isPalindrome(self, head): """:type head: ListNode :rtype: bool""" <|body_1|> <|end_skeleton|> <|body_start_0|> if not head: return True ...
stack_v2_sparse_classes_36k_train_003304
1,213
no_license
[ { "docstring": ":type head: ListNode :rtype: bool", "name": "isPalindrome1", "signature": "def isPalindrome1(self, head)" }, { "docstring": ":type head: ListNode :rtype: bool", "name": "isPalindrome", "signature": "def isPalindrome(self, head)" } ]
2
stack_v2_sparse_classes_30k_val_001199
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isPalindrome1(self, head): :type head: ListNode :rtype: bool - def isPalindrome(self, head): :type head: ListNode :rtype: bool
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isPalindrome1(self, head): :type head: ListNode :rtype: bool - def isPalindrome(self, head): :type head: ListNode :rtype: bool <|skeleton|> class Solution: def isPalind...
e5b018493bbd12edcdcd0434f35d9c358106d391
<|skeleton|> class Solution: def isPalindrome1(self, head): """:type head: ListNode :rtype: bool""" <|body_0|> def isPalindrome(self, head): """:type head: ListNode :rtype: bool""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def isPalindrome1(self, head): """:type head: ListNode :rtype: bool""" if not head: return True self.h = head def travel(tail): if tail.next: t = travel(tail.next) self.h = self.h.next return t a...
the_stack_v2_python_sparse
py/leetcode/234.py
wfeng1991/learnpy
train
0
8c9f904e160cccc19ef719a4ee421f0c1221e6f8
[ "if self.runner.output is not None:\n self.runner.output.Set(self.runner.output.Schema.DESCRIPTION('GetProcessesBinariesRekall binaries (regex: %s) ' % self.args.filename_regex or 'None'))\nself.CallFlow('ArtifactCollectorFlow', artifact_list=['FullVADBinaryList'], store_results_in_aff4=False, next_state='FetchB...
<|body_start_0|> if self.runner.output is not None: self.runner.output.Set(self.runner.output.Schema.DESCRIPTION('GetProcessesBinariesRekall binaries (regex: %s) ' % self.args.filename_regex or 'None')) self.CallFlow('ArtifactCollectorFlow', artifact_list=['FullVADBinaryList'], store_results...
Get list of all running binaries from Rekall, (optionally) fetch them. This flow executes the "vad" Rekall plugin to get the list of all currently running binaries (including dynamic libraries). Then if fetch_binaries option is set to True, it fetches all the binaries it has found. There is a caveat regarding using the...
ListVADBinaries
[ "Apache-2.0", "DOC" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ListVADBinaries: """Get list of all running binaries from Rekall, (optionally) fetch them. This flow executes the "vad" Rekall plugin to get the list of all currently running binaries (including dynamic libraries). Then if fetch_binaries option is set to True, it fetches all the binaries it has f...
stack_v2_sparse_classes_36k_train_003305
34,719
permissive
[ { "docstring": "Request VAD data.", "name": "Start", "signature": "def Start(self)" }, { "docstring": "Parses the Rekall response and initiates FileFinder flows.", "name": "FetchBinaries", "signature": "def FetchBinaries(self, responses)" }, { "docstring": "Handle success/failure...
3
null
Implement the Python class `ListVADBinaries` described below. Class description: Get list of all running binaries from Rekall, (optionally) fetch them. This flow executes the "vad" Rekall plugin to get the list of all currently running binaries (including dynamic libraries). Then if fetch_binaries option is set to Tru...
Implement the Python class `ListVADBinaries` described below. Class description: Get list of all running binaries from Rekall, (optionally) fetch them. This flow executes the "vad" Rekall plugin to get the list of all currently running binaries (including dynamic libraries). Then if fetch_binaries option is set to Tru...
ba1648b97a76f844ffb8e1891cc9e2680f9b1c6e
<|skeleton|> class ListVADBinaries: """Get list of all running binaries from Rekall, (optionally) fetch them. This flow executes the "vad" Rekall plugin to get the list of all currently running binaries (including dynamic libraries). Then if fetch_binaries option is set to True, it fetches all the binaries it has f...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ListVADBinaries: """Get list of all running binaries from Rekall, (optionally) fetch them. This flow executes the "vad" Rekall plugin to get the list of all currently running binaries (including dynamic libraries). Then if fetch_binaries option is set to True, it fetches all the binaries it has found. There i...
the_stack_v2_python_sparse
lib/flows/general/memory.py
defaultnamehere/grr
train
3
2a3f07f2dfcd3104843fff89cc72443df8c4f22f
[ "if phase_name == 'ECalDigi':\n return 0\nelif phase_name == 'HCalDigi':\n return 1\nelif phase_name == 'MuonAndHCalOtherDigi':\n return 2\nelif phase_name == 'ElectroMagEnergy':\n return 3\nelif phase_name == 'HadronicEnergy':\n return 4\nelif phase_name == 'PhotonTraining':\n return 5\nelse:\n ...
<|body_start_0|> if phase_name == 'ECalDigi': return 0 elif phase_name == 'HCalDigi': return 1 elif phase_name == 'MuonAndHCalOtherDigi': return 2 elif phase_name == 'ElectroMagEnergy': return 3 elif phase_name == 'HadronicEnergy': ...
Represents the different phases a calibration can be in. Since Python 2 does not have enums, this is hardcoded for the moment. Should this solution not be sufficient any more, one can make a better enum implementation by hand or install a backport of the python3 implementation from PyPi.
CalibrationPhase
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CalibrationPhase: """Represents the different phases a calibration can be in. Since Python 2 does not have enums, this is hardcoded for the moment. Should this solution not be sufficient any more, one can make a better enum implementation by hand or install a backport of the python3 implementatio...
stack_v2_sparse_classes_36k_train_003306
43,413
no_license
[ { "docstring": "Return the ID of the given CalibrationPhase, passed as a string. :param str phase_name: Name of the CalibrationPhase. Allowed are: ECalDigi, HCalDigi, MuonAndHCalOtherDigi, ElectroMagEnergy, HadronicEnergy, PhotonTraining :returns: ID of this phase :rtype: int", "name": "phaseIDFromString", ...
4
null
Implement the Python class `CalibrationPhase` described below. Class description: Represents the different phases a calibration can be in. Since Python 2 does not have enums, this is hardcoded for the moment. Should this solution not be sufficient any more, one can make a better enum implementation by hand or install ...
Implement the Python class `CalibrationPhase` described below. Class description: Represents the different phases a calibration can be in. Since Python 2 does not have enums, this is hardcoded for the moment. Should this solution not be sufficient any more, one can make a better enum implementation by hand or install ...
9c366957fdd680a284df675c318989cb88e5959c
<|skeleton|> class CalibrationPhase: """Represents the different phases a calibration can be in. Since Python 2 does not have enums, this is hardcoded for the moment. Should this solution not be sufficient any more, one can make a better enum implementation by hand or install a backport of the python3 implementatio...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CalibrationPhase: """Represents the different phases a calibration can be in. Since Python 2 does not have enums, this is hardcoded for the moment. Should this solution not be sufficient any more, one can make a better enum implementation by hand or install a backport of the python3 implementation from PyPi."...
the_stack_v2_python_sparse
CalibrationSystem/Service/CalibrationRun.py
LCDsoft/ILCDIRAC
train
1
a8570e514bf71fc9e1774e0fc4ddf389422b0bd4
[ "serializer = self.invite_new_user_serializer_class(data=request.data)\nif not serializer.is_valid():\n return self.json_failed_response(errors=serializer.errors)\ndata_from_request = serializer.data\nif not is_user_allowed_cascade_down(request.user, data_from_request[GROUP]):\n return self.json_forbidden_res...
<|body_start_0|> serializer = self.invite_new_user_serializer_class(data=request.data) if not serializer.is_valid(): return self.json_failed_response(errors=serializer.errors) data_from_request = serializer.data if not is_user_allowed_cascade_down(request.user, data_from_requ...
view for inviting new users permission_required: CAN_INVITE_NEW_USER_PERMISSION
InviteNewUserView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class InviteNewUserView: """view for inviting new users permission_required: CAN_INVITE_NEW_USER_PERMISSION""" def post(self, request: Request, *args, **kwargs) -> Response: """request params: - email - group (group name) :return json response http response codes: 200 - ok, invitation emai...
stack_v2_sparse_classes_36k_train_003307
4,750
no_license
[ { "docstring": "request params: - email - group (group name) :return json response http response codes: 200 - ok, invitation email sent 400 - failed, validation error, view errors key 403 - failed, permission denied keys: success - true if invitation email sent and false otherwise errors - json of errors if suc...
4
null
Implement the Python class `InviteNewUserView` described below. Class description: view for inviting new users permission_required: CAN_INVITE_NEW_USER_PERMISSION Method signatures and docstrings: - def post(self, request: Request, *args, **kwargs) -> Response: request params: - email - group (group name) :return jso...
Implement the Python class `InviteNewUserView` described below. Class description: view for inviting new users permission_required: CAN_INVITE_NEW_USER_PERMISSION Method signatures and docstrings: - def post(self, request: Request, *args, **kwargs) -> Response: request params: - email - group (group name) :return jso...
bab909324aa2e4c1c8fff72093d3fcf44aaf4963
<|skeleton|> class InviteNewUserView: """view for inviting new users permission_required: CAN_INVITE_NEW_USER_PERMISSION""" def post(self, request: Request, *args, **kwargs) -> Response: """request params: - email - group (group name) :return json response http response codes: 200 - ok, invitation emai...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class InviteNewUserView: """view for inviting new users permission_required: CAN_INVITE_NEW_USER_PERMISSION""" def post(self, request: Request, *args, **kwargs) -> Response: """request params: - email - group (group name) :return json response http response codes: 200 - ok, invitation email sent 400 - ...
the_stack_v2_python_sparse
crm/views/invite_new_user/invite_new_user_view.py
vovapasko/crm
train
0
4316dd648a836b67fd26c58b4a557df4bfffc03e
[ "self.continue_on_error = continue_on_error\nself.is_active = is_active\nself.script_params = script_params\nself.script_path = script_path\nself.timeout_secs = timeout_secs", "if dictionary is None:\n return None\ncontinue_on_error = dictionary.get('continueOnError')\nis_active = dictionary.get('isActive')\ns...
<|body_start_0|> self.continue_on_error = continue_on_error self.is_active = is_active self.script_params = script_params self.script_path = script_path self.timeout_secs = timeout_secs <|end_body_0|> <|body_start_1|> if dictionary is None: return None ...
Implementation of the 'ScriptPathAndParams' model. A message to encapsulate pre or post script associated with a backup job policy. Attributes: continue_on_error (bool): Applicable only for pre backup scripts. If this flag is set to true, then backup job will start even if the pre backup script fails. is_active (bool):...
ScriptPathAndParams
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ScriptPathAndParams: """Implementation of the 'ScriptPathAndParams' model. A message to encapsulate pre or post script associated with a backup job policy. Attributes: continue_on_error (bool): Applicable only for pre backup scripts. If this flag is set to true, then backup job will start even if...
stack_v2_sparse_classes_36k_train_003308
3,226
permissive
[ { "docstring": "Constructor for the ScriptPathAndParams class", "name": "__init__", "signature": "def __init__(self, continue_on_error=None, is_active=None, script_params=None, script_path=None, timeout_secs=None)" }, { "docstring": "Creates an instance of this model from a dictionary Args: dict...
2
stack_v2_sparse_classes_30k_train_010414
Implement the Python class `ScriptPathAndParams` described below. Class description: Implementation of the 'ScriptPathAndParams' model. A message to encapsulate pre or post script associated with a backup job policy. Attributes: continue_on_error (bool): Applicable only for pre backup scripts. If this flag is set to t...
Implement the Python class `ScriptPathAndParams` described below. Class description: Implementation of the 'ScriptPathAndParams' model. A message to encapsulate pre or post script associated with a backup job policy. Attributes: continue_on_error (bool): Applicable only for pre backup scripts. If this flag is set to t...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class ScriptPathAndParams: """Implementation of the 'ScriptPathAndParams' model. A message to encapsulate pre or post script associated with a backup job policy. Attributes: continue_on_error (bool): Applicable only for pre backup scripts. If this flag is set to true, then backup job will start even if...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ScriptPathAndParams: """Implementation of the 'ScriptPathAndParams' model. A message to encapsulate pre or post script associated with a backup job policy. Attributes: continue_on_error (bool): Applicable only for pre backup scripts. If this flag is set to true, then backup job will start even if the pre back...
the_stack_v2_python_sparse
cohesity_management_sdk/models/script_path_and_params.py
cohesity/management-sdk-python
train
24
70215d625c1dfd9bbb9efc25c3cafd7db770ceef
[ "self.is_injected = False\nself.name = name\nself.variables = []\nself.update_ops = []\nself._inject(model_vars, k, alpha)", "if not self.is_injected:\n raise AttributeError('LookAhead have not been injected!!')\nreturn [self.slow_weights_op, self.fast_weights_op]", "with tf.compat.v1.variable_scope(self.nam...
<|body_start_0|> self.is_injected = False self.name = name self.variables = [] self.update_ops = [] self._inject(model_vars, k, alpha) <|end_body_0|> <|body_start_1|> if not self.is_injected: raise AttributeError('LookAhead have not been injected!!') ...
Lookahead optimization strategy for any optimizer. This implemention is based on: https://arxiv.org/abs/1907.08610 "Lookahead Optimizer: k steps forward, 1 step back" Mockael R. Zhang, Jamses Lucas, Geoffrey Hinton, Jimmy Ba
BaseLookAhead
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BaseLookAhead: """Lookahead optimization strategy for any optimizer. This implemention is based on: https://arxiv.org/abs/1907.08610 "Lookahead Optimizer: k steps forward, 1 step back" Mockael R. Zhang, Jamses Lucas, Geoffrey Hinton, Jimmy Ba""" def __init__(self, model_vars, k=5, alpha=0.5,...
stack_v2_sparse_classes_36k_train_003309
3,548
permissive
[ { "docstring": "[Args] k: the difined forward step k. [int] alpha: the defined learning rate for lookahead. [float] name: namescope. [str]", "name": "__init__", "signature": "def __init__(self, model_vars, k=5, alpha=0.5, name='lookahead')" }, { "docstring": "Returns the update operators for the...
4
stack_v2_sparse_classes_30k_train_006771
Implement the Python class `BaseLookAhead` described below. Class description: Lookahead optimization strategy for any optimizer. This implemention is based on: https://arxiv.org/abs/1907.08610 "Lookahead Optimizer: k steps forward, 1 step back" Mockael R. Zhang, Jamses Lucas, Geoffrey Hinton, Jimmy Ba Method signatu...
Implement the Python class `BaseLookAhead` described below. Class description: Lookahead optimization strategy for any optimizer. This implemention is based on: https://arxiv.org/abs/1907.08610 "Lookahead Optimizer: k steps forward, 1 step back" Mockael R. Zhang, Jamses Lucas, Geoffrey Hinton, Jimmy Ba Method signatu...
7a612d6d6856c0d947a901e936cd7da2cc7b1dde
<|skeleton|> class BaseLookAhead: """Lookahead optimization strategy for any optimizer. This implemention is based on: https://arxiv.org/abs/1907.08610 "Lookahead Optimizer: k steps forward, 1 step back" Mockael R. Zhang, Jamses Lucas, Geoffrey Hinton, Jimmy Ba""" def __init__(self, model_vars, k=5, alpha=0.5,...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BaseLookAhead: """Lookahead optimization strategy for any optimizer. This implemention is based on: https://arxiv.org/abs/1907.08610 "Lookahead Optimizer: k steps forward, 1 step back" Mockael R. Zhang, Jamses Lucas, Geoffrey Hinton, Jimmy Ba""" def __init__(self, model_vars, k=5, alpha=0.5, name='lookah...
the_stack_v2_python_sparse
gan/HamGAN/optimization.py
MenghaoGuo/Enjoy-Hamburger
train
1
9e9d6c4bd384f56dcb5f4a7b6f902d7633172654
[ "super(RNNDecoder, self).__init__()\nself.embedding = tf.keras.layers.Embedding(vocab, embedding)\nself.gru = tf.keras.layers.GRU(units, recurrent_initializer='glorot_uniform', return_sequences=True, return_state=True)\nself.F = tf.keras.layers.Dense(vocab)", "attention = SelfAttention(s_prev.shape[1])\ncontext, ...
<|body_start_0|> super(RNNDecoder, self).__init__() self.embedding = tf.keras.layers.Embedding(vocab, embedding) self.gru = tf.keras.layers.GRU(units, recurrent_initializer='glorot_uniform', return_sequences=True, return_state=True) self.F = tf.keras.layers.Dense(vocab) <|end_body_0|> <...
RNNDecoder Class
RNNDecoder
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RNNDecoder: """RNNDecoder Class""" def __init__(self, vocab, embedding, units, batch): """Class constructor :param vocab: int representing size of output vocabulary :param embedding: int representing dimensionality of embedding vector :param units: int representing num of hidden unit...
stack_v2_sparse_classes_36k_train_003310
2,479
no_license
[ { "docstring": "Class constructor :param vocab: int representing size of output vocabulary :param embedding: int representing dimensionality of embedding vector :param units: int representing num of hidden units in RNN cell :param batch: int representing batch size Public Instances embedding: Keras Embedding la...
2
null
Implement the Python class `RNNDecoder` described below. Class description: RNNDecoder Class Method signatures and docstrings: - def __init__(self, vocab, embedding, units, batch): Class constructor :param vocab: int representing size of output vocabulary :param embedding: int representing dimensionality of embedding...
Implement the Python class `RNNDecoder` described below. Class description: RNNDecoder Class Method signatures and docstrings: - def __init__(self, vocab, embedding, units, batch): Class constructor :param vocab: int representing size of output vocabulary :param embedding: int representing dimensionality of embedding...
4ac942126918c7acaa9ef88d18efe299b2f726fe
<|skeleton|> class RNNDecoder: """RNNDecoder Class""" def __init__(self, vocab, embedding, units, batch): """Class constructor :param vocab: int representing size of output vocabulary :param embedding: int representing dimensionality of embedding vector :param units: int representing num of hidden unit...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RNNDecoder: """RNNDecoder Class""" def __init__(self, vocab, embedding, units, batch): """Class constructor :param vocab: int representing size of output vocabulary :param embedding: int representing dimensionality of embedding vector :param units: int representing num of hidden units in RNN cell...
the_stack_v2_python_sparse
supervised_learning/0x11-attention/2-rnn_decoder.py
DracoMindz/holbertonschool-machine_learning
train
2
4461b2eba907b9afb6292ad0ef79f692485cc5db
[ "super(SeqClassificationTaskModel, self).__init__()\nmodel_type = model_config.get('model_type', 'transformer')\nhidden_size = model_config.get('hidden_size', 512)\nin_channels = hidden_size * 2 if model_type == 'lstm' else hidden_size\nself.conv_decoder = nn.Sequential(nn.Conv1D(in_channels=in_channels, out_channe...
<|body_start_0|> super(SeqClassificationTaskModel, self).__init__() model_type = model_config.get('model_type', 'transformer') hidden_size = model_config.get('hidden_size', 512) in_channels = hidden_size * 2 if model_type == 'lstm' else hidden_size self.conv_decoder = nn.Sequenti...
SeqClassificationTaskModel
SeqClassificationTaskModel
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SeqClassificationTaskModel: """SeqClassificationTaskModel""" def __init__(self, class_num, model_config, encoder_model): """__init__""" <|body_0|> def forward(self, input, pos): """forward""" <|body_1|> <|end_skeleton|> <|body_start_0|> super(Se...
stack_v2_sparse_classes_36k_train_003311
17,522
permissive
[ { "docstring": "__init__", "name": "__init__", "signature": "def __init__(self, class_num, model_config, encoder_model)" }, { "docstring": "forward", "name": "forward", "signature": "def forward(self, input, pos)" } ]
2
stack_v2_sparse_classes_30k_train_011676
Implement the Python class `SeqClassificationTaskModel` described below. Class description: SeqClassificationTaskModel Method signatures and docstrings: - def __init__(self, class_num, model_config, encoder_model): __init__ - def forward(self, input, pos): forward
Implement the Python class `SeqClassificationTaskModel` described below. Class description: SeqClassificationTaskModel Method signatures and docstrings: - def __init__(self, class_num, model_config, encoder_model): __init__ - def forward(self, input, pos): forward <|skeleton|> class SeqClassificationTaskModel: "...
e6ab0261eb719c21806bbadfd94001ecfe27de45
<|skeleton|> class SeqClassificationTaskModel: """SeqClassificationTaskModel""" def __init__(self, class_num, model_config, encoder_model): """__init__""" <|body_0|> def forward(self, input, pos): """forward""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SeqClassificationTaskModel: """SeqClassificationTaskModel""" def __init__(self, class_num, model_config, encoder_model): """__init__""" super(SeqClassificationTaskModel, self).__init__() model_type = model_config.get('model_type', 'transformer') hidden_size = model_config....
the_stack_v2_python_sparse
pahelix/model_zoo/protein_sequence_model.py
PaddlePaddle/PaddleHelix
train
771
423fc8ed9a661f05ac89e88953c37e34b867b3de
[ "color_generator = getsvgcolors()\nwork_list = load_work()\ngoals = set()\nfor work in work_list:\n if work.category not in ('snowball',):\n continue\n if not hasattr(work, '_meta'):\n continue\n goal = str(work._meta[0]['goal'])\n goals.add(goal)\nfor goal in sorted(goals):\n color, te...
<|body_start_0|> color_generator = getsvgcolors() work_list = load_work() goals = set() for work in work_list: if work.category not in ('snowball',): continue if not hasattr(work, '_meta'): continue goal = str(work._meta...
GoalGraph
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GoalGraph: def create_widgets(self): """Creates custom categories""" <|body_0|> def work_key(self, work): """Returns work goal""" <|body_1|> def filter_work(self, work): """Filters work""" <|body_2|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_36k_train_003312
8,363
no_license
[ { "docstring": "Creates custom categories", "name": "create_widgets", "signature": "def create_widgets(self)" }, { "docstring": "Returns work goal", "name": "work_key", "signature": "def work_key(self, work)" }, { "docstring": "Filters work", "name": "filter_work", "signa...
3
stack_v2_sparse_classes_30k_train_001980
Implement the Python class `GoalGraph` described below. Class description: Implement the GoalGraph class. Method signatures and docstrings: - def create_widgets(self): Creates custom categories - def work_key(self, work): Returns work goal - def filter_work(self, work): Filters work
Implement the Python class `GoalGraph` described below. Class description: Implement the GoalGraph class. Method signatures and docstrings: - def create_widgets(self): Creates custom categories - def work_key(self, work): Returns work goal - def filter_work(self, work): Filters work <|skeleton|> class GoalGraph: ...
92997453631f31d7f751861feb9f0d0c76af54d3
<|skeleton|> class GoalGraph: def create_widgets(self): """Creates custom categories""" <|body_0|> def work_key(self, work): """Returns work goal""" <|body_1|> def filter_work(self, work): """Filters work""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GoalGraph: def create_widgets(self): """Creates custom categories""" color_generator = getsvgcolors() work_list = load_work() goals = set() for work in work_list: if work.category not in ('snowball',): continue if not hasattr(work...
the_stack_v2_python_sparse
notebooks/graph.py
dew-uff/scripts-provenance
train
1
9a980224f17c75043a4370594c21548494dc0e58
[ "idx = {}\na = headA\nwhile a:\n idx[a] = None\n a = a.next\nb = headB\nwhile b:\n if b in idx:\n return b\n b = b.next\nreturn None", "if not headA or not headB:\n return None\na, b = (headA, headB)\nwhile a != b:\n a = a.next if a else headB\n b = b.next if b else headA\nreturn a" ]
<|body_start_0|> idx = {} a = headA while a: idx[a] = None a = a.next b = headB while b: if b in idx: return b b = b.next return None <|end_body_0|> <|body_start_1|> if not headA or not headB: ...
OfficialSolution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OfficialSolution: def get_intersection_node(self, headA: ListNode, headB: ListNode) -> ListNode: """哈希表法。""" <|body_0|> def get_intersection_node(self, headA: ListNode, headB: ListNode) -> ListNode: """双指针。 设指针 a,b 分别指向链表 A,B 的头部, 然后分别遍历链表,当遍历完当前链表,便将指针指向另一个链表的头部,继续遍...
stack_v2_sparse_classes_36k_train_003313
5,154
no_license
[ { "docstring": "哈希表法。", "name": "get_intersection_node", "signature": "def get_intersection_node(self, headA: ListNode, headB: ListNode) -> ListNode" }, { "docstring": "双指针。 设指针 a,b 分别指向链表 A,B 的头部, 然后分别遍历链表,当遍历完当前链表,便将指针指向另一个链表的头部,继续遍历,直至 2 个指针相遇。 即: - 指针 a 遍历完链表 A 时,把指针 a 指向链表 B; - 指针 b 遍历完链表 B...
2
null
Implement the Python class `OfficialSolution` described below. Class description: Implement the OfficialSolution class. Method signatures and docstrings: - def get_intersection_node(self, headA: ListNode, headB: ListNode) -> ListNode: 哈希表法。 - def get_intersection_node(self, headA: ListNode, headB: ListNode) -> ListNo...
Implement the Python class `OfficialSolution` described below. Class description: Implement the OfficialSolution class. Method signatures and docstrings: - def get_intersection_node(self, headA: ListNode, headB: ListNode) -> ListNode: 哈希表法。 - def get_intersection_node(self, headA: ListNode, headB: ListNode) -> ListNo...
6932d69353b94ec824dd0ddc86a92453f6673232
<|skeleton|> class OfficialSolution: def get_intersection_node(self, headA: ListNode, headB: ListNode) -> ListNode: """哈希表法。""" <|body_0|> def get_intersection_node(self, headA: ListNode, headB: ListNode) -> ListNode: """双指针。 设指针 a,b 分别指向链表 A,B 的头部, 然后分别遍历链表,当遍历完当前链表,便将指针指向另一个链表的头部,继续遍...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OfficialSolution: def get_intersection_node(self, headA: ListNode, headB: ListNode) -> ListNode: """哈希表法。""" idx = {} a = headA while a: idx[a] = None a = a.next b = headB while b: if b in idx: return b ...
the_stack_v2_python_sparse
0160_intersection-of-two-linked-lists.py
Nigirimeshi/leetcode
train
0
c814413a89f1a2ba365ccf859a397170ddd11655
[ "super(EnsembleLayer, self).__init__()\nself.type = typ\nself.input_size = input_size\nself.output_size = output_size\nself.ensemble_size = ensemble_size\nself.act_fn = fn\nif typ == 'prob':\n self.ensemble = nn.ModuleList([nn.Sequential(nn.Linear(input_size, output_size), fn) for _ in range(ensemble_size)])\nel...
<|body_start_0|> super(EnsembleLayer, self).__init__() self.type = typ self.input_size = input_size self.output_size = output_size self.ensemble_size = ensemble_size self.act_fn = fn if typ == 'prob': self.ensemble = nn.ModuleList([nn.Sequential(nn.Lin...
Following Lee at al (2015) we implement probability and score averaging model ensembles.
EnsembleLayer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EnsembleLayer: """Following Lee at al (2015) we implement probability and score averaging model ensembles.""" def __init__(self, typ, input_size, output_size, ensemble_size=5, fn=nn.ReLU()): """Args: typ {str} from {'pron', 'score'} depending on whether the ensemble includes the acti...
stack_v2_sparse_classes_36k_train_003314
25,239
no_license
[ { "docstring": "Args: typ {str} from {'pron', 'score'} depending on whether the ensemble includes the activation function ('prob'). input_size {int} amount of input neurons output_size {int} amount of output neurons (# tasks/classes) ensemble_size {int} amount of parallel ensemble learners act_fn {int} activati...
2
stack_v2_sparse_classes_30k_train_019655
Implement the Python class `EnsembleLayer` described below. Class description: Following Lee at al (2015) we implement probability and score averaging model ensembles. Method signatures and docstrings: - def __init__(self, typ, input_size, output_size, ensemble_size=5, fn=nn.ReLU()): Args: typ {str} from {'pron', 'sc...
Implement the Python class `EnsembleLayer` described below. Class description: Following Lee at al (2015) we implement probability and score averaging model ensembles. Method signatures and docstrings: - def __init__(self, typ, input_size, output_size, ensemble_size=5, fn=nn.ReLU()): Args: typ {str} from {'pron', 'sc...
e88840528fa963066f85940ffeb31687773be2ba
<|skeleton|> class EnsembleLayer: """Following Lee at al (2015) we implement probability and score averaging model ensembles.""" def __init__(self, typ, input_size, output_size, ensemble_size=5, fn=nn.ReLU()): """Args: typ {str} from {'pron', 'score'} depending on whether the ensemble includes the acti...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EnsembleLayer: """Following Lee at al (2015) we implement probability and score averaging model ensembles.""" def __init__(self, typ, input_size, output_size, ensemble_size=5, fn=nn.ReLU()): """Args: typ {str} from {'pron', 'score'} depending on whether the ensemble includes the activation functi...
the_stack_v2_python_sparse
Utility/layers.py
kaicd/KAICD_pipeline
train
0
21150f240eca3a16f11dcb8503c350d619b6eae3
[ "if contact_bins is None:\n self.contact_bins = SPLIF_CONTACT_BINS\nelse:\n self.contact_bins = contact_bins\nself.size = size\nself.radius = radius", "if 'complex' in kwargs:\n datapoint = kwargs.get('complex')\n raise DeprecationWarning('Complex is being phased out as a parameter, please pass \"data...
<|body_start_0|> if contact_bins is None: self.contact_bins = SPLIF_CONTACT_BINS else: self.contact_bins = contact_bins self.size = size self.radius = radius <|end_body_0|> <|body_start_1|> if 'complex' in kwargs: datapoint = kwargs.get('compl...
Computes SPLIF Fingerprints for a macromolecular complex. SPLIF fingerprints are based on a technique introduced in the following paper. Da, C., and D. Kireev. "Structural protein–ligand interaction fingerprints (SPLIF) for structure-based virtual screening: method and benchmark study." Journal of chemical information ...
SplifFingerprint
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SplifFingerprint: """Computes SPLIF Fingerprints for a macromolecular complex. SPLIF fingerprints are based on a technique introduced in the following paper. Da, C., and D. Kireev. "Structural protein–ligand interaction fingerprints (SPLIF) for structure-based virtual screening: method and benchm...
stack_v2_sparse_classes_36k_train_003315
11,465
permissive
[ { "docstring": "Parameters ---------- contact_bins: list[tuple] List of contact bins. If not specified is set to default `[(0, 2.0), (2.0, 3.0), (3.0, 4.5)]`. radius : int, optional (default 2) Fingerprint radius used for circular fingerprints. size: int, optional (default 8) Length of generated bit vector.", ...
2
null
Implement the Python class `SplifFingerprint` described below. Class description: Computes SPLIF Fingerprints for a macromolecular complex. SPLIF fingerprints are based on a technique introduced in the following paper. Da, C., and D. Kireev. "Structural protein–ligand interaction fingerprints (SPLIF) for structure-bas...
Implement the Python class `SplifFingerprint` described below. Class description: Computes SPLIF Fingerprints for a macromolecular complex. SPLIF fingerprints are based on a technique introduced in the following paper. Da, C., and D. Kireev. "Structural protein–ligand interaction fingerprints (SPLIF) for structure-bas...
ee6e67ebcf7bf04259cf13aff6388e2b791fea3d
<|skeleton|> class SplifFingerprint: """Computes SPLIF Fingerprints for a macromolecular complex. SPLIF fingerprints are based on a technique introduced in the following paper. Da, C., and D. Kireev. "Structural protein–ligand interaction fingerprints (SPLIF) for structure-based virtual screening: method and benchm...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SplifFingerprint: """Computes SPLIF Fingerprints for a macromolecular complex. SPLIF fingerprints are based on a technique introduced in the following paper. Da, C., and D. Kireev. "Structural protein–ligand interaction fingerprints (SPLIF) for structure-based virtual screening: method and benchmark study." J...
the_stack_v2_python_sparse
deepchem/feat/complex_featurizers/splif_fingerprints.py
deepchem/deepchem
train
4,876
1ccb5d6e2690a3478249ed20178d14dba5372360
[ "super(KerasResnet, self).__init__(**kwargs)\nmode = 'train'\nself.mode = mode\nself.logger = logging.getLogger(__name__)\nself.model = self.build_model(self.data.get_feature_shape(), self.data.num_classes)\nprint(self.model.summary())\nif self.data.y_train is not None and self.data.y_val is not None:\n print('T...
<|body_start_0|> super(KerasResnet, self).__init__(**kwargs) mode = 'train' self.mode = mode self.logger = logging.getLogger(__name__) self.model = self.build_model(self.data.get_feature_shape(), self.data.num_classes) print(self.model.summary()) if self.data.y_tr...
ResNet model.
KerasResnet
[ "BSD-3-Clause", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-protobuf", "Apache-2.0", "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class KerasResnet: """ResNet model.""" def __init__(self, **kwargs): """ResNet constructor. Args: mode: One of 'train' and 'eval'.""" <|body_0|> def build_model(input_shape, num_classes, depth=20): """Build the model Args: input_shape (numpy.ndarray): shape of the inpu...
stack_v2_sparse_classes_36k_train_003316
6,879
permissive
[ { "docstring": "ResNet constructor. Args: mode: One of 'train' and 'eval'.", "name": "__init__", "signature": "def __init__(self, **kwargs)" }, { "docstring": "Build the model Args: input_shape (numpy.ndarray): shape of the input to the model num_classes (int): Number of classes in the output de...
2
null
Implement the Python class `KerasResnet` described below. Class description: ResNet model. Method signatures and docstrings: - def __init__(self, **kwargs): ResNet constructor. Args: mode: One of 'train' and 'eval'. - def build_model(input_shape, num_classes, depth=20): Build the model Args: input_shape (numpy.ndarra...
Implement the Python class `KerasResnet` described below. Class description: ResNet model. Method signatures and docstrings: - def __init__(self, **kwargs): ResNet constructor. Args: mode: One of 'train' and 'eval'. - def build_model(input_shape, num_classes, depth=20): Build the model Args: input_shape (numpy.ndarra...
d8e2d22dfccfb8488f70f1fb5593d4e6ee1eca1f
<|skeleton|> class KerasResnet: """ResNet model.""" def __init__(self, **kwargs): """ResNet constructor. Args: mode: One of 'train' and 'eval'.""" <|body_0|> def build_model(input_shape, num_classes, depth=20): """Build the model Args: input_shape (numpy.ndarray): shape of the inpu...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class KerasResnet: """ResNet model.""" def __init__(self, **kwargs): """ResNet constructor. Args: mode: One of 'train' and 'eval'.""" super(KerasResnet, self).__init__(**kwargs) mode = 'train' self.mode = mode self.logger = logging.getLogger(__name__) self.model ...
the_stack_v2_python_sparse
openfl/models/tensorflow/keras_resnet/keras_resnet.py
sbakas/OpenFederatedLearning-1
train
0
0f29dfbeb8b6a0df5cb497b266db133252027762
[ "def backtrack(nums, size, start, path):\n res.append(path[:])\n for i in range(start, size):\n path.append(nums[i])\n backtrack(nums, size, i + 1, path)\n path.pop()\nres = []\nsize = len(nums)\nbacktrack(nums, size, 0, [])\nreturn res", "if len(nums) == 0:\n return [[]]\nlast = num...
<|body_start_0|> def backtrack(nums, size, start, path): res.append(path[:]) for i in range(start, size): path.append(nums[i]) backtrack(nums, size, i + 1, path) path.pop() res = [] size = len(nums) backtrack(nums, s...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def subsets(self, nums: List[int]) -> List[List[int]]: """题解:https://leetcode-cn.com/problems/subsets/solution/c-zong-jie-liao-hui-su-wen-ti-lei-xing-dai-ni-gao-/""" <|body_0|> def subsets1(self, nums: List[int]) -> List[List[int]]: """数学归纳递归:subset([1,2,3]...
stack_v2_sparse_classes_36k_train_003317
3,816
permissive
[ { "docstring": "题解:https://leetcode-cn.com/problems/subsets/solution/c-zong-jie-liao-hui-su-wen-ti-lei-xing-dai-ni-gao-/", "name": "subsets", "signature": "def subsets(self, nums: List[int]) -> List[List[int]]" }, { "docstring": "数学归纳递归:subset([1,2,3]) = A + [A[i].add(3) for i = 1..len(A)] https...
5
stack_v2_sparse_classes_30k_train_008581
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def subsets(self, nums: List[int]) -> List[List[int]]: 题解:https://leetcode-cn.com/problems/subsets/solution/c-zong-jie-liao-hui-su-wen-ti-lei-xing-dai-ni-gao-/ - def subsets1(sel...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def subsets(self, nums: List[int]) -> List[List[int]]: 题解:https://leetcode-cn.com/problems/subsets/solution/c-zong-jie-liao-hui-su-wen-ti-lei-xing-dai-ni-gao-/ - def subsets1(sel...
e8a1c6cae6547cbcb6e8494be6df685f3e7c837c
<|skeleton|> class Solution: def subsets(self, nums: List[int]) -> List[List[int]]: """题解:https://leetcode-cn.com/problems/subsets/solution/c-zong-jie-liao-hui-su-wen-ti-lei-xing-dai-ni-gao-/""" <|body_0|> def subsets1(self, nums: List[int]) -> List[List[int]]: """数学归纳递归:subset([1,2,3]...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def subsets(self, nums: List[int]) -> List[List[int]]: """题解:https://leetcode-cn.com/problems/subsets/solution/c-zong-jie-liao-hui-su-wen-ti-lei-xing-dai-ni-gao-/""" def backtrack(nums, size, start, path): res.append(path[:]) for i in range(start, size): ...
the_stack_v2_python_sparse
78-subsets.py
yuenliou/leetcode
train
0
86e0fe266dd5d09fdb76c269547f9d01393ea1ac
[ "self._output_size = output_size\nself._train_on_crops = train_on_crops\nself._resize_eval_groundtruth = resize_eval_groundtruth\nif not resize_eval_groundtruth and groundtruth_padded_size is None:\n raise ValueError('groundtruth_padded_size ([height, width]) needs to bespecified when resize_eval_groundtruth is ...
<|body_start_0|> self._output_size = output_size self._train_on_crops = train_on_crops self._resize_eval_groundtruth = resize_eval_groundtruth if not resize_eval_groundtruth and groundtruth_padded_size is None: raise ValueError('groundtruth_padded_size ([height, width]) needs...
Parser to parse an image and its annotations into a dictionary of tensors.
Parser
[ "Apache-2.0", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Parser: """Parser to parse an image and its annotations into a dictionary of tensors.""" def __init__(self, output_size, train_on_crops=False, resize_eval_groundtruth=True, groundtruth_padded_size=None, ignore_label=255, aug_rand_hflip=False, aug_scale_min=1.0, aug_scale_max=1.0, dtype='floa...
stack_v2_sparse_classes_36k_train_003318
7,966
permissive
[ { "docstring": "Initializes parameters for parsing annotations in the dataset. Args: output_size: `Tensor` or `list` for [height, width] of output image. The output_size should be divided by the largest feature stride 2^max_level. train_on_crops: `bool`, if True, a training crop of size output_size is returned....
4
null
Implement the Python class `Parser` described below. Class description: Parser to parse an image and its annotations into a dictionary of tensors. Method signatures and docstrings: - def __init__(self, output_size, train_on_crops=False, resize_eval_groundtruth=True, groundtruth_padded_size=None, ignore_label=255, aug...
Implement the Python class `Parser` described below. Class description: Parser to parse an image and its annotations into a dictionary of tensors. Method signatures and docstrings: - def __init__(self, output_size, train_on_crops=False, resize_eval_groundtruth=True, groundtruth_padded_size=None, ignore_label=255, aug...
6fc53292b1d3ce3c0340ce724c2c11c77e663d27
<|skeleton|> class Parser: """Parser to parse an image and its annotations into a dictionary of tensors.""" def __init__(self, output_size, train_on_crops=False, resize_eval_groundtruth=True, groundtruth_padded_size=None, ignore_label=255, aug_rand_hflip=False, aug_scale_min=1.0, aug_scale_max=1.0, dtype='floa...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Parser: """Parser to parse an image and its annotations into a dictionary of tensors.""" def __init__(self, output_size, train_on_crops=False, resize_eval_groundtruth=True, groundtruth_padded_size=None, ignore_label=255, aug_rand_hflip=False, aug_scale_min=1.0, aug_scale_max=1.0, dtype='float32'): ...
the_stack_v2_python_sparse
models/official/vision/beta/dataloaders/segmentation_input.py
aboerzel/German_License_Plate_Recognition
train
34
3921ffc20c6e6fcb32261a5b42c703f6855121ff
[ "self.angle1 = angle1\nself.angle2 = angle2\nself.angle3 = angle3\nnumber_of_sides = 3", "if self.angle1 + self.angle2 + self.angle3 == 180:\n print('This is a triangle')\n return True\nelse:\n print('This is not a traingle')\n return False" ]
<|body_start_0|> self.angle1 = angle1 self.angle2 = angle2 self.angle3 = angle3 number_of_sides = 3 <|end_body_0|> <|body_start_1|> if self.angle1 + self.angle2 + self.angle3 == 180: print('This is a triangle') return True else: print(...
validateTriangle
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class validateTriangle: def __init__(self, angle1, angle2, angle3): """initializing""" <|body_0|> def checkValidity(self): """function to check if three sides form a triangle or not""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.angle1 = angle1 ...
stack_v2_sparse_classes_36k_train_003319
738
no_license
[ { "docstring": "initializing", "name": "__init__", "signature": "def __init__(self, angle1, angle2, angle3)" }, { "docstring": "function to check if three sides form a triangle or not", "name": "checkValidity", "signature": "def checkValidity(self)" } ]
2
stack_v2_sparse_classes_30k_val_000417
Implement the Python class `validateTriangle` described below. Class description: Implement the validateTriangle class. Method signatures and docstrings: - def __init__(self, angle1, angle2, angle3): initializing - def checkValidity(self): function to check if three sides form a triangle or not
Implement the Python class `validateTriangle` described below. Class description: Implement the validateTriangle class. Method signatures and docstrings: - def __init__(self, angle1, angle2, angle3): initializing - def checkValidity(self): function to check if three sides form a triangle or not <|skeleton|> class va...
646355ed2334cc28ab5ceedbd6d7036a5aa331ee
<|skeleton|> class validateTriangle: def __init__(self, angle1, angle2, angle3): """initializing""" <|body_0|> def checkValidity(self): """function to check if three sides form a triangle or not""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class validateTriangle: def __init__(self, angle1, angle2, angle3): """initializing""" self.angle1 = angle1 self.angle2 = angle2 self.angle3 = angle3 number_of_sides = 3 def checkValidity(self): """function to check if three sides form a triangle or not""" ...
the_stack_v2_python_sparse
validate_triangle.py
vidzierlein/Internship-Sep2020-Code
train
0
e644580f866c9077292b996484b25ac8e7bba683
[ "self.graph = tf.Graph()\ngraph_def = None\ntar_file = tarfile.open(tarball_path)\nfor tar_info in tar_file.getmembers():\n if self.FROZEN_GRAPH_NAME in os.path.basename(tar_info.name):\n file_handle = tar_file.extractfile(tar_info)\n graph_def = tf.GraphDef.FromString(file_handle.read())\n ...
<|body_start_0|> self.graph = tf.Graph() graph_def = None tar_file = tarfile.open(tarball_path) for tar_info in tar_file.getmembers(): if self.FROZEN_GRAPH_NAME in os.path.basename(tar_info.name): file_handle = tar_file.extractfile(tar_info) gr...
Class to load deeplab model and run inference.
DeepLabModel
[ "MIT", "LicenseRef-scancode-proprietary-license" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DeepLabModel: """Class to load deeplab model and run inference.""" def __init__(self, tarball_path): """Creates and loads pretrained deeplab model.""" <|body_0|> def run(self, image): """Runs inference on a single image. Args: image: A PIL.Image object, raw input...
stack_v2_sparse_classes_36k_train_003320
4,258
permissive
[ { "docstring": "Creates and loads pretrained deeplab model.", "name": "__init__", "signature": "def __init__(self, tarball_path)" }, { "docstring": "Runs inference on a single image. Args: image: A PIL.Image object, raw input image. Returns: resized_image: RGB image resized from original input i...
2
stack_v2_sparse_classes_30k_val_000967
Implement the Python class `DeepLabModel` described below. Class description: Class to load deeplab model and run inference. Method signatures and docstrings: - def __init__(self, tarball_path): Creates and loads pretrained deeplab model. - def run(self, image): Runs inference on a single image. Args: image: A PIL.Im...
Implement the Python class `DeepLabModel` described below. Class description: Class to load deeplab model and run inference. Method signatures and docstrings: - def __init__(self, tarball_path): Creates and loads pretrained deeplab model. - def run(self, image): Runs inference on a single image. Args: image: A PIL.Im...
05946339e5a478216d7a9234e29e9bd7af5b3492
<|skeleton|> class DeepLabModel: """Class to load deeplab model and run inference.""" def __init__(self, tarball_path): """Creates and loads pretrained deeplab model.""" <|body_0|> def run(self, image): """Runs inference on a single image. Args: image: A PIL.Image object, raw input...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DeepLabModel: """Class to load deeplab model and run inference.""" def __init__(self, tarball_path): """Creates and loads pretrained deeplab model.""" self.graph = tf.Graph() graph_def = None tar_file = tarfile.open(tarball_path) for tar_info in tar_file.getmembers...
the_stack_v2_python_sparse
GAN_preprocess/deeplab_demo.py
sun-yitao/GrabAIChallenge
train
10
7cd53c77c6c11968aa5daf29a67a4a315491adb6
[ "image = warpWithLandmarks5.warp.warpedImage.coreImage\nlandmarks = warpWithLandmarks5.landmarks.coreEstimation\nif asyncEstimate:\n task = self._coreEstimator.asyncEstimate(image, landmarks)\n return AsyncTask(task, POST_PROCESSING.postProcessing)\nerror, gaze = self._coreEstimator.estimate(image, landmarks)...
<|body_start_0|> image = warpWithLandmarks5.warp.warpedImage.coreImage landmarks = warpWithLandmarks5.landmarks.coreEstimation if asyncEstimate: task = self._coreEstimator.asyncEstimate(image, landmarks) return AsyncTask(task, POST_PROCESSING.postProcessing) error...
Red-eye estimator.
RedEyesEstimator
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RedEyesEstimator: """Red-eye estimator.""" def estimate(self, warpWithLandmarks5: WarpWithLandmarks5, asyncEstimate: bool=False) -> Union[RedEyes, AsyncTask[RedEyes]]: """Estimate red-eye on warp. Args: warpWithLandmarks5: warped image with transformed landmarks asyncEstimate: estima...
stack_v2_sparse_classes_36k_train_003321
4,636
permissive
[ { "docstring": "Estimate red-eye on warp. Args: warpWithLandmarks5: warped image with transformed landmarks asyncEstimate: estimate or run estimation in background Returns: estimated red-eye statuses if asyncEstimate is false otherwise async task Raises: LunaSDKException: if estimation failed", "name": "est...
2
stack_v2_sparse_classes_30k_test_000042
Implement the Python class `RedEyesEstimator` described below. Class description: Red-eye estimator. Method signatures and docstrings: - def estimate(self, warpWithLandmarks5: WarpWithLandmarks5, asyncEstimate: bool=False) -> Union[RedEyes, AsyncTask[RedEyes]]: Estimate red-eye on warp. Args: warpWithLandmarks5: warp...
Implement the Python class `RedEyesEstimator` described below. Class description: Red-eye estimator. Method signatures and docstrings: - def estimate(self, warpWithLandmarks5: WarpWithLandmarks5, asyncEstimate: bool=False) -> Union[RedEyes, AsyncTask[RedEyes]]: Estimate red-eye on warp. Args: warpWithLandmarks5: warp...
7a4bebc92ae7a96d8d9c18a024208308942f90cd
<|skeleton|> class RedEyesEstimator: """Red-eye estimator.""" def estimate(self, warpWithLandmarks5: WarpWithLandmarks5, asyncEstimate: bool=False) -> Union[RedEyes, AsyncTask[RedEyes]]: """Estimate red-eye on warp. Args: warpWithLandmarks5: warped image with transformed landmarks asyncEstimate: estima...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RedEyesEstimator: """Red-eye estimator.""" def estimate(self, warpWithLandmarks5: WarpWithLandmarks5, asyncEstimate: bool=False) -> Union[RedEyes, AsyncTask[RedEyes]]: """Estimate red-eye on warp. Args: warpWithLandmarks5: warped image with transformed landmarks asyncEstimate: estimate or run est...
the_stack_v2_python_sparse
lunavl/sdk/estimators/face_estimators/red_eye.py
matemax/lunasdk
train
16
b9bf926936cd93a24b3dd42442ddc72f23a45233
[ "print(nums)\nn = len(nums)\nleft, right = (0, 0)\nwhile right < n:\n if nums[left] == 0:\n right += 1\n if right < n and nums[right] != 0:\n nums[left], nums[right] = (nums[right], nums[left])\n left += 1\n else:\n left += 1\nprint(nums)\nreturn nums", "print(nums...
<|body_start_0|> print(nums) n = len(nums) left, right = (0, 0) while right < n: if nums[left] == 0: right += 1 if right < n and nums[right] != 0: nums[left], nums[right] = (nums[right], nums[left]) left ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def moveZeroes(self, nums: List[int]) -> None: """Do not return anything, modify nums in-place instead.""" <|body_0|> def moveZeroes2(self, nums: List[int]) -> None: """Do not return anything, modify nums in-place instead.""" <|body_1|> def mov...
stack_v2_sparse_classes_36k_train_003322
2,855
no_license
[ { "docstring": "Do not return anything, modify nums in-place instead.", "name": "moveZeroes", "signature": "def moveZeroes(self, nums: List[int]) -> None" }, { "docstring": "Do not return anything, modify nums in-place instead.", "name": "moveZeroes2", "signature": "def moveZeroes2(self,...
5
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def moveZeroes(self, nums: List[int]) -> None: Do not return anything, modify nums in-place instead. - def moveZeroes2(self, nums: List[int]) -> None: Do not return anything, mod...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def moveZeroes(self, nums: List[int]) -> None: Do not return anything, modify nums in-place instead. - def moveZeroes2(self, nums: List[int]) -> None: Do not return anything, mod...
e43ee86c5a8cdb808da09b4b6138e10275abadb5
<|skeleton|> class Solution: def moveZeroes(self, nums: List[int]) -> None: """Do not return anything, modify nums in-place instead.""" <|body_0|> def moveZeroes2(self, nums: List[int]) -> None: """Do not return anything, modify nums in-place instead.""" <|body_1|> def mov...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def moveZeroes(self, nums: List[int]) -> None: """Do not return anything, modify nums in-place instead.""" print(nums) n = len(nums) left, right = (0, 0) while right < n: if nums[left] == 0: right += 1 if right < n a...
the_stack_v2_python_sparse
LeetCode/双指针(two points)/283. Move Zeroes.py
yiming1012/MyLeetCode
train
2
4aa1a8f7b1844258ef13a83e3b7c556dfe311d17
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn BookingWorkHours()", "from .booking_work_time_slot import BookingWorkTimeSlot\nfrom .day_of_week import DayOfWeek\nfrom .booking_work_time_slot import BookingWorkTimeSlot\nfrom .day_of_week import DayOfWeek\nfields: Dict[str, Callable[...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return BookingWorkHours() <|end_body_0|> <|body_start_1|> from .booking_work_time_slot import BookingWorkTimeSlot from .day_of_week import DayOfWeek from .booking_work_time_slot import ...
This type represents the set of working hours in a single day of the week.
BookingWorkHours
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BookingWorkHours: """This type represents the set of working hours in a single day of the week.""" def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BookingWorkHours: """Creates a new instance of the appropriate class based on discriminator value Args: pars...
stack_v2_sparse_classes_36k_train_003323
3,164
permissive
[ { "docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: BookingWorkHours", "name": "create_from_discriminator_value", "signature": "def create_from_discriminator_va...
3
null
Implement the Python class `BookingWorkHours` described below. Class description: This type represents the set of working hours in a single day of the week. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BookingWorkHours: Creates a new instance of the ...
Implement the Python class `BookingWorkHours` described below. Class description: This type represents the set of working hours in a single day of the week. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BookingWorkHours: Creates a new instance of the ...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class BookingWorkHours: """This type represents the set of working hours in a single day of the week.""" def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BookingWorkHours: """Creates a new instance of the appropriate class based on discriminator value Args: pars...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BookingWorkHours: """This type represents the set of working hours in a single day of the week.""" def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BookingWorkHours: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The p...
the_stack_v2_python_sparse
msgraph/generated/models/booking_work_hours.py
microsoftgraph/msgraph-sdk-python
train
135
fd12b40a6ba32ae214bd14b06ab4b1f2e55d86c4
[ "super(DataArchive, self).__init__(inputs, outputs, **kwargs)\nself.datastore = datastore\nself.packet_dict = defaultdict(dict)\nfor k, v in tlm.getDefaultDict().iteritems():\n self.packet_dict[v.uid] = v\ntry:\n mod, cls = self.datastore.rsplit('.', 1)\n self.dbconn = getattr(importlib.import_module(mod),...
<|body_start_0|> super(DataArchive, self).__init__(inputs, outputs, **kwargs) self.datastore = datastore self.packet_dict = defaultdict(dict) for k, v in tlm.getDefaultDict().iteritems(): self.packet_dict[v.uid] = v try: mod, cls = self.datastore.rsplit('....
DataArchive
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DataArchive: def __init__(self, inputs, outputs, datastore='ait.core.db.InfluxDBBackend', **kwargs): """Attempts to connect to database backend. Plugin will not be created if connection fails. Creates base packet dictionary for decoding packets with packet UIDs as keys and packet definit...
stack_v2_sparse_classes_36k_train_003324
7,504
permissive
[ { "docstring": "Attempts to connect to database backend. Plugin will not be created if connection fails. Creates base packet dictionary for decoding packets with packet UIDs as keys and packet definitions as values. Params: inputs: list of names of input streams to plugin outputs: list of names of plugin output...
2
stack_v2_sparse_classes_30k_train_012595
Implement the Python class `DataArchive` described below. Class description: Implement the DataArchive class. Method signatures and docstrings: - def __init__(self, inputs, outputs, datastore='ait.core.db.InfluxDBBackend', **kwargs): Attempts to connect to database backend. Plugin will not be created if connection fa...
Implement the Python class `DataArchive` described below. Class description: Implement the DataArchive class. Method signatures and docstrings: - def __init__(self, inputs, outputs, datastore='ait.core.db.InfluxDBBackend', **kwargs): Attempts to connect to database backend. Plugin will not be created if connection fa...
d746079bcff574d930f633bee59337eabf54e99c
<|skeleton|> class DataArchive: def __init__(self, inputs, outputs, datastore='ait.core.db.InfluxDBBackend', **kwargs): """Attempts to connect to database backend. Plugin will not be created if connection fails. Creates base packet dictionary for decoding packets with packet UIDs as keys and packet definit...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DataArchive: def __init__(self, inputs, outputs, datastore='ait.core.db.InfluxDBBackend', **kwargs): """Attempts to connect to database backend. Plugin will not be created if connection fails. Creates base packet dictionary for decoding packets with packet UIDs as keys and packet definitions as values...
the_stack_v2_python_sparse
ait/core/server/plugin.py
seanlu99/AIT-Core
train
1
f4024a3136f0a56071238bd8822c94c61a10c346
[ "if output_md is None:\n output_md = metadata_info.ClassificationTensorMd(name=_OUTPUT_NAME, description=_OUTPUT_DESCRIPTION)\nreturn cls.create_from_metadata_info_for_multihead(model_buffer, general_md, input_md, [output_md])", "if general_md is None:\n general_md = metadata_info.GeneralMd(name=_MODEL_NAME...
<|body_start_0|> if output_md is None: output_md = metadata_info.ClassificationTensorMd(name=_OUTPUT_NAME, description=_OUTPUT_DESCRIPTION) return cls.create_from_metadata_info_for_multihead(model_buffer, general_md, input_md, [output_md]) <|end_body_0|> <|body_start_1|> if general_...
Writes metadata into an audio classifier.
MetadataWriter
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause", "GPL-1.0-or-later", "MIT", "LGPL-2.0-or-later" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MetadataWriter: """Writes metadata into an audio classifier.""" def create_from_metadata_info(cls, model_buffer: bytearray, general_md: Optional[metadata_info.GeneralMd]=None, input_md: Optional[metadata_info.InputAudioTensorMd]=None, output_md: Optional[metadata_info.ClassificationTensorMd]...
stack_v2_sparse_classes_36k_train_003325
7,060
permissive
[ { "docstring": "Creates MetadataWriter based on general/input/output information. Args: model_buffer: valid buffer of the model file. general_md: general information about the model. If not specified, default general metadata will be generated. input_md: input audio tensor informaton. If not specified, default ...
3
stack_v2_sparse_classes_30k_train_008185
Implement the Python class `MetadataWriter` described below. Class description: Writes metadata into an audio classifier. Method signatures and docstrings: - def create_from_metadata_info(cls, model_buffer: bytearray, general_md: Optional[metadata_info.GeneralMd]=None, input_md: Optional[metadata_info.InputAudioTenso...
Implement the Python class `MetadataWriter` described below. Class description: Writes metadata into an audio classifier. Method signatures and docstrings: - def create_from_metadata_info(cls, model_buffer: bytearray, general_md: Optional[metadata_info.GeneralMd]=None, input_md: Optional[metadata_info.InputAudioTenso...
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
<|skeleton|> class MetadataWriter: """Writes metadata into an audio classifier.""" def create_from_metadata_info(cls, model_buffer: bytearray, general_md: Optional[metadata_info.GeneralMd]=None, input_md: Optional[metadata_info.InputAudioTensorMd]=None, output_md: Optional[metadata_info.ClassificationTensorMd]...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MetadataWriter: """Writes metadata into an audio classifier.""" def create_from_metadata_info(cls, model_buffer: bytearray, general_md: Optional[metadata_info.GeneralMd]=None, input_md: Optional[metadata_info.InputAudioTensorMd]=None, output_md: Optional[metadata_info.ClassificationTensorMd]=None): ...
the_stack_v2_python_sparse
third_party/tflite_support/src/tensorflow_lite_support/metadata/python/metadata_writers/audio_classifier.py
chromium/chromium
train
17,408
4bedaefdd7415cc2a3c58bef152103cd0331ac83
[ "super().__init__(name)\nself.fluid = OreList(fluid)\nself.material = OreList(material)", "result = {'distribution': 'underfluid', 'fluid': self.fluid.as_json()}\nif not self.material.is_empty:\n result['material'] = self.material.as_json()\nreturn result" ]
<|body_start_0|> super().__init__(name) self.fluid = OreList(fluid) self.material = OreList(material) <|end_body_0|> <|body_start_1|> result = {'distribution': 'underfluid', 'fluid': self.fluid.as_json()} if not self.material.is_empty: result['material'] = self.mater...
SubmergedDistribution places deposits immediately below a body of liquid..
SubmergedDistribution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SubmergedDistribution: """SubmergedDistribution places deposits immediately below a body of liquid..""" def __init__(self, name: str, fluid: OreListable, material: OreListable=None): """Create a new uniform distribution.""" <|body_0|> def as_json(self) -> Dict[str, Any]:...
stack_v2_sparse_classes_36k_train_003326
1,112
no_license
[ { "docstring": "Create a new uniform distribution.", "name": "__init__", "signature": "def __init__(self, name: str, fluid: OreListable, material: OreListable=None)" }, { "docstring": "Create a dict representation of this deposit suitable for being converted to JSON.", "name": "as_json", ...
2
stack_v2_sparse_classes_30k_train_019826
Implement the Python class `SubmergedDistribution` described below. Class description: SubmergedDistribution places deposits immediately below a body of liquid.. Method signatures and docstrings: - def __init__(self, name: str, fluid: OreListable, material: OreListable=None): Create a new uniform distribution. - def ...
Implement the Python class `SubmergedDistribution` described below. Class description: SubmergedDistribution places deposits immediately below a body of liquid.. Method signatures and docstrings: - def __init__(self, name: str, fluid: OreListable, material: OreListable=None): Create a new uniform distribution. - def ...
9bd6e74cb3817eec76119978ea31cf5b04e0ed51
<|skeleton|> class SubmergedDistribution: """SubmergedDistribution places deposits immediately below a body of liquid..""" def __init__(self, name: str, fluid: OreListable, material: OreListable=None): """Create a new uniform distribution.""" <|body_0|> def as_json(self) -> Dict[str, Any]:...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SubmergedDistribution: """SubmergedDistribution places deposits immediately below a body of liquid..""" def __init__(self, name: str, fluid: OreListable, material: OreListable=None): """Create a new uniform distribution.""" super().__init__(name) self.fluid = OreList(fluid) ...
the_stack_v2_python_sparse
src/packconfig/oregen/distributions/submerged_distribution.py
tungstonminer/packconfig
train
0
06225024d1b048c4e9a12171268627cc018534c7
[ "super().__init__(order=CallbackOrder.ExternalExtra, node=CallbackNode.master)\nself.qconfig_spec = qconfig_spec\nself.dtype = dtype\nif logdir is not None:\n self.filename = Path(logdir) / filename\nelse:\n self.filename = filename", "q_model = quantize_model(runner.model.cpu(), qconfig_spec=self.qconfig_s...
<|body_start_0|> super().__init__(order=CallbackOrder.ExternalExtra, node=CallbackNode.master) self.qconfig_spec = qconfig_spec self.dtype = dtype if logdir is not None: self.filename = Path(logdir) / filename else: self.filename = filename <|end_body_0|> ...
Callback for model quantiztion. Args: logdir: path to folder for saving filename: filename qconfig_spec (Dict, optional): quantization config in PyTorch format. Defaults to None. dtype (Union[str, Optional[torch.dtype]], optional): Type of weights after quantization. Defaults to "qint8". Example: .. code-block:: python...
QuantizationCallback
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class QuantizationCallback: """Callback for model quantiztion. Args: logdir: path to folder for saving filename: filename qconfig_spec (Dict, optional): quantization config in PyTorch format. Defaults to None. dtype (Union[str, Optional[torch.dtype]], optional): Type of weights after quantization. Defa...
stack_v2_sparse_classes_36k_train_003327
3,179
permissive
[ { "docstring": "Init.", "name": "__init__", "signature": "def __init__(self, logdir: Union[str, Path]=None, filename: str='quantized.pth', qconfig_spec: Dict=None, dtype: Union[str, Optional[torch.dtype]]='qint8')" }, { "docstring": "Event handler.", "name": "on_stage_end", "signature": ...
2
null
Implement the Python class `QuantizationCallback` described below. Class description: Callback for model quantiztion. Args: logdir: path to folder for saving filename: filename qconfig_spec (Dict, optional): quantization config in PyTorch format. Defaults to None. dtype (Union[str, Optional[torch.dtype]], optional): T...
Implement the Python class `QuantizationCallback` described below. Class description: Callback for model quantiztion. Args: logdir: path to folder for saving filename: filename qconfig_spec (Dict, optional): quantization config in PyTorch format. Defaults to None. dtype (Union[str, Optional[torch.dtype]], optional): T...
ac8567dc389fb7a265e3104e8a743497aa903165
<|skeleton|> class QuantizationCallback: """Callback for model quantiztion. Args: logdir: path to folder for saving filename: filename qconfig_spec (Dict, optional): quantization config in PyTorch format. Defaults to None. dtype (Union[str, Optional[torch.dtype]], optional): Type of weights after quantization. Defa...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class QuantizationCallback: """Callback for model quantiztion. Args: logdir: path to folder for saving filename: filename qconfig_spec (Dict, optional): quantization config in PyTorch format. Defaults to None. dtype (Union[str, Optional[torch.dtype]], optional): Type of weights after quantization. Defaults to "qint...
the_stack_v2_python_sparse
catalyst/callbacks/quantization.py
Podidiving/catalyst
train
2
ae4c923a26bf1f8cd1bd8039078c957125ca73ae
[ "self.duration = duration\nself.position_debt = (0.0, 0.0)\nself.bonus_type = bonus_type\nself.bonus = BonusSprite(bonus_type, (SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2))", "if self in GAME_DATA.elements.bonuses:\n GAME_DATA.elements.bonuses.remove(self)\nif self.bonus in GAME_DATA.sprites:\n GAME_DATA.sprites.r...
<|body_start_0|> self.duration = duration self.position_debt = (0.0, 0.0) self.bonus_type = bonus_type self.bonus = BonusSprite(bonus_type, (SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2)) <|end_body_0|> <|body_start_1|> if self in GAME_DATA.elements.bonuses: GAME_DATA.element...
Controls Bonus element
Bonus
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Bonus: """Controls Bonus element""" def __init__(self, bonus_type, duration=500): """:param bonus_type: bonus type(health - additional health, damage - increased damage, speed - increased tank speed, attack_speed - increased attack speed) :param duration: duration after which bonus w...
stack_v2_sparse_classes_36k_train_003328
21,421
no_license
[ { "docstring": ":param bonus_type: bonus type(health - additional health, damage - increased damage, speed - increased tank speed, attack_speed - increased attack speed) :param duration: duration after which bonus will be destroyed", "name": "__init__", "signature": "def __init__(self, bonus_type, durat...
3
stack_v2_sparse_classes_30k_val_001107
Implement the Python class `Bonus` described below. Class description: Controls Bonus element Method signatures and docstrings: - def __init__(self, bonus_type, duration=500): :param bonus_type: bonus type(health - additional health, damage - increased damage, speed - increased tank speed, attack_speed - increased at...
Implement the Python class `Bonus` described below. Class description: Controls Bonus element Method signatures and docstrings: - def __init__(self, bonus_type, duration=500): :param bonus_type: bonus type(health - additional health, damage - increased damage, speed - increased tank speed, attack_speed - increased at...
51a2f2ecc09a05672a2c3deb00ab8c273d3b756b
<|skeleton|> class Bonus: """Controls Bonus element""" def __init__(self, bonus_type, duration=500): """:param bonus_type: bonus type(health - additional health, damage - increased damage, speed - increased tank speed, attack_speed - increased attack speed) :param duration: duration after which bonus w...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Bonus: """Controls Bonus element""" def __init__(self, bonus_type, duration=500): """:param bonus_type: bonus type(health - additional health, damage - increased damage, speed - increased tank speed, attack_speed - increased attack speed) :param duration: duration after which bonus will be destro...
the_stack_v2_python_sparse
game_core/game_data.py
asmodeii/tanki
train
0
3144b761a32807fb4adbc98844c7a14134b3a46d
[ "crc8_byte = 255\nfor ind_char in msg_chars:\n ind_int = ind_char\n crc8_byte = OppRs232Intf.CRC8_LOOKUP[crc8_byte ^ ind_int]\nreturn bytes([crc8_byte])", "crc8_byte = 255\nindex = 0\nif len(msg_chars) < start_index + num_chars:\n raise AssertionError('String too short for {} chars of CRC: {}'.format(num...
<|body_start_0|> crc8_byte = 255 for ind_char in msg_chars: ind_int = ind_char crc8_byte = OppRs232Intf.CRC8_LOOKUP[crc8_byte ^ ind_int] return bytes([crc8_byte]) <|end_body_0|> <|body_start_1|> crc8_byte = 255 index = 0 if len(msg_chars) < start_...
Constants for OPP serial protocol.
OppRs232Intf
[ "MIT", "CC-BY-4.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OppRs232Intf: """Constants for OPP serial protocol.""" def calc_crc8_whole_msg(msg_chars): """Calculate CRC for message.""" <|body_0|> def calc_crc8_part_msg(msg_chars, start_index, num_chars): """Calculate CRC for part of a message.""" <|body_1|> <|end_...
stack_v2_sparse_classes_36k_train_003329
5,002
permissive
[ { "docstring": "Calculate CRC for message.", "name": "calc_crc8_whole_msg", "signature": "def calc_crc8_whole_msg(msg_chars)" }, { "docstring": "Calculate CRC for part of a message.", "name": "calc_crc8_part_msg", "signature": "def calc_crc8_part_msg(msg_chars, start_index, num_chars)" ...
2
null
Implement the Python class `OppRs232Intf` described below. Class description: Constants for OPP serial protocol. Method signatures and docstrings: - def calc_crc8_whole_msg(msg_chars): Calculate CRC for message. - def calc_crc8_part_msg(msg_chars, start_index, num_chars): Calculate CRC for part of a message.
Implement the Python class `OppRs232Intf` described below. Class description: Constants for OPP serial protocol. Method signatures and docstrings: - def calc_crc8_whole_msg(msg_chars): Calculate CRC for message. - def calc_crc8_part_msg(msg_chars, start_index, num_chars): Calculate CRC for part of a message. <|skele...
9f90c8b1586363b65340017bfa3af5d56d32c6d9
<|skeleton|> class OppRs232Intf: """Constants for OPP serial protocol.""" def calc_crc8_whole_msg(msg_chars): """Calculate CRC for message.""" <|body_0|> def calc_crc8_part_msg(msg_chars, start_index, num_chars): """Calculate CRC for part of a message.""" <|body_1|> <|end_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OppRs232Intf: """Constants for OPP serial protocol.""" def calc_crc8_whole_msg(msg_chars): """Calculate CRC for message.""" crc8_byte = 255 for ind_char in msg_chars: ind_int = ind_char crc8_byte = OppRs232Intf.CRC8_LOOKUP[crc8_byte ^ ind_int] retur...
the_stack_v2_python_sparse
mpf/platforms/opp/opp_rs232_intf.py
missionpinball/mpf
train
191
0530e9112702a0b71ec68f72aa4ac7d4fb39baa0
[ "super().__init__()\nself.query_emb = nn.Linear(in_channels, out_channels)\nself.key_emb = nn.Linear(in_channels, out_channels)\nself.val_emb = nn.Linear(in_channels, out_channels)\nself.att = nn.MultiheadAttention(out_channels, 1)", "queries = self.query_emb(node_encodings.permute(1, 0, 2))\nkeys = self.key_emb(...
<|body_start_0|> super().__init__() self.query_emb = nn.Linear(in_channels, out_channels) self.key_emb = nn.Linear(in_channels, out_channels) self.val_emb = nn.Linear(in_channels, out_channels) self.att = nn.MultiheadAttention(out_channels, 1) <|end_body_0|> <|body_start_1|> ...
GAT layer for aggregating local context at each lane node. Uses scaled dot product attention using pytorch's multihead attention module.
GAT
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GAT: """GAT layer for aggregating local context at each lane node. Uses scaled dot product attention using pytorch's multihead attention module.""" def __init__(self, in_channels, out_channels): """Initialize GAT layer. :param in_channels: size of node encodings :param out_channels: ...
stack_v2_sparse_classes_36k_train_003330
27,074
permissive
[ { "docstring": "Initialize GAT layer. :param in_channels: size of node encodings :param out_channels: size of aggregated node encodings", "name": "__init__", "signature": "def __init__(self, in_channels, out_channels)" }, { "docstring": "Forward pass for GAT layer :param node_encodings: Tensor o...
2
stack_v2_sparse_classes_30k_train_020127
Implement the Python class `GAT` described below. Class description: GAT layer for aggregating local context at each lane node. Uses scaled dot product attention using pytorch's multihead attention module. Method signatures and docstrings: - def __init__(self, in_channels, out_channels): Initialize GAT layer. :param ...
Implement the Python class `GAT` described below. Class description: GAT layer for aggregating local context at each lane node. Uses scaled dot product attention using pytorch's multihead attention module. Method signatures and docstrings: - def __init__(self, in_channels, out_channels): Initialize GAT layer. :param ...
6419894aa040adb9570b14493952a98c0a52f803
<|skeleton|> class GAT: """GAT layer for aggregating local context at each lane node. Uses scaled dot product attention using pytorch's multihead attention module.""" def __init__(self, in_channels, out_channels): """Initialize GAT layer. :param in_channels: size of node encodings :param out_channels: ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GAT: """GAT layer for aggregating local context at each lane node. Uses scaled dot product attention using pytorch's multihead attention module.""" def __init__(self, in_channels, out_channels): """Initialize GAT layer. :param in_channels: size of node encodings :param out_channels: size of aggre...
the_stack_v2_python_sparse
models/encoders/pgp_scout_encoder.py
sancarlim/Explainable-MP
train
17
1fd6b82c3bd7a971cc0680e2909ccfd8db83e644
[ "self._repositories = []\nself.__kinds = set()\nself._controller = False", "kind = svc_ref.get_property(cohorte.repositories.PROP_FACTORY_MODEL)\nself.__kinds.add(kind)\nself._controller = REQUIRED_REPOSITORIES.issubset(self.__kinds)", "kind = svc_ref.get_property(cohorte.repositories.PROP_FACTORY_MODEL)\ntry:\...
<|body_start_0|> self._repositories = [] self.__kinds = set() self._controller = False <|end_body_0|> <|body_start_1|> kind = svc_ref.get_property(cohorte.repositories.PROP_FACTORY_MODEL) self.__kinds.add(kind) self._controller = REQUIRED_REPOSITORIES.issubset(self.__kin...
Looks for the source bundle of components
ComponentFinder
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ComponentFinder: """Looks for the source bundle of components""" def __init__(self): """Sets up members""" <|body_0|> def _bind_repository(self, field, svc, svc_ref): """A repository has been bound. Starts the timer to provide the service when most of repositorie...
stack_v2_sparse_classes_36k_train_003331
4,627
permissive
[ { "docstring": "Sets up members", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "A repository has been bound. Starts the timer to provide the service when most of repositories have been bound.", "name": "_bind_repository", "signature": "def _bind_repository(self...
4
stack_v2_sparse_classes_30k_train_007413
Implement the Python class `ComponentFinder` described below. Class description: Looks for the source bundle of components Method signatures and docstrings: - def __init__(self): Sets up members - def _bind_repository(self, field, svc, svc_ref): A repository has been bound. Starts the timer to provide the service whe...
Implement the Python class `ComponentFinder` described below. Class description: Looks for the source bundle of components Method signatures and docstrings: - def __init__(self): Sets up members - def _bind_repository(self, field, svc, svc_ref): A repository has been bound. Starts the timer to provide the service whe...
686556cdde20beba77ae202de9969be46feed5e2
<|skeleton|> class ComponentFinder: """Looks for the source bundle of components""" def __init__(self): """Sets up members""" <|body_0|> def _bind_repository(self, field, svc, svc_ref): """A repository has been bound. Starts the timer to provide the service when most of repositorie...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ComponentFinder: """Looks for the source bundle of components""" def __init__(self): """Sets up members""" self._repositories = [] self.__kinds = set() self._controller = False def _bind_repository(self, field, svc, svc_ref): """A repository has been bound. St...
the_stack_v2_python_sparse
python/cohorte/composer/node/finder.py
cohorte/cohorte-runtime
train
3
ee64b80eb4f754529bbd8908a3fc6e62e69b05e9
[ "table_parameters = self._get_table_parameters(database_name, table_name)\nlogger.info(f'Table parameters: {table_parameters}')\nvalidate_schema, validate_latest = self._parse_table_parameters(table_parameters)\nif validate_schema:\n table_schema = sorted(self._get_table_schema(database_name, table_name), key=la...
<|body_start_0|> table_parameters = self._get_table_parameters(database_name, table_name) logger.info(f'Table parameters: {table_parameters}') validate_schema, validate_latest = self._parse_table_parameters(table_parameters) if validate_schema: table_schema = sorted(self._get...
ParquetSchemaValidator
[ "MIT-0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ParquetSchemaValidator: def validate(self, prefix, keys, database_name, table_name): """Validates the Parquet S3 object(s) against the Glue schema Args: prefix: S3 prefix keys: list of S3 keys database_name: Glue database name table_name: Glue table name Returns: validation result: True ...
stack_v2_sparse_classes_36k_train_003332
5,404
permissive
[ { "docstring": "Validates the Parquet S3 object(s) against the Glue schema Args: prefix: S3 prefix keys: list of S3 keys database_name: Glue database name table_name: Glue table name Returns: validation result: True or False", "name": "validate", "signature": "def validate(self, prefix, keys, database_n...
3
stack_v2_sparse_classes_30k_train_011553
Implement the Python class `ParquetSchemaValidator` described below. Class description: Implement the ParquetSchemaValidator class. Method signatures and docstrings: - def validate(self, prefix, keys, database_name, table_name): Validates the Parquet S3 object(s) against the Glue schema Args: prefix: S3 prefix keys: ...
Implement the Python class `ParquetSchemaValidator` described below. Class description: Implement the ParquetSchemaValidator class. Method signatures and docstrings: - def validate(self, prefix, keys, database_name, table_name): Validates the Parquet S3 object(s) against the Glue schema Args: prefix: S3 prefix keys: ...
f75307daf35fd7914a839ec00ca002db1b6148f4
<|skeleton|> class ParquetSchemaValidator: def validate(self, prefix, keys, database_name, table_name): """Validates the Parquet S3 object(s) against the Glue schema Args: prefix: S3 prefix keys: list of S3 keys database_name: Glue database name table_name: Glue table name Returns: validation result: True ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ParquetSchemaValidator: def validate(self, prefix, keys, database_name, table_name): """Validates the Parquet S3 object(s) against the Glue schema Args: prefix: S3 prefix keys: list of S3 keys database_name: Glue database name table_name: Glue table name Returns: validation result: True or False""" ...
the_stack_v2_python_sparse
sdlf-datalakeLibrary/python/datalake_library/data_quality/schema_validator.py
awslabs/aws-serverless-data-lake-framework
train
357
bc6136c8d3d0334ffae535b8adb6cbcf6b89ea1d
[ "uglys = [1]\nugly2 = ugly3 = ugly5 = 0\nwhile len(uglys) < n:\n ugnext2, ugnext3, ugnext5 = (uglys[ugly2] * 2, uglys[ugly3] * 3, uglys[ugly5] * 5)\n if ugnext2 <= ugnext3 and ugnext2 <= ugnext5:\n ugly2 += 1\n if ugnext2 not in uglys:\n uglys.append(ugnext2)\n continue\n if...
<|body_start_0|> uglys = [1] ugly2 = ugly3 = ugly5 = 0 while len(uglys) < n: ugnext2, ugnext3, ugnext5 = (uglys[ugly2] * 2, uglys[ugly3] * 3, uglys[ugly5] * 5) if ugnext2 <= ugnext3 and ugnext2 <= ugnext5: ugly2 += 1 if ugnext2 not in uglys...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def nthUglyNumber(self, n): """:type n: int :rtype: int""" <|body_0|> def nthUglyNumber2(self, n): """:type n: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> uglys = [1] ugly2 = ugly3 = ugly5 = 0 while len(...
stack_v2_sparse_classes_36k_train_003333
1,534
no_license
[ { "docstring": ":type n: int :rtype: int", "name": "nthUglyNumber", "signature": "def nthUglyNumber(self, n)" }, { "docstring": ":type n: int :rtype: int", "name": "nthUglyNumber2", "signature": "def nthUglyNumber2(self, n)" } ]
2
stack_v2_sparse_classes_30k_train_021467
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def nthUglyNumber(self, n): :type n: int :rtype: int - def nthUglyNumber2(self, n): :type n: int :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def nthUglyNumber(self, n): :type n: int :rtype: int - def nthUglyNumber2(self, n): :type n: int :rtype: int <|skeleton|> class Solution: def nthUglyNumber(self, n): ...
0fc4c7af59246e3064db41989a45d9db413a624b
<|skeleton|> class Solution: def nthUglyNumber(self, n): """:type n: int :rtype: int""" <|body_0|> def nthUglyNumber2(self, n): """:type n: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def nthUglyNumber(self, n): """:type n: int :rtype: int""" uglys = [1] ugly2 = ugly3 = ugly5 = 0 while len(uglys) < n: ugnext2, ugnext3, ugnext5 = (uglys[ugly2] * 2, uglys[ugly3] * 3, uglys[ugly5] * 5) if ugnext2 <= ugnext3 and ugnext2 <= ugnex...
the_stack_v2_python_sparse
264. Ugly Number II/ugly2.py
Macielyoung/LeetCode
train
1
2d861eb7d326567410d45389136f83232d8218c0
[ "dict = self.findAllPosible(N)\nallArrange = []\nself.findArrange(N, [], allArrange, dict)\nreturn len(allArrange)", "dict = {}\nfor i in xrange(1, N + 1):\n dict[i] = reduce(list.__add__, ([j] for j in xrange(1, N + 1) if i % j == 0 or j % i == 0))\nreturn dict", "if N == len(arrange):\n resSet.append(ar...
<|body_start_0|> dict = self.findAllPosible(N) allArrange = [] self.findArrange(N, [], allArrange, dict) return len(allArrange) <|end_body_0|> <|body_start_1|> dict = {} for i in xrange(1, N + 1): dict[i] = reduce(list.__add__, ([j] for j in xrange(1, N + 1) ...
Solution_2
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution_2: def countArrangement(self, N): """:type N: int :rtype: int""" <|body_0|> def findAllPosible(self, N): """:type N:int :rtype: dictionary""" <|body_1|> def findArrange(self, N, arrange, resSet, dict): """:N: type (int) :arrange: type li...
stack_v2_sparse_classes_36k_train_003334
3,226
no_license
[ { "docstring": ":type N: int :rtype: int", "name": "countArrangement", "signature": "def countArrangement(self, N)" }, { "docstring": ":type N:int :rtype: dictionary", "name": "findAllPosible", "signature": "def findAllPosible(self, N)" }, { "docstring": ":N: type (int) :arrange:...
3
stack_v2_sparse_classes_30k_train_009889
Implement the Python class `Solution_2` described below. Class description: Implement the Solution_2 class. Method signatures and docstrings: - def countArrangement(self, N): :type N: int :rtype: int - def findAllPosible(self, N): :type N:int :rtype: dictionary - def findArrange(self, N, arrange, resSet, dict): :N: t...
Implement the Python class `Solution_2` described below. Class description: Implement the Solution_2 class. Method signatures and docstrings: - def countArrangement(self, N): :type N: int :rtype: int - def findAllPosible(self, N): :type N:int :rtype: dictionary - def findArrange(self, N, arrange, resSet, dict): :N: t...
d2cbfb1022b1ee5bce8083c9940ba10320fc2d43
<|skeleton|> class Solution_2: def countArrangement(self, N): """:type N: int :rtype: int""" <|body_0|> def findAllPosible(self, N): """:type N:int :rtype: dictionary""" <|body_1|> def findArrange(self, N, arrange, resSet, dict): """:N: type (int) :arrange: type li...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution_2: def countArrangement(self, N): """:type N: int :rtype: int""" dict = self.findAllPosible(N) allArrange = [] self.findArrange(N, [], allArrange, dict) return len(allArrange) def findAllPosible(self, N): """:type N:int :rtype: dictionary""" ...
the_stack_v2_python_sparse
526_Beautiful_Arrangement/526_Beautiful_Arrangement.py
VividLiu/LeeCode_Practice
train
1
9d86a88b183b76581ce68664baa169d317ab1fa9
[ "if len(args) == 1:\n self.total = args[0].total\n self.percluster = args[0].percluster\n self.rest_term = args[0].rest_term\nelse:\n self.calc_ELBO_Opti(args)", "if len(args[0]) < 5:\n maskedData, suffStat, vbParam, param = args[0]\n nfeature, Khat, nchannel = vbParam.muhat.shape\n P = nfeat...
<|body_start_0|> if len(args) == 1: self.total = args[0].total self.percluster = args[0].percluster self.rest_term = args[0].rest_term else: self.calc_ELBO_Opti(args) <|end_body_0|> <|body_start_1|> if len(args[0]) < 5: maskedData, suf...
Class for calculating the ELBO for VB inference Attributes: ----------- percluster: np.array K x 1 numpy array containing part of ELBO value that depends on each cluster. Can be used to calculate value for only a given cluster rest_term: float Part of ELBO value that has to be calculated regardless of cluster total: fl...
ELBO_Class
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ELBO_Class: """Class for calculating the ELBO for VB inference Attributes: ----------- percluster: np.array K x 1 numpy array containing part of ELBO value that depends on each cluster. Can be used to calculate value for only a given cluster rest_term: float Part of ELBO value that has to be calc...
stack_v2_sparse_classes_36k_train_003335
45,319
permissive
[ { "docstring": "Initializes attributes. Calls cal_ELBO_opti() Parameters: ----------- maskedData: maskData object suffStat: suffStatistics object vbParam: vbPar object param: Config object (see Config.py) K_ind (optional): list Cluster indices for which the partial ELBO is being calculated. Defaults to all clus...
2
null
Implement the Python class `ELBO_Class` described below. Class description: Class for calculating the ELBO for VB inference Attributes: ----------- percluster: np.array K x 1 numpy array containing part of ELBO value that depends on each cluster. Can be used to calculate value for only a given cluster rest_term: float...
Implement the Python class `ELBO_Class` described below. Class description: Class for calculating the ELBO for VB inference Attributes: ----------- percluster: np.array K x 1 numpy array containing part of ELBO value that depends on each cluster. Can be used to calculate value for only a given cluster rest_term: float...
b18d13a69946c1fee28fbc1f67215d3a89d892af
<|skeleton|> class ELBO_Class: """Class for calculating the ELBO for VB inference Attributes: ----------- percluster: np.array K x 1 numpy array containing part of ELBO value that depends on each cluster. Can be used to calculate value for only a given cluster rest_term: float Part of ELBO value that has to be calc...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ELBO_Class: """Class for calculating the ELBO for VB inference Attributes: ----------- percluster: np.array K x 1 numpy array containing part of ELBO value that depends on each cluster. Can be used to calculate value for only a given cluster rest_term: float Part of ELBO value that has to be calculated regard...
the_stack_v2_python_sparse
src/yass/mfm.py
paninski-lab/yass
train
68
46cbd726862a2c1d26e2813f68439fa48c908e69
[ "instance = TriggerInstance(action, trigger_info, self)\nself.trigger_instances.append(instance)\nif self.topic is not None:\n await instance.async_attach_trigger()\n\n@callback\ndef async_remove() -> None:\n \"\"\"Remove trigger.\"\"\"\n if instance not in self.trigger_instances:\n raise HomeAssist...
<|body_start_0|> instance = TriggerInstance(action, trigger_info, self) self.trigger_instances.append(instance) if self.topic is not None: await instance.async_attach_trigger() @callback def async_remove() -> None: """Remove trigger.""" if ins...
Device trigger settings.
Trigger
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Trigger: """Device trigger settings.""" async def add_trigger(self, action: TriggerActionType, trigger_info: TriggerInfo) -> Callable[[], None]: """Add MQTT trigger.""" <|body_0|> async def update_trigger(self, config: ConfigType) -> None: """Update MQTT device t...
stack_v2_sparse_classes_36k_train_003336
11,475
permissive
[ { "docstring": "Add MQTT trigger.", "name": "add_trigger", "signature": "async def add_trigger(self, action: TriggerActionType, trigger_info: TriggerInfo) -> Callable[[], None]" }, { "docstring": "Update MQTT device trigger.", "name": "update_trigger", "signature": "async def update_trig...
3
null
Implement the Python class `Trigger` described below. Class description: Device trigger settings. Method signatures and docstrings: - async def add_trigger(self, action: TriggerActionType, trigger_info: TriggerInfo) -> Callable[[], None]: Add MQTT trigger. - async def update_trigger(self, config: ConfigType) -> None:...
Implement the Python class `Trigger` described below. Class description: Device trigger settings. Method signatures and docstrings: - async def add_trigger(self, action: TriggerActionType, trigger_info: TriggerInfo) -> Callable[[], None]: Add MQTT trigger. - async def update_trigger(self, config: ConfigType) -> None:...
80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743
<|skeleton|> class Trigger: """Device trigger settings.""" async def add_trigger(self, action: TriggerActionType, trigger_info: TriggerInfo) -> Callable[[], None]: """Add MQTT trigger.""" <|body_0|> async def update_trigger(self, config: ConfigType) -> None: """Update MQTT device t...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Trigger: """Device trigger settings.""" async def add_trigger(self, action: TriggerActionType, trigger_info: TriggerInfo) -> Callable[[], None]: """Add MQTT trigger.""" instance = TriggerInstance(action, trigger_info, self) self.trigger_instances.append(instance) if self.t...
the_stack_v2_python_sparse
homeassistant/components/mqtt/device_trigger.py
home-assistant/core
train
35,501
f03a710f13bc9958348156d49e4af302f43d947f
[ "self.f = False\n\ndef help(nums, i, subsum, t):\n if t == subsum:\n self.f = True\n return\n if i < len(nums) and (not self.f):\n help(nums, i + 1, subsum + nums[i], t)\n help(nums, i + 1, subsum, t)\ns = sum(nums)\nif s % 2 == 1:\n return self.f\nelse:\n help(nums, 0, 0, s ...
<|body_start_0|> self.f = False def help(nums, i, subsum, t): if t == subsum: self.f = True return if i < len(nums) and (not self.f): help(nums, i + 1, subsum + nums[i], t) help(nums, i + 1, subsum, t) s = s...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def canPartition1(self, nums): """:type nums: List[int] :rtype: bool""" <|body_0|> def canPartition(self, nums): """:type nums: List[int] :rtype: bool""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.f = False def help(nums, i...
stack_v2_sparse_classes_36k_train_003337
1,237
no_license
[ { "docstring": ":type nums: List[int] :rtype: bool", "name": "canPartition1", "signature": "def canPartition1(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: bool", "name": "canPartition", "signature": "def canPartition(self, nums)" } ]
2
stack_v2_sparse_classes_30k_train_016301
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def canPartition1(self, nums): :type nums: List[int] :rtype: bool - def canPartition(self, nums): :type nums: List[int] :rtype: bool
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def canPartition1(self, nums): :type nums: List[int] :rtype: bool - def canPartition(self, nums): :type nums: List[int] :rtype: bool <|skeleton|> class Solution: def canPar...
e5b018493bbd12edcdcd0434f35d9c358106d391
<|skeleton|> class Solution: def canPartition1(self, nums): """:type nums: List[int] :rtype: bool""" <|body_0|> def canPartition(self, nums): """:type nums: List[int] :rtype: bool""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def canPartition1(self, nums): """:type nums: List[int] :rtype: bool""" self.f = False def help(nums, i, subsum, t): if t == subsum: self.f = True return if i < len(nums) and (not self.f): help(nums, i +...
the_stack_v2_python_sparse
py/leetcode/416.py
wfeng1991/learnpy
train
0
ecc92716dfd0d6e6a7f65199741a6378aa6c24a9
[ "losses = []\nfor obs in batch_handler.val_data:\n gen = self._tf_generate(obs.low_res)\n loss, _ = self.calc_loss(obs.high_res, gen, weight_gen_advers=weight_gen_advers, train_gen=True, train_disc=True)\n losses.append(float(loss))\nreturn losses", "losses = []\nfor obs in batch_handler.val_data:\n g...
<|body_start_0|> losses = [] for obs in batch_handler.val_data: gen = self._tf_generate(obs.low_res) loss, _ = self.calc_loss(obs.high_res, gen, weight_gen_advers=weight_gen_advers, train_gen=True, train_disc=True) losses.append(float(loss)) return losses <|en...
Data-centric model using loss across time bins to select training observations
Sup3rGanDC
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Sup3rGanDC: """Data-centric model using loss across time bins to select training observations""" def calc_val_loss_gen(self, batch_handler, weight_gen_advers): """Calculate the validation total loss across the validation samples. e.g. If the sample domain has 100 steps and the valida...
stack_v2_sparse_classes_36k_train_003338
11,269
permissive
[ { "docstring": "Calculate the validation total loss across the validation samples. e.g. If the sample domain has 100 steps and the validation set has 10 bins then this will get a list of losses across step 0 to 10, 10 to 20, etc. Use this to determine performance within bins and to update how observations are s...
4
stack_v2_sparse_classes_30k_train_002546
Implement the Python class `Sup3rGanDC` described below. Class description: Data-centric model using loss across time bins to select training observations Method signatures and docstrings: - def calc_val_loss_gen(self, batch_handler, weight_gen_advers): Calculate the validation total loss across the validation sample...
Implement the Python class `Sup3rGanDC` described below. Class description: Data-centric model using loss across time bins to select training observations Method signatures and docstrings: - def calc_val_loss_gen(self, batch_handler, weight_gen_advers): Calculate the validation total loss across the validation sample...
f3803a823c7bb0afd7ab6064625908dca0be3476
<|skeleton|> class Sup3rGanDC: """Data-centric model using loss across time bins to select training observations""" def calc_val_loss_gen(self, batch_handler, weight_gen_advers): """Calculate the validation total loss across the validation samples. e.g. If the sample domain has 100 steps and the valida...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Sup3rGanDC: """Data-centric model using loss across time bins to select training observations""" def calc_val_loss_gen(self, batch_handler, weight_gen_advers): """Calculate the validation total loss across the validation samples. e.g. If the sample domain has 100 steps and the validation set has ...
the_stack_v2_python_sparse
sup3r/models/data_centric.py
NREL/sup3r
train
20
0484230a889cb8bc673e56ff8162f2fbf5ba242b
[ "n = len(nums)\nleft, right = ([0] * (n + 1), [0] * (n + 1))\nfor i in range(1, n + 1):\n left[i] = left[i - 1] + nums[i - 1]\nfor i in range(n - 1, -1, -1):\n right[i] = right[i + 1] + nums[i]\nres = [0] * n\nfor i in range(n):\n res[i] = nums[i] * (2 * i - n + 1) - left[i] + right[i + 1]\nreturn res", ...
<|body_start_0|> n = len(nums) left, right = ([0] * (n + 1), [0] * (n + 1)) for i in range(1, n + 1): left[i] = left[i - 1] + nums[i - 1] for i in range(n - 1, -1, -1): right[i] = right[i + 1] + nums[i] res = [0] * n for i in range(n): ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def getSumAbsoluteDifferences(self, nums): """:type nums: List[int] :rtype: List[int]""" <|body_0|> def getSumAbsoluteDifferencesLessSpace(self, nums): """:type nums: List[int] :rtype: List[int]""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_36k_train_003339
1,971
no_license
[ { "docstring": ":type nums: List[int] :rtype: List[int]", "name": "getSumAbsoluteDifferences", "signature": "def getSumAbsoluteDifferences(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: List[int]", "name": "getSumAbsoluteDifferencesLessSpace", "signature": "def getSumAbsol...
2
stack_v2_sparse_classes_30k_train_015878
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def getSumAbsoluteDifferences(self, nums): :type nums: List[int] :rtype: List[int] - def getSumAbsoluteDifferencesLessSpace(self, nums): :type nums: List[int] :rtype: List[int]
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def getSumAbsoluteDifferences(self, nums): :type nums: List[int] :rtype: List[int] - def getSumAbsoluteDifferencesLessSpace(self, nums): :type nums: List[int] :rtype: List[int] ...
810575368ecffa97677bdb51744d1f716140bbb1
<|skeleton|> class Solution: def getSumAbsoluteDifferences(self, nums): """:type nums: List[int] :rtype: List[int]""" <|body_0|> def getSumAbsoluteDifferencesLessSpace(self, nums): """:type nums: List[int] :rtype: List[int]""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def getSumAbsoluteDifferences(self, nums): """:type nums: List[int] :rtype: List[int]""" n = len(nums) left, right = ([0] * (n + 1), [0] * (n + 1)) for i in range(1, n + 1): left[i] = left[i - 1] + nums[i - 1] for i in range(n - 1, -1, -1): ...
the_stack_v2_python_sparse
S/SumofAbsoluteDifferencesinaSortedArray.py
bssrdf/pyleet
train
2
3964a5e0662386fa82323828a6a0d3cb790afc89
[ "try:\n SKU.objects.get(id=value)\nexcept SKU.DoesNotExist:\n raise serializers.ValidationError('该商品不存在')", "user_id = self.user.id\nsku_id = validated_data['sku_id']\nredis_conn = get_redis_connection('history')\npl = redis_conn.pipeline()\npl.lrem('history_%s' % user_id, 0, sku_id)\npl.lpush('history_%s' ...
<|body_start_0|> try: SKU.objects.get(id=value) except SKU.DoesNotExist: raise serializers.ValidationError('该商品不存在') <|end_body_0|> <|body_start_1|> user_id = self.user.id sku_id = validated_data['sku_id'] redis_conn = get_redis_connection('history') ...
添加用户浏览历史序列化器
AddBrowseHistorySerializer
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AddBrowseHistorySerializer: """添加用户浏览历史序列化器""" def validate_sku_id(self, value): """检验sku_id是否存在""" <|body_0|> def create(self, validated_data): """保存""" <|body_1|> <|end_skeleton|> <|body_start_0|> try: SKU.objects.get(id=value) ...
stack_v2_sparse_classes_36k_train_003340
6,086
permissive
[ { "docstring": "检验sku_id是否存在", "name": "validate_sku_id", "signature": "def validate_sku_id(self, value)" }, { "docstring": "保存", "name": "create", "signature": "def create(self, validated_data)" } ]
2
null
Implement the Python class `AddBrowseHistorySerializer` described below. Class description: 添加用户浏览历史序列化器 Method signatures and docstrings: - def validate_sku_id(self, value): 检验sku_id是否存在 - def create(self, validated_data): 保存
Implement the Python class `AddBrowseHistorySerializer` described below. Class description: 添加用户浏览历史序列化器 Method signatures and docstrings: - def validate_sku_id(self, value): 检验sku_id是否存在 - def create(self, validated_data): 保存 <|skeleton|> class AddBrowseHistorySerializer: """添加用户浏览历史序列化器""" def validate_sk...
5fc4d9930b0cd1e115f8c6ebf51cd9e28922d263
<|skeleton|> class AddBrowseHistorySerializer: """添加用户浏览历史序列化器""" def validate_sku_id(self, value): """检验sku_id是否存在""" <|body_0|> def create(self, validated_data): """保存""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AddBrowseHistorySerializer: """添加用户浏览历史序列化器""" def validate_sku_id(self, value): """检验sku_id是否存在""" try: SKU.objects.get(id=value) except SKU.DoesNotExist: raise serializers.ValidationError('该商品不存在') def create(self, validated_data): """保存""" ...
the_stack_v2_python_sparse
meiduo/meiduo_mall/meiduo_mall/apps/users/serializers.py
Highsir/Simplestore
train
1
c18d24e960ec4aab1974d6d14db3b08e5e0eb2fc
[ "self.sc = sc\nself.gradient = gradient\nif not f_diff:\n f_diff = np.ones(self.sc.shape[0]) * 0.05\nif isinstance(self.sc, list):\n if not isinstance(gradient, list):\n self.gradient = [self.gradient, self.gradient]\n self.hopf = [HopfModel(self.sc[ii], *args, f_diff=f_diff, hmap=self.gradient[ii],...
<|body_start_0|> self.sc = sc self.gradient = gradient if not f_diff: f_diff = np.ones(self.sc.shape[0]) * 0.05 if isinstance(self.sc, list): if not isinstance(gradient, list): self.gradient = [self.gradient, self.gradient] self.hopf = ...
Wrapper class for Hopf model.
Hopf
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Hopf: """Wrapper class for Hopf model.""" def __init__(self, sc, f_diff=None, gradient=None, *args, **kwargs): """Parameters ---------- sc : ndarray Structural connectivity matrix gradient : ndarray, optional Heterogeneity map to scale local model parameters. If None, the model param...
stack_v2_sparse_classes_36k_train_003341
3,717
no_license
[ { "docstring": "Parameters ---------- sc : ndarray Structural connectivity matrix gradient : ndarray, optional Heterogeneity map to scale local model parameters. If None, the model parameters are homogeneous (None by default) Notes ----- The optional arguments and keyword arguments pass to the Model class. If t...
5
stack_v2_sparse_classes_30k_train_005357
Implement the Python class `Hopf` described below. Class description: Wrapper class for Hopf model. Method signatures and docstrings: - def __init__(self, sc, f_diff=None, gradient=None, *args, **kwargs): Parameters ---------- sc : ndarray Structural connectivity matrix gradient : ndarray, optional Heterogeneity map ...
Implement the Python class `Hopf` described below. Class description: Wrapper class for Hopf model. Method signatures and docstrings: - def __init__(self, sc, f_diff=None, gradient=None, *args, **kwargs): Parameters ---------- sc : ndarray Structural connectivity matrix gradient : ndarray, optional Heterogeneity map ...
7aa2d0296673cf4a3df96fb01cc34712671b109c
<|skeleton|> class Hopf: """Wrapper class for Hopf model.""" def __init__(self, sc, f_diff=None, gradient=None, *args, **kwargs): """Parameters ---------- sc : ndarray Structural connectivity matrix gradient : ndarray, optional Heterogeneity map to scale local model parameters. If None, the model param...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Hopf: """Wrapper class for Hopf model.""" def __init__(self, sc, f_diff=None, gradient=None, *args, **kwargs): """Parameters ---------- sc : ndarray Structural connectivity matrix gradient : ndarray, optional Heterogeneity map to scale local model parameters. If None, the model parameters are hom...
the_stack_v2_python_sparse
lib/models/hopf/model_wrapper.py
murat-demirtas/pylib
train
2
5ccb1ac73ec869651e61f594597a1aab1b33c9bc
[ "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')", "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')", "conte...
<|body_start_0|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') <|end_body_0|> <|body_start_1|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not im...
Missing associated documentation comment in .proto file.
RealmAppServiceServicer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RealmAppServiceServicer: """Missing associated documentation comment in .proto file.""" def realm_by_name(self, request, context): """Missing associated documentation comment in .proto file.""" <|body_0|> def realm_by_id(self, request, context): """Missing associ...
stack_v2_sparse_classes_36k_train_003342
9,951
no_license
[ { "docstring": "Missing associated documentation comment in .proto file.", "name": "realm_by_name", "signature": "def realm_by_name(self, request, context)" }, { "docstring": "Missing associated documentation comment in .proto file.", "name": "realm_by_id", "signature": "def realm_by_id(...
5
null
Implement the Python class `RealmAppServiceServicer` described below. Class description: Missing associated documentation comment in .proto file. Method signatures and docstrings: - def realm_by_name(self, request, context): Missing associated documentation comment in .proto file. - def realm_by_id(self, request, con...
Implement the Python class `RealmAppServiceServicer` described below. Class description: Missing associated documentation comment in .proto file. Method signatures and docstrings: - def realm_by_name(self, request, context): Missing associated documentation comment in .proto file. - def realm_by_id(self, request, con...
55d36c068e26e13ee5bae5c033e2e17784c63feb
<|skeleton|> class RealmAppServiceServicer: """Missing associated documentation comment in .proto file.""" def realm_by_name(self, request, context): """Missing associated documentation comment in .proto file.""" <|body_0|> def realm_by_id(self, request, context): """Missing associ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RealmAppServiceServicer: """Missing associated documentation comment in .proto file.""" def realm_by_name(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not impleme...
the_stack_v2_python_sparse
src/resource/proto/_generated/identity/realm_app_service_pb2_grpc.py
arkanmgerges/cafm.identity
train
0
815bd8400c5db4e60ff32008a35019a14a7683b2
[ "super(MudderyProfitRoom, self).__init__()\nself.scheduler = AsyncIOScheduler(timezone=pytz.utc)\nself.last_trigger_time = {}\nself.loot_handler = None", "await super(MudderyProfitRoom, self).at_element_setup(first_time)\nself.loot_handler = LootHandler(RoomProfitList.get(self.get_element_key()))\nif self.schedul...
<|body_start_0|> super(MudderyProfitRoom, self).__init__() self.scheduler = AsyncIOScheduler(timezone=pytz.utc) self.last_trigger_time = {} self.loot_handler = None <|end_body_0|> <|body_start_1|> await super(MudderyProfitRoom, self).at_element_setup(first_time) self.loo...
Characters in this room can get profits.
MudderyProfitRoom
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MudderyProfitRoom: """Characters in this room can get profits.""" def __init__(self): """Init the element.""" <|body_0|> async def at_element_setup(self, first_time): """Set data_info to the object.""" <|body_1|> async def at_character_arrive(self, c...
stack_v2_sparse_classes_36k_train_003343
4,520
permissive
[ { "docstring": "Init the element.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Set data_info to the object.", "name": "at_element_setup", "signature": "async def at_element_setup(self, first_time)" }, { "docstring": "Called after an object has been m...
5
null
Implement the Python class `MudderyProfitRoom` described below. Class description: Characters in this room can get profits. Method signatures and docstrings: - def __init__(self): Init the element. - async def at_element_setup(self, first_time): Set data_info to the object. - async def at_character_arrive(self, chara...
Implement the Python class `MudderyProfitRoom` described below. Class description: Characters in this room can get profits. Method signatures and docstrings: - def __init__(self): Init the element. - async def at_element_setup(self, first_time): Set data_info to the object. - async def at_character_arrive(self, chara...
5fa06b29bf800646dc4da5851fdf7a1f299f15a7
<|skeleton|> class MudderyProfitRoom: """Characters in this room can get profits.""" def __init__(self): """Init the element.""" <|body_0|> async def at_element_setup(self, first_time): """Set data_info to the object.""" <|body_1|> async def at_character_arrive(self, c...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MudderyProfitRoom: """Characters in this room can get profits.""" def __init__(self): """Init the element.""" super(MudderyProfitRoom, self).__init__() self.scheduler = AsyncIOScheduler(timezone=pytz.utc) self.last_trigger_time = {} self.loot_handler = None as...
the_stack_v2_python_sparse
muddery/server/elements/profit_room.py
muddery/muddery
train
139
9e469b074e5d6cfeb90e97ee6a1d82f136477cef
[ "self.__counter = 0\nself.__gauss_mean = self._config.get('gauss_mean', convert_to=float, min_value=0, max_value=10, required_field=True)\nself.__gauss_stddev = self._config.get('gauss_stddev', default=0.25, convert_to=float, min_value=0, max_value=5)", "self.__counter += 1\nself._logger.emit_value('uniform', ran...
<|body_start_0|> self.__counter = 0 self.__gauss_mean = self._config.get('gauss_mean', convert_to=float, min_value=0, max_value=10, required_field=True) self.__gauss_stddev = self._config.get('gauss_stddev', default=0.25, convert_to=float, min_value=0, max_value=5) <|end_body_0|> <|body_start_1...
A Scalyr agent monitor that records random numbers.
RandomMonitor
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RandomMonitor: """A Scalyr agent monitor that records random numbers.""" def _initialize(self): """Performs monitor-specific initialization.""" <|body_0|> def gather_sample(self): """Invoked once per sample interval to gather a statistic.""" <|body_1|> <...
stack_v2_sparse_classes_36k_train_003344
4,610
permissive
[ { "docstring": "Performs monitor-specific initialization.", "name": "_initialize", "signature": "def _initialize(self)" }, { "docstring": "Invoked once per sample interval to gather a statistic.", "name": "gather_sample", "signature": "def gather_sample(self)" } ]
2
stack_v2_sparse_classes_30k_train_017233
Implement the Python class `RandomMonitor` described below. Class description: A Scalyr agent monitor that records random numbers. Method signatures and docstrings: - def _initialize(self): Performs monitor-specific initialization. - def gather_sample(self): Invoked once per sample interval to gather a statistic.
Implement the Python class `RandomMonitor` described below. Class description: A Scalyr agent monitor that records random numbers. Method signatures and docstrings: - def _initialize(self): Performs monitor-specific initialization. - def gather_sample(self): Invoked once per sample interval to gather a statistic. <|...
5099a498edc47ab841965b483c2c32af49eb7dae
<|skeleton|> class RandomMonitor: """A Scalyr agent monitor that records random numbers.""" def _initialize(self): """Performs monitor-specific initialization.""" <|body_0|> def gather_sample(self): """Invoked once per sample interval to gather a statistic.""" <|body_1|> <...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RandomMonitor: """A Scalyr agent monitor that records random numbers.""" def _initialize(self): """Performs monitor-specific initialization.""" self.__counter = 0 self.__gauss_mean = self._config.get('gauss_mean', convert_to=float, min_value=0, max_value=10, required_field=True) ...
the_stack_v2_python_sparse
scalyr_agent/builtin_monitors/test_monitor.py
scalyr/scalyr-agent-2
train
75
d7e08d9fe74455f70df4be5b7c4ca61f6214f580
[ "if name is None:\n name = 'simple_conv_net_{}'.format(network_type)\nsuper(SimpleConvNet, self).__init__(name=name)\nself._conv_spec = conv_spec\nself._use_bias = use_bias\nself._initializers = initializers\nself._initializers_no_bias = initializers_no_bias\nself._regularizers = regularizers\nself._regularizers...
<|body_start_0|> if name is None: name = 'simple_conv_net_{}'.format(network_type) super(SimpleConvNet, self).__init__(name=name) self._conv_spec = conv_spec self._use_bias = use_bias self._initializers = initializers self._initializers_no_bias = initializers_...
A simple convolutional network.
SimpleConvNet
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SimpleConvNet: """A simple convolutional network.""" def __init__(self, conv_spec, network_type='encoder', use_bias=True, nonlinearity=tf.nn.leaky_relu, skip_type=None, data_format='NCHW', initializers=None, initializers_no_bias=None, regularizers=None, regularizers_no_bias=None, name=None):...
stack_v2_sparse_classes_36k_train_003345
31,363
no_license
[ { "docstring": "Constructs a SimpleConvNet. Args: conv_spec: A tuple specifying the parameters of the network. Each entry is a NamedTuple, with the values of the corresponding layer. network_type: Determines whether the network is an 'encoder' or 'decoder'. The former can specify pooling layers, while the latte...
2
stack_v2_sparse_classes_30k_train_018428
Implement the Python class `SimpleConvNet` described below. Class description: A simple convolutional network. Method signatures and docstrings: - def __init__(self, conv_spec, network_type='encoder', use_bias=True, nonlinearity=tf.nn.leaky_relu, skip_type=None, data_format='NCHW', initializers=None, initializers_no_...
Implement the Python class `SimpleConvNet` described below. Class description: A simple convolutional network. Method signatures and docstrings: - def __init__(self, conv_spec, network_type='encoder', use_bias=True, nonlinearity=tf.nn.leaky_relu, skip_type=None, data_format='NCHW', initializers=None, initializers_no_...
358a09d491aab0794df9cc7f3f8064430a78fbc3
<|skeleton|> class SimpleConvNet: """A simple convolutional network.""" def __init__(self, conv_spec, network_type='encoder', use_bias=True, nonlinearity=tf.nn.leaky_relu, skip_type=None, data_format='NCHW', initializers=None, initializers_no_bias=None, regularizers=None, regularizers_no_bias=None, name=None):...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SimpleConvNet: """A simple convolutional network.""" def __init__(self, conv_spec, network_type='encoder', use_bias=True, nonlinearity=tf.nn.leaky_relu, skip_type=None, data_format='NCHW', initializers=None, initializers_no_bias=None, regularizers=None, regularizers_no_bias=None, name=None): """C...
the_stack_v2_python_sparse
architectures/conv_architectures.py
zwbgood6/temporal-hierarchy
train
0
08db45e88733372e62ed979752e2830f4d375942
[ "context = self.user_context\nfw = context.first\nuse_user = context.batch_user()\nplaces = shareds.dservice.dr_get_place_list_fw(use_user, fw, context.count, lang=context.lang)\nif places:\n print(f'PlaceReader.get_place_list: {len(places)} places {context.direction} \"{places[0].pname}\" – \"{places[-1].pname}...
<|body_start_0|> context = self.user_context fw = context.first use_user = context.batch_user() places = shareds.dservice.dr_get_place_list_fw(use_user, fw, context.count, lang=context.lang) if places: print(f'PlaceReader.get_place_list: {len(places)} places {context....
Abstracted Place datastore for reading. Data reading class for Place objects with associated data. - Methods return a dict result object {'status':Status, ...}
PlaceReader
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PlaceReader: """Abstracted Place datastore for reading. Data reading class for Place objects with associated data. - Methods return a dict result object {'status':Status, ...}""" def get_place_list(self): """Get a list on PlaceBl objects with nearest heirarchy neighbours. Haetaan pai...
stack_v2_sparse_classes_36k_train_003346
24,736
no_license
[ { "docstring": "Get a list on PlaceBl objects with nearest heirarchy neighbours. Haetaan paikkaluettelo ml. hierarkiassa ylemmät ja alemmat", "name": "get_place_list", "signature": "def get_place_list(self)" }, { "docstring": "Read the place hierarchy and events connected to this place. Luetaan ...
3
stack_v2_sparse_classes_30k_train_001926
Implement the Python class `PlaceReader` described below. Class description: Abstracted Place datastore for reading. Data reading class for Place objects with associated data. - Methods return a dict result object {'status':Status, ...} Method signatures and docstrings: - def get_place_list(self): Get a list on Place...
Implement the Python class `PlaceReader` described below. Class description: Abstracted Place datastore for reading. Data reading class for Place objects with associated data. - Methods return a dict result object {'status':Status, ...} Method signatures and docstrings: - def get_place_list(self): Get a list on Place...
0f8d6ba035e3cca8dc756531b7cc51029a549a4f
<|skeleton|> class PlaceReader: """Abstracted Place datastore for reading. Data reading class for Place objects with associated data. - Methods return a dict result object {'status':Status, ...}""" def get_place_list(self): """Get a list on PlaceBl objects with nearest heirarchy neighbours. Haetaan pai...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PlaceReader: """Abstracted Place datastore for reading. Data reading class for Place objects with associated data. - Methods return a dict result object {'status':Status, ...}""" def get_place_list(self): """Get a list on PlaceBl objects with nearest heirarchy neighbours. Haetaan paikkaluettelo m...
the_stack_v2_python_sparse
bl/place.py
kkujansuu/stk
train
0
6a308b1cb84be20d3c9175ff54979ecff518a24d
[ "base.Action.__init__(self, self.__openDir)\nself.__overlayList = overlayList\nself.__displayCtx = displayCtx", "def onLoad(paths, overlays):\n if len(overlays) == 0:\n return\n self.__overlayList.extend(overlays)\n self.__displayCtx.selectedOverlay = self.__displayCtx.overlayOrder[-1]\n if sel...
<|body_start_0|> base.Action.__init__(self, self.__openDir) self.__overlayList = overlayList self.__displayCtx = displayCtx <|end_body_0|> <|body_start_1|> def onLoad(paths, overlays): if len(overlays) == 0: return self.__overlayList.extend(overla...
The ``LoadOverlayFromDirAction`` allows the user to add overlays to the :class:`.OverlayList`. This functionality is provided by functions in the :mod:`.loadoverlay` module.
LoadOverlayFromDirAction
[ "BSD-3-Clause", "CC-BY-3.0", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LoadOverlayFromDirAction: """The ``LoadOverlayFromDirAction`` allows the user to add overlays to the :class:`.OverlayList`. This functionality is provided by functions in the :mod:`.loadoverlay` module.""" def __init__(self, overlayList, displayCtx, frame): """Create an ``OpenDirActi...
stack_v2_sparse_classes_36k_train_003347
2,200
permissive
[ { "docstring": "Create an ``OpenDirAction``. :arg overlayList: The :class:`.OverlayList`. :arg displayCtx: The :class:`.DisplayContext`. :arg frame: The :class:`.FSLeyesFrame`.", "name": "__init__", "signature": "def __init__(self, overlayList, displayCtx, frame)" }, { "docstring": "Calls the :f...
2
null
Implement the Python class `LoadOverlayFromDirAction` described below. Class description: The ``LoadOverlayFromDirAction`` allows the user to add overlays to the :class:`.OverlayList`. This functionality is provided by functions in the :mod:`.loadoverlay` module. Method signatures and docstrings: - def __init__(self,...
Implement the Python class `LoadOverlayFromDirAction` described below. Class description: The ``LoadOverlayFromDirAction`` allows the user to add overlays to the :class:`.OverlayList`. This functionality is provided by functions in the :mod:`.loadoverlay` module. Method signatures and docstrings: - def __init__(self,...
46ccb4fe2b2346eb57576247f49714032b61307a
<|skeleton|> class LoadOverlayFromDirAction: """The ``LoadOverlayFromDirAction`` allows the user to add overlays to the :class:`.OverlayList`. This functionality is provided by functions in the :mod:`.loadoverlay` module.""" def __init__(self, overlayList, displayCtx, frame): """Create an ``OpenDirActi...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LoadOverlayFromDirAction: """The ``LoadOverlayFromDirAction`` allows the user to add overlays to the :class:`.OverlayList`. This functionality is provided by functions in the :mod:`.loadoverlay` module.""" def __init__(self, overlayList, displayCtx, frame): """Create an ``OpenDirAction``. :arg ov...
the_stack_v2_python_sparse
fsleyes/actions/loadoverlayfromdir.py
sanjayankur31/fsleyes
train
1
30e3ca8b72cc31243d061348299db2db33ef26de
[ "self._absolute_value = absolute_value\nself._comparator_fn = comparator_fn\nself._error_loss_fn = error_loss_fn\nsuper(AbsoluteConstraint, self).__init__(time_step_spec, action_spec, constraint_network, error_loss_fn=self._error_loss_fn, name=name)", "predicted_values, _ = self._constraint_network(observation, t...
<|body_start_0|> self._absolute_value = absolute_value self._comparator_fn = comparator_fn self._error_loss_fn = error_loss_fn super(AbsoluteConstraint, self).__init__(time_step_spec, action_spec, constraint_network, error_loss_fn=self._error_loss_fn, name=name) <|end_body_0|> <|body_st...
Class for representing a trainable absolute value constraint. This constraint class implements an absolute value constraint such as ``` expected_value(action) >= absolute_value ``` or ``` expected_value(action) <= absolute_value ```
AbsoluteConstraint
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AbsoluteConstraint: """Class for representing a trainable absolute value constraint. This constraint class implements an absolute value constraint such as ``` expected_value(action) >= absolute_value ``` or ``` expected_value(action) <= absolute_value ```""" def __init__(self, time_step_spec...
stack_v2_sparse_classes_36k_train_003348
22,532
permissive
[ { "docstring": "Creates a trainable absolute constraint using a neural network. Args: time_step_spec: A `TimeStep` spec of the expected time_steps. action_spec: A nest of `BoundedTensorSpec` representing the actions. constraint_network: An instance of `tf_agents.network.Network` used to provide estimates of act...
2
null
Implement the Python class `AbsoluteConstraint` described below. Class description: Class for representing a trainable absolute value constraint. This constraint class implements an absolute value constraint such as ``` expected_value(action) >= absolute_value ``` or ``` expected_value(action) <= absolute_value ``` M...
Implement the Python class `AbsoluteConstraint` described below. Class description: Class for representing a trainable absolute value constraint. This constraint class implements an absolute value constraint such as ``` expected_value(action) >= absolute_value ``` or ``` expected_value(action) <= absolute_value ``` M...
eca1093d3a047e538f17f6ab92ab4d8144284f23
<|skeleton|> class AbsoluteConstraint: """Class for representing a trainable absolute value constraint. This constraint class implements an absolute value constraint such as ``` expected_value(action) >= absolute_value ``` or ``` expected_value(action) <= absolute_value ```""" def __init__(self, time_step_spec...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AbsoluteConstraint: """Class for representing a trainable absolute value constraint. This constraint class implements an absolute value constraint such as ``` expected_value(action) >= absolute_value ``` or ``` expected_value(action) <= absolute_value ```""" def __init__(self, time_step_spec: types.TimeS...
the_stack_v2_python_sparse
tf_agents/bandits/policies/constraints.py
tensorflow/agents
train
2,755
b3216b2e8501a0d64451f80d8715c76a6de275f1
[ "t_data = np.copy(_t_data.astype(np.float))\nt_data = (_t_outLimits[1] - _t_outLimits[0]) * (t_data - t_data.min()) / (t_data.max() - t_data.min()) + _t_outLimits[0]\nreturn t_data", "t_data = np.copy(_t_data.astype(np.float))\nt_hist = np.histogram(t_data, QARK_HISTOGRAM_BINS)\nt_histCumul = np.cumsum(1.0 * t_hi...
<|body_start_0|> t_data = np.copy(_t_data.astype(np.float)) t_data = (_t_outLimits[1] - _t_outLimits[0]) * (t_data - t_data.min()) / (t_data.max() - t_data.min()) + _t_outLimits[0] return t_data <|end_body_0|> <|body_start_1|> t_data = np.copy(_t_data.astype(np.float)) t_hist = ...
QArkHistogramEqualization
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class QArkHistogramEqualization: def equalize_LINEAR(cls, _t_data, _t_outLimits): """Egalisation lineaire de la matrice en entree @param _t_data : donnee en entree @type _t_data : L{np.nparray} @param _t_outLimits : (min, max) @type _t_outLimits : C{tuple} @rtype : L{np.nparray}""" <|b...
stack_v2_sparse_classes_36k_train_003349
3,223
permissive
[ { "docstring": "Egalisation lineaire de la matrice en entree @param _t_data : donnee en entree @type _t_data : L{np.nparray} @param _t_outLimits : (min, max) @type _t_outLimits : C{tuple} @rtype : L{np.nparray}", "name": "equalize_LINEAR", "signature": "def equalize_LINEAR(cls, _t_data, _t_outLimits)" ...
3
null
Implement the Python class `QArkHistogramEqualization` described below. Class description: Implement the QArkHistogramEqualization class. Method signatures and docstrings: - def equalize_LINEAR(cls, _t_data, _t_outLimits): Egalisation lineaire de la matrice en entree @param _t_data : donnee en entree @type _t_data : ...
Implement the Python class `QArkHistogramEqualization` described below. Class description: Implement the QArkHistogramEqualization class. Method signatures and docstrings: - def equalize_LINEAR(cls, _t_data, _t_outLimits): Egalisation lineaire de la matrice en entree @param _t_data : donnee en entree @type _t_data : ...
46e03095028d2a2f153959d910ceab06a633223d
<|skeleton|> class QArkHistogramEqualization: def equalize_LINEAR(cls, _t_data, _t_outLimits): """Egalisation lineaire de la matrice en entree @param _t_data : donnee en entree @type _t_data : L{np.nparray} @param _t_outLimits : (min, max) @type _t_outLimits : C{tuple} @rtype : L{np.nparray}""" <|b...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class QArkHistogramEqualization: def equalize_LINEAR(cls, _t_data, _t_outLimits): """Egalisation lineaire de la matrice en entree @param _t_data : donnee en entree @type _t_data : L{np.nparray} @param _t_outLimits : (min, max) @type _t_outLimits : C{tuple} @rtype : L{np.nparray}""" t_data = np.copy(...
the_stack_v2_python_sparse
src/pyQArk/Image/QArkHistogramEqualization.py
arnaudkelbert/pyQArk
train
1
cdadb53dc4ebc74162e6a2fc73eb7adb21dcdfa3
[ "self.logger = logging.getLogger('RuleManager')\nself.logger.debug('Initializing the %s.' % self.__class__.__name__)\nself._initialized = datetime.now()\nself.archive_dir = archive_dir\nself.files = self.collect_all_files()", "collected_files = list()\nfor subdir, dirs, files in os.walk(self.archive_dir):\n fo...
<|body_start_0|> self.logger = logging.getLogger('RuleManager') self.logger.debug('Initializing the %s.' % self.__class__.__name__) self._initialized = datetime.now() self.archive_dir = archive_dir self.files = self.collect_all_files() <|end_body_0|> <|body_start_1|> col...
Class FileCollector Used for collecting files from a directory
FileCollector
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FileCollector: """Class FileCollector Used for collecting files from a directory""" def __init__(self, archive_dir): """Initialize a file collector class.""" <|body_0|> def collect_all_files(self): """Store all files in the directory.""" <|body_1|> <|end...
stack_v2_sparse_classes_36k_train_003350
1,088
permissive
[ { "docstring": "Initialize a file collector class.", "name": "__init__", "signature": "def __init__(self, archive_dir)" }, { "docstring": "Store all files in the directory.", "name": "collect_all_files", "signature": "def collect_all_files(self)" } ]
2
stack_v2_sparse_classes_30k_train_016492
Implement the Python class `FileCollector` described below. Class description: Class FileCollector Used for collecting files from a directory Method signatures and docstrings: - def __init__(self, archive_dir): Initialize a file collector class. - def collect_all_files(self): Store all files in the directory.
Implement the Python class `FileCollector` described below. Class description: Class FileCollector Used for collecting files from a directory Method signatures and docstrings: - def __init__(self, archive_dir): Initialize a file collector class. - def collect_all_files(self): Store all files in the directory. <|skel...
6f0719b8e778e4603ca5d2b131d8bda733326019
<|skeleton|> class FileCollector: """Class FileCollector Used for collecting files from a directory""" def __init__(self, archive_dir): """Initialize a file collector class.""" <|body_0|> def collect_all_files(self): """Store all files in the directory.""" <|body_1|> <|end...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FileCollector: """Class FileCollector Used for collecting files from a directory""" def __init__(self, archive_dir): """Initialize a file collector class.""" self.logger = logging.getLogger('RuleManager') self.logger.debug('Initializing the %s.' % self.__class__.__name__) ...
the_stack_v2_python_sparse
sds/filecollector.py
KNMI/DMPilot-RuleManager
train
4
0c1e6fe470dccd462751deb6e6bf8c1f338c7340
[ "self.dic = {}\nself.lis = []\nself.cap = capacity\nself.use = 0", "if key in self.dic:\n self.lis.remove(key)\n self.lis.append(key)\n return self.dic[key]\nelse:\n return -1", "if self.get(key) == -1:\n if self.use < self.cap:\n self.dic[key] = value\n self.lis.append(key)\n ...
<|body_start_0|> self.dic = {} self.lis = [] self.cap = capacity self.use = 0 <|end_body_0|> <|body_start_1|> if key in self.dic: self.lis.remove(key) self.lis.append(key) return self.dic[key] else: return -1 <|end_body_1|>...
LRUCache
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LRUCache: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def get(self, key): """:rtype: int""" <|body_1|> def set(self, key, value): """:type key: int :type value: int :rtype: nothing""" <|body_2|> <|end_skeleton|> <...
stack_v2_sparse_classes_36k_train_003351
948
no_license
[ { "docstring": ":type capacity: int", "name": "__init__", "signature": "def __init__(self, capacity)" }, { "docstring": ":rtype: int", "name": "get", "signature": "def get(self, key)" }, { "docstring": ":type key: int :type value: int :rtype: nothing", "name": "set", "sig...
3
null
Implement the Python class `LRUCache` described below. Class description: Implement the LRUCache class. Method signatures and docstrings: - def __init__(self, capacity): :type capacity: int - def get(self, key): :rtype: int - def set(self, key, value): :type key: int :type value: int :rtype: nothing
Implement the Python class `LRUCache` described below. Class description: Implement the LRUCache class. Method signatures and docstrings: - def __init__(self, capacity): :type capacity: int - def get(self, key): :rtype: int - def set(self, key, value): :type key: int :type value: int :rtype: nothing <|skeleton|> cla...
ef8c9422c481aa3c482933318c785ad28dd7703e
<|skeleton|> class LRUCache: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def get(self, key): """:rtype: int""" <|body_1|> def set(self, key, value): """:type key: int :type value: int :rtype: nothing""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LRUCache: def __init__(self, capacity): """:type capacity: int""" self.dic = {} self.lis = [] self.cap = capacity self.use = 0 def get(self, key): """:rtype: int""" if key in self.dic: self.lis.remove(key) self.lis.append(key...
the_stack_v2_python_sparse
python/lru_cache.py
pzmrzy/LeetCode
train
2
4ced799c2e6370ca55cc2a371541627f77ffaa3d
[ "ls = len(s)\nlp = len(p)\nif ls < lp or lp == 0:\n return []\ndic = dict()\nfor c in p:\n if c in dic:\n dic[c] += 1\n else:\n dic[c] = 1\nimport copy\nr = []\nfor i in range(0, ls - lp + 1):\n t = copy.deepcopy(dic)\n f = True\n for j in range(i, i + lp):\n if s[j] in t and ...
<|body_start_0|> ls = len(s) lp = len(p) if ls < lp or lp == 0: return [] dic = dict() for c in p: if c in dic: dic[c] += 1 else: dic[c] = 1 import copy r = [] for i in range(0, ls - lp + ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def findAnagrams1(self, s, p): """:type s: str :type p: str :rtype: List[int]""" <|body_0|> def findAnagrams(self, s, p): """:type s: str :type p: str :rtype: List[int]""" <|body_1|> <|end_skeleton|> <|body_start_0|> ls = len(s) lp...
stack_v2_sparse_classes_36k_train_003352
1,779
no_license
[ { "docstring": ":type s: str :type p: str :rtype: List[int]", "name": "findAnagrams1", "signature": "def findAnagrams1(self, s, p)" }, { "docstring": ":type s: str :type p: str :rtype: List[int]", "name": "findAnagrams", "signature": "def findAnagrams(self, s, p)" } ]
2
stack_v2_sparse_classes_30k_train_007809
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findAnagrams1(self, s, p): :type s: str :type p: str :rtype: List[int] - def findAnagrams(self, s, p): :type s: str :type p: str :rtype: List[int]
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findAnagrams1(self, s, p): :type s: str :type p: str :rtype: List[int] - def findAnagrams(self, s, p): :type s: str :type p: str :rtype: List[int] <|skeleton|> class Solutio...
e5b018493bbd12edcdcd0434f35d9c358106d391
<|skeleton|> class Solution: def findAnagrams1(self, s, p): """:type s: str :type p: str :rtype: List[int]""" <|body_0|> def findAnagrams(self, s, p): """:type s: str :type p: str :rtype: List[int]""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def findAnagrams1(self, s, p): """:type s: str :type p: str :rtype: List[int]""" ls = len(s) lp = len(p) if ls < lp or lp == 0: return [] dic = dict() for c in p: if c in dic: dic[c] += 1 else: ...
the_stack_v2_python_sparse
py/leetcode/438.py
wfeng1991/learnpy
train
0
f35f3cce805cff67a4c4ef0955c82132ecad2c0e
[ "self.name = 'DIRECT'\nself.epsilon = epsilon\nself.delta = delta\nsuper(MABDirect, self).__init__(self.name, arm_pull)", "n = len(arms)\nnum_pulls = int(np.ceil(2 / self.epsilon ** 2 * math.log(n / self.delta)))\nrewards = np.empty([num_pulls, n])\nfor a in range(0, n):\n for p in range(0, num_pulls):\n ...
<|body_start_0|> self.name = 'DIRECT' self.epsilon = epsilon self.delta = delta super(MABDirect, self).__init__(self.name, arm_pull) <|end_body_0|> <|body_start_1|> n = len(arms) num_pulls = int(np.ceil(2 / self.epsilon ** 2 * math.log(n / self.delta))) rewards =...
The DIRECT algorithm pulls each arm a fixed number of times such that with high probability (1-delta), the k selected arms with highest empirical averages are all (epsilon, k)-optimal. Ref: "Efficient Selection of Multiple Bandit Arms: Theory and Practice", Shivaram Kalyanakrishnan and Peter Stone
MABDirect
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MABDirect: """The DIRECT algorithm pulls each arm a fixed number of times such that with high probability (1-delta), the k selected arms with highest empirical averages are all (epsilon, k)-optimal. Ref: "Efficient Selection of Multiple Bandit Arms: Theory and Practice", Shivaram Kalyanakrishnan ...
stack_v2_sparse_classes_36k_train_003353
3,050
permissive
[ { "docstring": "Set up local variables, :param arm_pull: function handle returning distance between fixed and simulated data for a sample from prior. The prior function must be used within the definition of arm_pull :param epsilon: algorithm-specific (optimality) constant :param delta: algorithm-specific consta...
2
stack_v2_sparse_classes_30k_train_012022
Implement the Python class `MABDirect` described below. Class description: The DIRECT algorithm pulls each arm a fixed number of times such that with high probability (1-delta), the k selected arms with highest empirical averages are all (epsilon, k)-optimal. Ref: "Efficient Selection of Multiple Bandit Arms: Theory a...
Implement the Python class `MABDirect` described below. Class description: The DIRECT algorithm pulls each arm a fixed number of times such that with high probability (1-delta), the k selected arms with highest empirical averages are all (epsilon, k)-optimal. Ref: "Efficient Selection of Multiple Bandit Arms: Theory a...
42f4cfdefd3150e481e1920a92065731370e1b7c
<|skeleton|> class MABDirect: """The DIRECT algorithm pulls each arm a fixed number of times such that with high probability (1-delta), the k selected arms with highest empirical averages are all (epsilon, k)-optimal. Ref: "Efficient Selection of Multiple Bandit Arms: Theory and Practice", Shivaram Kalyanakrishnan ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MABDirect: """The DIRECT algorithm pulls each arm a fixed number of times such that with high probability (1-delta), the k selected arms with highest empirical averages are all (epsilon, k)-optimal. Ref: "Efficient Selection of Multiple Bandit Arms: Theory and Practice", Shivaram Kalyanakrishnan and Peter Sto...
the_stack_v2_python_sparse
sciope/utilities/mab/mab_direct.py
mattiasakesson/sciope
train
0
12dff6e98c672ea7b7e8c1e5b1410b6d0ec5ed1a
[ "self.x = np.array(x)\ntry:\n self.n, self.xdim = self.x.shape\nexcept ValueError:\n self.x = np.reshape(self.x, (len(self.x), 1))\n self.n, self.xdim = self.x.shape\nself.y = np.array(y)\ntry:\n _, self.ydim = y.shape\nexcept ValueError:\n self.ydim = 1\nself.xmin = np.min(self.x, axis=0)\nself.xmax...
<|body_start_0|> self.x = np.array(x) try: self.n, self.xdim = self.x.shape except ValueError: self.x = np.reshape(self.x, (len(self.x), 1)) self.n, self.xdim = self.x.shape self.y = np.array(y) try: _, self.ydim = y.shape e...
Wrap functions.
Wrap
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Wrap: """Wrap functions.""" def __init__(self, x, y, p): """Initialises class to wrap the function with values y at x so that it is p-periodic. Parameters ---------- x : array-like Array of points at which the original function has been evaluated. y : array-like Values of the functio...
stack_v2_sparse_classes_36k_train_003354
35,613
permissive
[ { "docstring": "Initialises class to wrap the function with values y at x so that it is p-periodic. Parameters ---------- x : array-like Array of points at which the original function has been evaluated. y : array-like Values of the function at points x. p : array-like Period of the function in each direction."...
3
stack_v2_sparse_classes_30k_train_016453
Implement the Python class `Wrap` described below. Class description: Wrap functions. Method signatures and docstrings: - def __init__(self, x, y, p): Initialises class to wrap the function with values y at x so that it is p-periodic. Parameters ---------- x : array-like Array of points at which the original function...
Implement the Python class `Wrap` described below. Class description: Wrap functions. Method signatures and docstrings: - def __init__(self, x, y, p): Initialises class to wrap the function with values y at x so that it is p-periodic. Parameters ---------- x : array-like Array of points at which the original function...
b065544639a483dda48cda89bcbb11c1772232aa
<|skeleton|> class Wrap: """Wrap functions.""" def __init__(self, x, y, p): """Initialises class to wrap the function with values y at x so that it is p-periodic. Parameters ---------- x : array-like Array of points at which the original function has been evaluated. y : array-like Values of the functio...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Wrap: """Wrap functions.""" def __init__(self, x, y, p): """Initialises class to wrap the function with values y at x so that it is p-periodic. Parameters ---------- x : array-like Array of points at which the original function has been evaluated. y : array-like Values of the function at points x...
the_stack_v2_python_sparse
maths.py
interesting-codes/active_particles
train
0
2add1c74240e929699c8c39345b8b032f5093026
[ "\"\"\"This will handel all the GET request.\"\"\"\ntrack_info = ArtistInformation.objects.all()\nserializer = ArtistInformationSerializer(track_info, many=True)\nreturn Response({'artist_info': serializer.data})", "artist_name = request.data.get('name')\nserializer = ArtistInformationSerializer(data={'artistName...
<|body_start_0|> """This will handel all the GET request.""" track_info = ArtistInformation.objects.all() serializer = ArtistInformationSerializer(track_info, many=True) return Response({'artist_info': serializer.data}) <|end_body_0|> <|body_start_1|> artist_name = request.data....
This view is for handling operation for Artist Information. It will perform GET, POST, DELETE request for artist information.
ArtistInformationView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ArtistInformationView: """This view is for handling operation for Artist Information. It will perform GET, POST, DELETE request for artist information.""" def get(self, pk=None): """Performs GET operation. Returns a Response with all artist information""" <|body_0|> def ...
stack_v2_sparse_classes_36k_train_003355
5,113
no_license
[ { "docstring": "Performs GET operation. Returns a Response with all artist information", "name": "get", "signature": "def get(self, pk=None)" }, { "docstring": "Performs POST operation. Creates new artist record. Returns a Response with artist information", "name": "post", "signature": "...
3
stack_v2_sparse_classes_30k_train_004990
Implement the Python class `ArtistInformationView` described below. Class description: This view is for handling operation for Artist Information. It will perform GET, POST, DELETE request for artist information. Method signatures and docstrings: - def get(self, pk=None): Performs GET operation. Returns a Response wi...
Implement the Python class `ArtistInformationView` described below. Class description: This view is for handling operation for Artist Information. It will perform GET, POST, DELETE request for artist information. Method signatures and docstrings: - def get(self, pk=None): Performs GET operation. Returns a Response wi...
c2174592ea5a074579f02509590e4ebef34e9348
<|skeleton|> class ArtistInformationView: """This view is for handling operation for Artist Information. It will perform GET, POST, DELETE request for artist information.""" def get(self, pk=None): """Performs GET operation. Returns a Response with all artist information""" <|body_0|> def ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ArtistInformationView: """This view is for handling operation for Artist Information. It will perform GET, POST, DELETE request for artist information.""" def get(self, pk=None): """Performs GET operation. Returns a Response with all artist information""" """This will handel all the GET r...
the_stack_v2_python_sparse
symphony/music_api/views.py
vdkotian/symphony_api
train
0
5df9d0c7f372f827d28df7d0d1ce1f03a98a6b36
[ "EnergyPDF.__init__(self, e_pdf_dict)\nwith open(e_pdf_dict['spline_path'], 'rb') as g:\n f = Pickle.load(g)\n self.f = lambda x: np.exp(f(x))", "weights = mc['ow'] * self.f(mc['trueE'])\nif hasattr(self, 'e_min'):\n mask = mc['trueE'] < self.e_min\n weights[mask] = 0.0\nif hasattr(self, 'e_max'):\n ...
<|body_start_0|> EnergyPDF.__init__(self, e_pdf_dict) with open(e_pdf_dict['spline_path'], 'rb') as g: f = Pickle.load(g) self.f = lambda x: np.exp(f(x)) <|end_body_0|> <|body_start_1|> weights = mc['ow'] * self.f(mc['trueE']) if hasattr(self, 'e_min'): ...
A Power Law energy PDF. Takes an argument of gamma in the dictionary for the init function, where gamma is the spectral index of the Power Law.
Spline
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Spline: """A Power Law energy PDF. Takes an argument of gamma in the dictionary for the init function, where gamma is the spectral index of the Power Law.""" def __init__(self, e_pdf_dict={}): """Creates a PowerLaw object, which is an energy PDF based on a power law. The power law is...
stack_v2_sparse_classes_36k_train_003356
12,372
permissive
[ { "docstring": "Creates a PowerLaw object, which is an energy PDF based on a power law. The power law is generated from e_pdf_dict, which can specify a spectral index (Gamma), as well as an optional minimum energy (E Min) and a maximum energy (E Max) :param e_pdf_dict: Dictionary containing parameters", "na...
2
null
Implement the Python class `Spline` described below. Class description: A Power Law energy PDF. Takes an argument of gamma in the dictionary for the init function, where gamma is the spectral index of the Power Law. Method signatures and docstrings: - def __init__(self, e_pdf_dict={}): Creates a PowerLaw object, whic...
Implement the Python class `Spline` described below. Class description: A Power Law energy PDF. Takes an argument of gamma in the dictionary for the init function, where gamma is the spectral index of the Power Law. Method signatures and docstrings: - def __init__(self, e_pdf_dict={}): Creates a PowerLaw object, whic...
4d02244e3b92744a08b3c09009cc9aa3ea5e7931
<|skeleton|> class Spline: """A Power Law energy PDF. Takes an argument of gamma in the dictionary for the init function, where gamma is the spectral index of the Power Law.""" def __init__(self, e_pdf_dict={}): """Creates a PowerLaw object, which is an energy PDF based on a power law. The power law is...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Spline: """A Power Law energy PDF. Takes an argument of gamma in the dictionary for the init function, where gamma is the spectral index of the Power Law.""" def __init__(self, e_pdf_dict={}): """Creates a PowerLaw object, which is an energy PDF based on a power law. The power law is generated fr...
the_stack_v2_python_sparse
flarestack/core/energy_pdf.py
icecube/flarestack
train
9
168a5c61824136861c43cb0137bf3385ede0a6a0
[ "self.source = source\nself.values = values\nself.before = before\nself._columns_out = None\nself._const_values = [self.values[tag] for tag in self.values]", "if self._columns_out is None:\n new_columns = [HXLColumn(hxlTag=tag) for tag in self.values]\n if self.before:\n self._columns_out = new_colum...
<|body_start_0|> self.source = source self.values = values self.before = before self._columns_out = None self._const_values = [self.values[tag] for tag in self.values] <|end_body_0|> <|body_start_1|> if self._columns_out is None: new_columns = [HXLColumn(hxlT...
Composable filter class to add constant values to every row of a HXL dataset. This is the class supporting the hxladd command-line utility. Because this class is a {@link hxl.model.HXLDataProvider}, you can use it as the source to an instance of another filter class to build a dynamic, single-threaded processing pipeli...
HXLAddFilter
[ "Unlicense" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HXLAddFilter: """Composable filter class to add constant values to every row of a HXL dataset. This is the class supporting the hxladd command-line utility. Because this class is a {@link hxl.model.HXLDataProvider}, you can use it as the source to an instance of another filter class to build a dy...
stack_v2_sparse_classes_36k_train_003357
4,076
permissive
[ { "docstring": "@param source a HXL data source @param values a dictionary of tags and constant values @param before True to add new columns before existing ones", "name": "__init__", "signature": "def __init__(self, source, values, before=False)" }, { "docstring": "Add the constant columns to t...
3
stack_v2_sparse_classes_30k_train_000384
Implement the Python class `HXLAddFilter` described below. Class description: Composable filter class to add constant values to every row of a HXL dataset. This is the class supporting the hxladd command-line utility. Because this class is a {@link hxl.model.HXLDataProvider}, you can use it as the source to an instanc...
Implement the Python class `HXLAddFilter` described below. Class description: Composable filter class to add constant values to every row of a HXL dataset. This is the class supporting the hxladd command-line utility. Because this class is a {@link hxl.model.HXLDataProvider}, you can use it as the source to an instanc...
b0209e75789501d99a2fb2df8a30cf55a383065a
<|skeleton|> class HXLAddFilter: """Composable filter class to add constant values to every row of a HXL dataset. This is the class supporting the hxladd command-line utility. Because this class is a {@link hxl.model.HXLDataProvider}, you can use it as the source to an instance of another filter class to build a dy...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class HXLAddFilter: """Composable filter class to add constant values to every row of a HXL dataset. This is the class supporting the hxladd command-line utility. Because this class is a {@link hxl.model.HXLDataProvider}, you can use it as the source to an instance of another filter class to build a dynamic, single...
the_stack_v2_python_sparse
hxl/filters/add.py
jayvdb/libhxl-python
train
0
1a725a99c23d33a59e31935e37c031cb7f117502
[ "status = ErrorCode.SUCCESS\ntry:\n tid = self.get_argument('tid')\nexcept Exception as e:\n status = ErrorCode.ILLEGAL_DATA_FORMAT\n logging.exception('[UWEB] Invalid data format. Exception: %s', e.args)\n self.write_ret(status)\n return\ntry:\n res = QueryHelper.get_bind_region(tid, self.db)\n ...
<|body_start_0|> status = ErrorCode.SUCCESS try: tid = self.get_argument('tid') except Exception as e: status = ErrorCode.ILLEGAL_DATA_FORMAT logging.exception('[UWEB] Invalid data format. Exception: %s', e.args) self.write_ret(status) ...
Handle regions-bind for corp. :url /bindregion
BindRegionHandler
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BindRegionHandler: """Handle regions-bind for corp. :url /bindregion""" def get(self): """Get all regions binded by the terminal.""" <|body_0|> def post(self): """Bind region bind for the terminals.""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_36k_train_003358
2,434
no_license
[ { "docstring": "Get all regions binded by the terminal.", "name": "get", "signature": "def get(self)" }, { "docstring": "Bind region bind for the terminals.", "name": "post", "signature": "def post(self)" } ]
2
stack_v2_sparse_classes_30k_train_010068
Implement the Python class `BindRegionHandler` described below. Class description: Handle regions-bind for corp. :url /bindregion Method signatures and docstrings: - def get(self): Get all regions binded by the terminal. - def post(self): Bind region bind for the terminals.
Implement the Python class `BindRegionHandler` described below. Class description: Handle regions-bind for corp. :url /bindregion Method signatures and docstrings: - def get(self): Get all regions binded by the terminal. - def post(self): Bind region bind for the terminals. <|skeleton|> class BindRegionHandler: ...
3b095a325581b1fc48497c234f0ad55e928586a1
<|skeleton|> class BindRegionHandler: """Handle regions-bind for corp. :url /bindregion""" def get(self): """Get all regions binded by the terminal.""" <|body_0|> def post(self): """Bind region bind for the terminals.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BindRegionHandler: """Handle regions-bind for corp. :url /bindregion""" def get(self): """Get all regions binded by the terminal.""" status = ErrorCode.SUCCESS try: tid = self.get_argument('tid') except Exception as e: status = ErrorCode.ILLEGAL_DAT...
the_stack_v2_python_sparse
apps/uweb/handlers/bindregion.py
jcsy521/ydws
train
0
86cbfa7089d0e7f9bc204d59894669c4786271d2
[ "timestamp = self._GetRowValue(query_hash, row, value_name)\nif timestamp is None:\n return None\nreturn dfdatetime_posix_time.PosixTime(timestamp=timestamp)", "query_hash = hash(query)\nversion_path = self._GetRowValue(query_hash, row, 'version_path')\npath = self._GetRowValue(query_hash, row, 'path')\npaths ...
<|body_start_0|> timestamp = self._GetRowValue(query_hash, row, value_name) if timestamp is None: return None return dfdatetime_posix_time.PosixTime(timestamp=timestamp) <|end_body_0|> <|body_start_1|> query_hash = hash(query) version_path = self._GetRowValue(query_h...
SQLite parser plugin for MacOS document revision database files.
MacOSDocumentVersionsPlugin
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MacOSDocumentVersionsPlugin: """SQLite parser plugin for MacOS document revision database files.""" def _GetDateTimeRowValue(self, query_hash, row, value_name): """Retrieves a date and time value from the row. Args: query_hash (int): hash of the query, that uniquely identifies the qu...
stack_v2_sparse_classes_36k_train_003359
5,759
permissive
[ { "docstring": "Retrieves a date and time value from the row. Args: query_hash (int): hash of the query, that uniquely identifies the query that produced the row. row (sqlite3.Row): row. value_name (str): name of the value. Returns: dfdatetime.PosixTime: date and time value or None if not available.", "name...
2
null
Implement the Python class `MacOSDocumentVersionsPlugin` described below. Class description: SQLite parser plugin for MacOS document revision database files. Method signatures and docstrings: - def _GetDateTimeRowValue(self, query_hash, row, value_name): Retrieves a date and time value from the row. Args: query_hash ...
Implement the Python class `MacOSDocumentVersionsPlugin` described below. Class description: SQLite parser plugin for MacOS document revision database files. Method signatures and docstrings: - def _GetDateTimeRowValue(self, query_hash, row, value_name): Retrieves a date and time value from the row. Args: query_hash ...
d6022f8cfebfddf2d08ab2d300a41b61f3349933
<|skeleton|> class MacOSDocumentVersionsPlugin: """SQLite parser plugin for MacOS document revision database files.""" def _GetDateTimeRowValue(self, query_hash, row, value_name): """Retrieves a date and time value from the row. Args: query_hash (int): hash of the query, that uniquely identifies the qu...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MacOSDocumentVersionsPlugin: """SQLite parser plugin for MacOS document revision database files.""" def _GetDateTimeRowValue(self, query_hash, row, value_name): """Retrieves a date and time value from the row. Args: query_hash (int): hash of the query, that uniquely identifies the query that prod...
the_stack_v2_python_sparse
plaso/parsers/sqlite_plugins/macos_document_versions.py
log2timeline/plaso
train
1,506
be46cd7531ff525606a8d8ab0fc87b512c849162
[ "self.username = username\nself.password = password\nself.privkey = None\nself.__set_or_create_key_if_not_exist()", "pki = PKI(username=self.username, password=self.password)\nprivkey = pki.load_priv_key()\nif not privkey:\n pki.generate_pub_priv_key()\n privkey = pki.load_priv_key()\nself.privkey = privkey...
<|body_start_0|> self.username = username self.password = password self.privkey = None self.__set_or_create_key_if_not_exist() <|end_body_0|> <|body_start_1|> pki = PKI(username=self.username, password=self.password) privkey = pki.load_priv_key() if not privkey: ...
DigitalSigner
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DigitalSigner: def __init__(self, username, password): """class for digitally signing :param username: string, privkey names after username :param password: string, used to decrypt privkey""" <|body_0|> def __set_or_create_key_if_not_exist(self): """used to set self....
stack_v2_sparse_classes_36k_train_003360
5,078
permissive
[ { "docstring": "class for digitally signing :param username: string, privkey names after username :param password: string, used to decrypt privkey", "name": "__init__", "signature": "def __init__(self, username, password)" }, { "docstring": "used to set self.privkey to private key saved under us...
5
stack_v2_sparse_classes_30k_train_017604
Implement the Python class `DigitalSigner` described below. Class description: Implement the DigitalSigner class. Method signatures and docstrings: - def __init__(self, username, password): class for digitally signing :param username: string, privkey names after username :param password: string, used to decrypt privk...
Implement the Python class `DigitalSigner` described below. Class description: Implement the DigitalSigner class. Method signatures and docstrings: - def __init__(self, username, password): class for digitally signing :param username: string, privkey names after username :param password: string, used to decrypt privk...
218706c2956de47e8c5699a6abcad5cab1af85cd
<|skeleton|> class DigitalSigner: def __init__(self, username, password): """class for digitally signing :param username: string, privkey names after username :param password: string, used to decrypt privkey""" <|body_0|> def __set_or_create_key_if_not_exist(self): """used to set self....
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DigitalSigner: def __init__(self, username, password): """class for digitally signing :param username: string, privkey names after username :param password: string, used to decrypt privkey""" self.username = username self.password = password self.privkey = None self.__s...
the_stack_v2_python_sparse
Orses_Cryptography_Core/DigitalSigner.py
snwokenk/Orses_Core
train
0
74d316a81db98c9f5dd6e04d4c4001fea727adc6
[ "from collections import defaultdict\nstore = defaultdict(dict)\nreturn self.uniqueP(m, n, 1, 1, store)", "if x == m and y == n:\n return 1\nif x >= m:\n return self.uniqueP(m, n, x, y + 1, store)\nif y >= n:\n return self.uniqueP(m, n, x + 1, y, store)\nif y not in store[x]:\n store[x][y] = self.uniq...
<|body_start_0|> from collections import defaultdict store = defaultdict(dict) return self.uniqueP(m, n, 1, 1, store) <|end_body_0|> <|body_start_1|> if x == m and y == n: return 1 if x >= m: return self.uniqueP(m, n, x, y + 1, store) if y >= n: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def uniquePaths(self, m, n): """:type m: int :type n: int :rtype: int""" <|body_0|> def uniqueP(self, m, n, x, y, store): """x, y represent robot position""" <|body_1|> <|end_skeleton|> <|body_start_0|> from collections import defaultdict ...
stack_v2_sparse_classes_36k_train_003361
1,313
no_license
[ { "docstring": ":type m: int :type n: int :rtype: int", "name": "uniquePaths", "signature": "def uniquePaths(self, m, n)" }, { "docstring": "x, y represent robot position", "name": "uniqueP", "signature": "def uniqueP(self, m, n, x, y, store)" } ]
2
stack_v2_sparse_classes_30k_train_002272
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def uniquePaths(self, m, n): :type m: int :type n: int :rtype: int - def uniqueP(self, m, n, x, y, store): x, y represent robot position
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def uniquePaths(self, m, n): :type m: int :type n: int :rtype: int - def uniqueP(self, m, n, x, y, store): x, y represent robot position <|skeleton|> class Solution: def un...
c170b8eb6c71533c78663ec1e3e9f47cff811419
<|skeleton|> class Solution: def uniquePaths(self, m, n): """:type m: int :type n: int :rtype: int""" <|body_0|> def uniqueP(self, m, n, x, y, store): """x, y represent robot position""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def uniquePaths(self, m, n): """:type m: int :type n: int :rtype: int""" from collections import defaultdict store = defaultdict(dict) return self.uniqueP(m, n, 1, 1, store) def uniqueP(self, m, n, x, y, store): """x, y represent robot position""" ...
the_stack_v2_python_sparse
leetcode/062_unique_paths/python/unique_paths.py
philips-ni/ecfs
train
1
3526a519f2d906d116fbecdd4930a0d76e93586f
[ "err = np.ones(k + 1)\ngroup_size = len(traindata) // 5\nfor j in range(1, k + 1):\n err_sum = 0.0\n classifier = KNeighborsClassifier(n_neighbors=j)\n for i in range(5):\n tdata = np.concatenate((traindata[:i * group_size, :], traindata[(i + 1) * group_size:, :]), axis=0)\n tlabels = np.appe...
<|body_start_0|> err = np.ones(k + 1) group_size = len(traindata) // 5 for j in range(1, k + 1): err_sum = 0.0 classifier = KNeighborsClassifier(n_neighbors=j) for i in range(5): tdata = np.concatenate((traindata[:i * group_size, :], traindata[...
Question2
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Question2: def crossValidationkNN(self, traindata, trainlabels, k): """Write a function which implements 5-fold cross-validation to estimate the error of a classifier with cross-validation with the 0,1-loss for k-Nearest Neighbors (kNN). For this problem, take your folds to be 0:N/5, N/5...
stack_v2_sparse_classes_36k_train_003362
21,354
no_license
[ { "docstring": "Write a function which implements 5-fold cross-validation to estimate the error of a classifier with cross-validation with the 0,1-loss for k-Nearest Neighbors (kNN). For this problem, take your folds to be 0:N/5, N/5:2N/5, ..., 4N/5:N for cross-validation. Parameters: 1. traindata (Nt, d) numpy...
3
null
Implement the Python class `Question2` described below. Class description: Implement the Question2 class. Method signatures and docstrings: - def crossValidationkNN(self, traindata, trainlabels, k): Write a function which implements 5-fold cross-validation to estimate the error of a classifier with cross-validation w...
Implement the Python class `Question2` described below. Class description: Implement the Question2 class. Method signatures and docstrings: - def crossValidationkNN(self, traindata, trainlabels, k): Write a function which implements 5-fold cross-validation to estimate the error of a classifier with cross-validation w...
adcb6b47164a909fe8b3cd3969c8bc3f3696893a
<|skeleton|> class Question2: def crossValidationkNN(self, traindata, trainlabels, k): """Write a function which implements 5-fold cross-validation to estimate the error of a classifier with cross-validation with the 0,1-loss for k-Nearest Neighbors (kNN). For this problem, take your folds to be 0:N/5, N/5...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Question2: def crossValidationkNN(self, traindata, trainlabels, k): """Write a function which implements 5-fold cross-validation to estimate the error of a classifier with cross-validation with the 0,1-loss for k-Nearest Neighbors (kNN). For this problem, take your folds to be 0:N/5, N/5:2N/5, ..., 4N...
the_stack_v2_python_sparse
ECE365/ML/lab3/main.py
RickyL-2000/ZJUI-lib
train
1
01d2a0e9624894f835cba384993e5225bfce2811
[ "self.record = record\nself.current_action = action\nrecord_needs = self.collect_needs()\nsuper().__init__(*record_needs)", "if self.current_action == 'read':\n return self.read_permissions()\nelif self.current_action == 'create':\n return [create_records_action, backoffice_access_action]\nelif self.current...
<|body_start_0|> self.record = record self.current_action = action record_needs = self.collect_needs() super().__init__(*record_needs) <|end_body_0|> <|body_start_1|> if self.current_action == 'read': return self.read_permissions() elif self.current_action ==...
Record permission. - Create action given to librarian, admin and specified users. - Read access given to everyone with possibility to hide. - Delete access to admin and specified users.
RecordPermission
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RecordPermission: """Record permission. - Create action given to librarian, admin and specified users. - Read access given to everyone with possibility to hide. - Delete access to admin and specified users.""" def __init__(self, record, action): """Constructor.""" <|body_0|> ...
stack_v2_sparse_classes_36k_train_003363
3,773
permissive
[ { "docstring": "Constructor.", "name": "__init__", "signature": "def __init__(self, record, action)" }, { "docstring": "Collect permission policy per action.", "name": "collect_needs", "signature": "def collect_needs(self)" }, { "docstring": "Define read permission policy per rec...
6
null
Implement the Python class `RecordPermission` described below. Class description: Record permission. - Create action given to librarian, admin and specified users. - Read access given to everyone with possibility to hide. - Delete access to admin and specified users. Method signatures and docstrings: - def __init__(s...
Implement the Python class `RecordPermission` described below. Class description: Record permission. - Create action given to librarian, admin and specified users. - Read access given to everyone with possibility to hide. - Delete access to admin and specified users. Method signatures and docstrings: - def __init__(s...
1c36526e85510100c5f64059518d1b716d87ac10
<|skeleton|> class RecordPermission: """Record permission. - Create action given to librarian, admin and specified users. - Read access given to everyone with possibility to hide. - Delete access to admin and specified users.""" def __init__(self, record, action): """Constructor.""" <|body_0|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RecordPermission: """Record permission. - Create action given to librarian, admin and specified users. - Read access given to everyone with possibility to hide. - Delete access to admin and specified users.""" def __init__(self, record, action): """Constructor.""" self.record = record ...
the_stack_v2_python_sparse
invenio_app_ils/records/permissions.py
inveniosoftware/invenio-app-ils
train
64
611a2a180f1cb77fc415c4430ed0eb8d723aa8b2
[ "color2D = ee.Dictionary(ee.Dictionary(color).get('2D'))\nsaturation = ee.Image(color2D.get('saturation'))\nvalue = ee.Image(color2D.get('value'))\nthreshold = value.subtract(0.15).updateMask(value.lt(0.3)).unmask(0.15, False)\ngrey_and_bright = saturation.lt(ee.Image(threshold))\ncold = ee.Image(BT).lt(20)\ncloud ...
<|body_start_0|> color2D = ee.Dictionary(ee.Dictionary(color).get('2D')) saturation = ee.Image(color2D.get('saturation')) value = ee.Image(color2D.get('value')) threshold = value.subtract(0.15).updateMask(value.lt(0.3)).unmask(0.15, False) grey_and_bright = saturation.lt(ee.Image...
Finds cloud, water and valid TIR pixels
Mask
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Mask: """Finds cloud, water and valid TIR pixels""" def cloud(color, BT): """Cloud pixels are grey, bright and cold - grey and bright: 2D Saturation and Value - cold: Brightness Temperature More detail on grey and bright threshold: - Saturation always < 0.1 - if Value between 0.1 and...
stack_v2_sparse_classes_36k_train_003364
1,682
no_license
[ { "docstring": "Cloud pixels are grey, bright and cold - grey and bright: 2D Saturation and Value - cold: Brightness Temperature More detail on grey and bright threshold: - Saturation always < 0.1 - if Value between 0.1 and 0.2 then Saturation must be 0.1 less than Value - Value always > 0.1 (i.e. negative Satu...
2
stack_v2_sparse_classes_30k_train_016482
Implement the Python class `Mask` described below. Class description: Finds cloud, water and valid TIR pixels Method signatures and docstrings: - def cloud(color, BT): Cloud pixels are grey, bright and cold - grey and bright: 2D Saturation and Value - cold: Brightness Temperature More detail on grey and bright thresh...
Implement the Python class `Mask` described below. Class description: Finds cloud, water and valid TIR pixels Method signatures and docstrings: - def cloud(color, BT): Cloud pixels are grey, bright and cold - grey and bright: 2D Saturation and Value - cold: Brightness Temperature More detail on grey and bright thresh...
b57ac0c18ce37b0f71f59fc8d254fa12890090ee
<|skeleton|> class Mask: """Finds cloud, water and valid TIR pixels""" def cloud(color, BT): """Cloud pixels are grey, bright and cold - grey and bright: 2D Saturation and Value - cold: Brightness Temperature More detail on grey and bright threshold: - Saturation always < 0.1 - if Value between 0.1 and...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Mask: """Finds cloud, water and valid TIR pixels""" def cloud(color, BT): """Cloud pixels are grey, bright and cold - grey and bright: 2D Saturation and Value - cold: Brightness Temperature More detail on grey and bright threshold: - Saturation always < 0.1 - if Value between 0.1 and 0.2 then Sat...
the_stack_v2_python_sparse
bin/masks.py
YutingYao/crater_lakes
train
0
932f3b24d5242c1eea1b129d37ac3cfc0c46a2cb
[ "super().__init__(parse_line)\nself.log_type = 'log'\nself.parse_line = self._wrap_parse_line(parser_functions={self.log_type: parse_line})", "with open(file_path) as f:\n for line in f:\n log = self.parse_line(line)\n yield log", "paths = glob.iglob(filepath_pattern)\nfor file_path in paths:\n...
<|body_start_0|> super().__init__(parse_line) self.log_type = 'log' self.parse_line = self._wrap_parse_line(parser_functions={self.log_type: parse_line}) <|end_body_0|> <|body_start_1|> with open(file_path) as f: for line in f: log = self.parse_line(line) ...
Class to parse the log files.
Parser
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Parser: """Class to parse the log files.""" def __init__(self, parse_line: ParseLineFunctionType=parse_json): """Class to parse the log files. Args: parse_line (ParseLineFunctionType): Function to parse a line in the log file. The function should return None if the line is not a vali...
stack_v2_sparse_classes_36k_train_003365
3,718
permissive
[ { "docstring": "Class to parse the log files. Args: parse_line (ParseLineFunctionType): Function to parse a line in the log file. The function should return None if the line is not a valid log statement (eg error messages). Defaults to parse_json.", "name": "__init__", "signature": "def __init__(self, p...
5
stack_v2_sparse_classes_30k_train_005579
Implement the Python class `Parser` described below. Class description: Class to parse the log files. Method signatures and docstrings: - def __init__(self, parse_line: ParseLineFunctionType=parse_json): Class to parse the log files. Args: parse_line (ParseLineFunctionType): Function to parse a line in the log file. ...
Implement the Python class `Parser` described below. Class description: Class to parse the log files. Method signatures and docstrings: - def __init__(self, parse_line: ParseLineFunctionType=parse_json): Class to parse the log files. Args: parse_line (ParseLineFunctionType): Function to parse a line in the log file. ...
8914c4a408053e0df11e3d5235f618e88ec43a51
<|skeleton|> class Parser: """Class to parse the log files.""" def __init__(self, parse_line: ParseLineFunctionType=parse_json): """Class to parse the log files. Args: parse_line (ParseLineFunctionType): Function to parse a line in the log file. The function should return None if the line is not a vali...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Parser: """Class to parse the log files.""" def __init__(self, parse_line: ParseLineFunctionType=parse_json): """Class to parse the log files. Args: parse_line (ParseLineFunctionType): Function to parse a line in the log file. The function should return None if the line is not a valid log stateme...
the_stack_v2_python_sparse
ml_logger/parser/log.py
shagunsodhani/ml-logger
train
18
ecde8275229eb326b3b62dec9e27fd0dc93220ec
[ "shared_weight_names = []\nfor shared_weight_name, repeated_node_list in GlobalContext().repeated_weights.items():\n if node.onnx_name in repeated_node_list:\n shared_weight_names.append(shared_weight_name)\nreturn shared_weight_names", "default_weight_name = f'passthrough_w_{module_to_be_registered.sha...
<|body_start_0|> shared_weight_names = [] for shared_weight_name, repeated_node_list in GlobalContext().repeated_weights.items(): if node.onnx_name in repeated_node_list: shared_weight_names.append(shared_weight_name) return shared_weight_names <|end_body_0|> <|body_...
Helper function to process shared weights.
SharedWeightHelper
[ "Apache-2.0", "MIT", "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SharedWeightHelper: """Helper function to process shared weights.""" def check_node_has_shared_weight(node: NodeStruct): """Check the node has shared weight and return all of them. Args: node (NodeStruct): NodeStruct instance. Returns: list, a list of shared weight onnx names""" ...
stack_v2_sparse_classes_36k_train_003366
4,646
permissive
[ { "docstring": "Check the node has shared weight and return all of them. Args: node (NodeStruct): NodeStruct instance. Returns: list, a list of shared weight onnx names", "name": "check_node_has_shared_weight", "signature": "def check_node_has_shared_weight(node: NodeStruct)" }, { "docstring": "...
5
stack_v2_sparse_classes_30k_train_007300
Implement the Python class `SharedWeightHelper` described below. Class description: Helper function to process shared weights. Method signatures and docstrings: - def check_node_has_shared_weight(node: NodeStruct): Check the node has shared weight and return all of them. Args: node (NodeStruct): NodeStruct instance. ...
Implement the Python class `SharedWeightHelper` described below. Class description: Helper function to process shared weights. Method signatures and docstrings: - def check_node_has_shared_weight(node: NodeStruct): Check the node has shared weight and return all of them. Args: node (NodeStruct): NodeStruct instance. ...
9073ef36d7f750c72262c87779e77e7c3602dd83
<|skeleton|> class SharedWeightHelper: """Helper function to process shared weights.""" def check_node_has_shared_weight(node: NodeStruct): """Check the node has shared weight and return all of them. Args: node (NodeStruct): NodeStruct instance. Returns: list, a list of shared weight onnx names""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SharedWeightHelper: """Helper function to process shared weights.""" def check_node_has_shared_weight(node: NodeStruct): """Check the node has shared weight and return all of them. Args: node (NodeStruct): NodeStruct instance. Returns: list, a list of shared weight onnx names""" shared_we...
the_stack_v2_python_sparse
mindinsight/mindconverter/graph_based_converter/generator/shared_weights.py
nimengliusha/mindinsight
train
0
55a7236e91d68b4fea2ab75fa0ca764aeff6c166
[ "self.audio_type = audio_type\nself.audio_format = audio_format\nif audio_type in SERIALIZABLE_AUDIO_TYPES:\n self.audio = raw_data if isinstance(raw_data, io.BytesIO) else io.BytesIO(raw_data)\n self.duration = read_duration(audio_type, self.audio)\nelse:\n self.audio = raw_data\n if self.audio_format ...
<|body_start_0|> self.audio_type = audio_type self.audio_format = audio_format if audio_type in SERIALIZABLE_AUDIO_TYPES: self.audio = raw_data if isinstance(raw_data, io.BytesIO) else io.BytesIO(raw_data) self.duration = read_duration(audio_type, self.audio) else...
Represents in-memory audio data of a certain (convertible) representation. Attributes: audio_type (str): See `__init__`. audio_format (tuple:(int, int, int)): See `__init__`. audio (obj): Audio data represented as indicated by `audio_type` duration (float): Audio duration of the sample in seconds
Sample
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "CC-BY-4.0", "CC-BY-SA-3.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Sample: """Represents in-memory audio data of a certain (convertible) representation. Attributes: audio_type (str): See `__init__`. audio_format (tuple:(int, int, int)): See `__init__`. audio (obj): Audio data represented as indicated by `audio_type` duration (float): Audio duration of the sample...
stack_v2_sparse_classes_36k_train_003367
15,981
permissive
[ { "docstring": "Creates a Sample from a raw audio representation. :param audio_type: Audio data representation type CSupported types: - AUDIO_TYPE_OPUS: Memory file representation (BytesIO) of Opus encoded audio wrapped by a custom container format (used in SDBs) - AUDIO_TYPE_WAV: Memory file representation (By...
2
stack_v2_sparse_classes_30k_train_020052
Implement the Python class `Sample` described below. Class description: Represents in-memory audio data of a certain (convertible) representation. Attributes: audio_type (str): See `__init__`. audio_format (tuple:(int, int, int)): See `__init__`. audio (obj): Audio data represented as indicated by `audio_type` duratio...
Implement the Python class `Sample` described below. Class description: Represents in-memory audio data of a certain (convertible) representation. Attributes: audio_type (str): See `__init__`. audio_format (tuple:(int, int, int)): See `__init__`. audio (obj): Audio data represented as indicated by `audio_type` duratio...
93c4a42c95cd610c76dbd98de480dbb21f484c31
<|skeleton|> class Sample: """Represents in-memory audio data of a certain (convertible) representation. Attributes: audio_type (str): See `__init__`. audio_format (tuple:(int, int, int)): See `__init__`. audio (obj): Audio data represented as indicated by `audio_type` duration (float): Audio duration of the sample...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Sample: """Represents in-memory audio data of a certain (convertible) representation. Attributes: audio_type (str): See `__init__`. audio_format (tuple:(int, int, int)): See `__init__`. audio (obj): Audio data represented as indicated by `audio_type` duration (float): Audio duration of the sample in seconds""...
the_stack_v2_python_sparse
galvasr2/align/audio.py
Ciroye/peoples-speech
train
0
4026ec5ce846e765bd87dbd5b56a0e05331efdff
[ "s2t.calculate_prensors\ns2t.calculate_prensors_with_graph\ns2t.get_default_options\ns2t.get_options_with_minimal_checks\ns2t.calculate_prensors_with_source_paths\ns2t.create_expression_from_prensor\ns2t.create_expression_from_file_descriptor_set\ns2t.create_expression_from_proto\ns2t.Expression\ns2t.create_path\ns...
<|body_start_0|> s2t.calculate_prensors s2t.calculate_prensors_with_graph s2t.get_default_options s2t.get_options_with_minimal_checks s2t.calculate_prensors_with_source_paths s2t.create_expression_from_prensor s2t.create_expression_from_file_descriptor_set ...
Struct2tensorModuleTest
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Struct2tensorModuleTest: def test_importing_struct2tensor_modules(self): """This tests that the exposed packages in root __init__.py are found.""" <|body_0|> def test_importing_expression_impl_modules(self): """This tests that the expression_impl/__init__.py imports ...
stack_v2_sparse_classes_36k_train_003368
2,247
permissive
[ { "docstring": "This tests that the exposed packages in root __init__.py are found.", "name": "test_importing_struct2tensor_modules", "signature": "def test_importing_struct2tensor_modules(self)" }, { "docstring": "This tests that the expression_impl/__init__.py imports are found.", "name": ...
2
stack_v2_sparse_classes_30k_train_019293
Implement the Python class `Struct2tensorModuleTest` described below. Class description: Implement the Struct2tensorModuleTest class. Method signatures and docstrings: - def test_importing_struct2tensor_modules(self): This tests that the exposed packages in root __init__.py are found. - def test_importing_expression_...
Implement the Python class `Struct2tensorModuleTest` described below. Class description: Implement the Struct2tensorModuleTest class. Method signatures and docstrings: - def test_importing_struct2tensor_modules(self): This tests that the exposed packages in root __init__.py are found. - def test_importing_expression_...
86d8676ac295697853be8a194460e4d71de3990f
<|skeleton|> class Struct2tensorModuleTest: def test_importing_struct2tensor_modules(self): """This tests that the exposed packages in root __init__.py are found.""" <|body_0|> def test_importing_expression_impl_modules(self): """This tests that the expression_impl/__init__.py imports ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Struct2tensorModuleTest: def test_importing_struct2tensor_modules(self): """This tests that the exposed packages in root __init__.py are found.""" s2t.calculate_prensors s2t.calculate_prensors_with_graph s2t.get_default_options s2t.get_options_with_minimal_checks ...
the_stack_v2_python_sparse
struct2tensor/struct2tensor_module_test.py
google/struct2tensor
train
36
02ddcea71a7a6d1382e3d9302b3fb2c3d314efd0
[ "cls.store_soc = None\nexcept_ = ('__classcell__', '__doc__')\nfor key, val in attr_dict.items():\n assert not isinstance(val, socket.socket), 'Создание сокетов на уровне классов запрещенно'\n if key in except_ or isinstance(val, PortDescr):\n continue\n instrs = tuple(dis.Bytecode(val))\n glob_s...
<|body_start_0|> cls.store_soc = None except_ = ('__classcell__', '__doc__') for key, val in attr_dict.items(): assert not isinstance(val, socket.socket), 'Создание сокетов на уровне классов запрещенно' if key in except_ or isinstance(val, PortDescr): cont...
Верификатор клиента.
ClientVerifier
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ClientVerifier: """Верификатор клиента.""" def __new__(cls, name, bases, attr_dict): """Тут находим объявление сокета и проверяем его инициализацию. кэшируем имя атрибута""" <|body_0|> def __init__(cls, name, bases, attr_dict): """Т.к в предыдущей функции использ...
stack_v2_sparse_classes_36k_train_003369
2,962
permissive
[ { "docstring": "Тут находим объявление сокета и проверяем его инициализацию. кэшируем имя атрибута", "name": "__new__", "signature": "def __new__(cls, name, bases, attr_dict)" }, { "docstring": "Т.к в предыдущей функции использовался дикт. Мы могли пропустить вызовы интересующего метода тут еще ...
2
stack_v2_sparse_classes_30k_train_016338
Implement the Python class `ClientVerifier` described below. Class description: Верификатор клиента. Method signatures and docstrings: - def __new__(cls, name, bases, attr_dict): Тут находим объявление сокета и проверяем его инициализацию. кэшируем имя атрибута - def __init__(cls, name, bases, attr_dict): Т.к в преды...
Implement the Python class `ClientVerifier` described below. Class description: Верификатор клиента. Method signatures and docstrings: - def __new__(cls, name, bases, attr_dict): Тут находим объявление сокета и проверяем его инициализацию. кэшируем имя атрибута - def __init__(cls, name, bases, attr_dict): Т.к в преды...
d83fe60bc20535adb969d72f52aaca5cf4b00c6b
<|skeleton|> class ClientVerifier: """Верификатор клиента.""" def __new__(cls, name, bases, attr_dict): """Тут находим объявление сокета и проверяем его инициализацию. кэшируем имя атрибута""" <|body_0|> def __init__(cls, name, bases, attr_dict): """Т.к в предыдущей функции использ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ClientVerifier: """Верификатор клиента.""" def __new__(cls, name, bases, attr_dict): """Тут находим объявление сокета и проверяем его инициализацию. кэшируем имя атрибута""" cls.store_soc = None except_ = ('__classcell__', '__doc__') for key, val in attr_dict.items(): ...
the_stack_v2_python_sparse
talkative_client/talkative_client/metaclasses.py
mom1/messager
train
0
4d7dfbd2850a6f95d8e71eeee582e935f8dea9ef
[ "group = Group.objects.get(name='marketer')\nusers = group.user_set.all()\nchoices = [(user.id, _('%s' % (user.username,))) for user in users]\nreturn choices", "if self.value():\n users = MarketingRelationship.objects.filter(parent_marketer__id=self.value()).values('user')\n return queryset.filter(user__id...
<|body_start_0|> group = Group.objects.get(name='marketer') users = group.user_set.all() choices = [(user.id, _('%s' % (user.username,))) for user in users] return choices <|end_body_0|> <|body_start_1|> if self.value(): users = MarketingRelationship.objects.filter(p...
OrderInfoListFilter
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OrderInfoListFilter: def lookups(self, request, model_admin): """Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The second element is the human-readable name for the option that will appear in the right sideb...
stack_v2_sparse_classes_36k_train_003370
8,580
no_license
[ { "docstring": "Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The second element is the human-readable name for the option that will appear in the right sidebar.", "name": "lookups", "signature": "def lookups(self, request,...
2
null
Implement the Python class `OrderInfoListFilter` described below. Class description: Implement the OrderInfoListFilter class. Method signatures and docstrings: - def lookups(self, request, model_admin): Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the...
Implement the Python class `OrderInfoListFilter` described below. Class description: Implement the OrderInfoListFilter class. Method signatures and docstrings: - def lookups(self, request, model_admin): Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the...
25a568c5203d05a00bce139d084da6d7622b9956
<|skeleton|> class OrderInfoListFilter: def lookups(self, request, model_admin): """Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The second element is the human-readable name for the option that will appear in the right sideb...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OrderInfoListFilter: def lookups(self, request, model_admin): """Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The second element is the human-readable name for the option that will appear in the right sidebar.""" ...
the_stack_v2_python_sparse
apps/trade/admin.py
846468230/store
train
0
7eb543657b9b6ea7194052328684a42a8a4d4285
[ "records = []\nfor i in range(start_id, record_count + start_id):\n records.append(self.__create_record(i))\n self.persist_record([str(i)])\nself.persist_records('counterparties')\nreturn records", "record = {'counterparty_id': current_id, 'book': self.create_random_string(5, include_numbers=False), 'time_s...
<|body_start_0|> records = [] for i in range(start_id, record_count + start_id): records.append(self.__create_record(i)) self.persist_record([str(i)]) self.persist_records('counterparties') return records <|end_body_0|> <|body_start_1|> record = {'counter...
A class to create counterparties. Create method will create a set amount of positions.
CounterpartyFactory
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CounterpartyFactory: """A class to create counterparties. Create method will create a set amount of positions.""" def create(self, record_count, start_id, lock=None): """Create a set number of counterparties. Parameters ---------- record_count : int Number of counterparties to create...
stack_v2_sparse_classes_36k_train_003371
1,509
no_license
[ { "docstring": "Create a set number of counterparties. Parameters ---------- record_count : int Number of counterparties to create start_id : int Starting id to create from Returns ------- List Containing 'record_count' counterparties", "name": "create", "signature": "def create(self, record_count, star...
2
stack_v2_sparse_classes_30k_train_016843
Implement the Python class `CounterpartyFactory` described below. Class description: A class to create counterparties. Create method will create a set amount of positions. Method signatures and docstrings: - def create(self, record_count, start_id, lock=None): Create a set number of counterparties. Parameters -------...
Implement the Python class `CounterpartyFactory` described below. Class description: A class to create counterparties. Create method will create a set amount of positions. Method signatures and docstrings: - def create(self, record_count, start_id, lock=None): Create a set number of counterparties. Parameters -------...
1d8257bdd9e4533161f64e114f57312905adad5c
<|skeleton|> class CounterpartyFactory: """A class to create counterparties. Create method will create a set amount of positions.""" def create(self, record_count, start_id, lock=None): """Create a set number of counterparties. Parameters ---------- record_count : int Number of counterparties to create...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CounterpartyFactory: """A class to create counterparties. Create method will create a set amount of positions.""" def create(self, record_count, start_id, lock=None): """Create a set number of counterparties. Parameters ---------- record_count : int Number of counterparties to create start_id : i...
the_stack_v2_python_sparse
src/domainobjectfactories/tampa_poc/counterparty_factory.py
galatea-associates/fuse-test-data-gen
train
0
b84a28c9fdfd93806671569edce43bf3596106d0
[ "global parts_list_page, admin_page\nparts_list_page = PartsListPage(self.driver)\nadmin_page = AdminPage(self.driver)\nadmin_page.into_subsystem('业务管理')\nadmin_page.select_menu('首页/渠道终端管理/设备管理')", "admin_page.select_menu('T配件列表')\nparts_list_page.simple_query_parts(store='海南省')\nassert '海南省' in parts_list_page.r...
<|body_start_0|> global parts_list_page, admin_page parts_list_page = PartsListPage(self.driver) admin_page = AdminPage(self.driver) admin_page.into_subsystem('业务管理') admin_page.select_menu('首页/渠道终端管理/设备管理') <|end_body_0|> <|body_start_1|> admin_page.select_menu('T配件列表')...
TestPartsList
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestPartsList: def set_up(self): """前置操作 :return:""" <|body_0|> def test_query_parts_list(self, set_up): """查询配件列表""" <|body_1|> def test_reset_query_parts_list(self): """重置查询配件列表""" <|body_2|> def test_click_more_query_parts_list(se...
stack_v2_sparse_classes_36k_train_003372
2,489
no_license
[ { "docstring": "前置操作 :return:", "name": "set_up", "signature": "def set_up(self)" }, { "docstring": "查询配件列表", "name": "test_query_parts_list", "signature": "def test_query_parts_list(self, set_up)" }, { "docstring": "重置查询配件列表", "name": "test_reset_query_parts_list", "sign...
6
null
Implement the Python class `TestPartsList` described below. Class description: Implement the TestPartsList class. Method signatures and docstrings: - def set_up(self): 前置操作 :return: - def test_query_parts_list(self, set_up): 查询配件列表 - def test_reset_query_parts_list(self): 重置查询配件列表 - def test_click_more_query_parts_li...
Implement the Python class `TestPartsList` described below. Class description: Implement the TestPartsList class. Method signatures and docstrings: - def set_up(self): 前置操作 :return: - def test_query_parts_list(self, set_up): 查询配件列表 - def test_reset_query_parts_list(self): 重置查询配件列表 - def test_click_more_query_parts_li...
86d1b085af2d3808ac8472d541f4bf26d26591e0
<|skeleton|> class TestPartsList: def set_up(self): """前置操作 :return:""" <|body_0|> def test_query_parts_list(self, set_up): """查询配件列表""" <|body_1|> def test_reset_query_parts_list(self): """重置查询配件列表""" <|body_2|> def test_click_more_query_parts_list(se...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestPartsList: def set_up(self): """前置操作 :return:""" global parts_list_page, admin_page parts_list_page = PartsListPage(self.driver) admin_page = AdminPage(self.driver) admin_page.into_subsystem('业务管理') admin_page.select_menu('首页/渠道终端管理/设备管理') def test_quer...
the_stack_v2_python_sparse
src/cases/business_manage/channel_device_manage/device_manage/test_parts_list_page_310.py
102244653/SeleniumByPython
train
2
5c721f287edb7eb2fb8c6b39ec96021c772c3a5b
[ "for _key, _value in self.items():\n if isinstance(_key, Iterable) and (not isinstance(_key, str)):\n left, right = _key\n if left <= key <= right:\n self[key] = _value\n return _value\nraise KeyError('Cannot find {} in RangeDict'.format(key))", "if key in self:\n return ...
<|body_start_0|> for _key, _value in self.items(): if isinstance(_key, Iterable) and (not isinstance(_key, str)): left, right = _key if left <= key <= right: self[key] = _value return _value raise KeyError('Cannot find {...
Defines a dictionary that can use immutable iterables such as tuples, as keys so that anything in the range can be queried from the dictionary. Example: >>> range_dict = RangeDict() >>> range_dict[(100,105)] = 5 >>> range_dict[107] = 3 >>> range_dict[101] 5 >>> range_dict.get(101) 5 >>> range_dict.get(107) 3 >>> range_...
RangeDict
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RangeDict: """Defines a dictionary that can use immutable iterables such as tuples, as keys so that anything in the range can be queried from the dictionary. Example: >>> range_dict = RangeDict() >>> range_dict[(100,105)] = 5 >>> range_dict[107] = 3 >>> range_dict[101] 5 >>> range_dict.get(101) 5...
stack_v2_sparse_classes_36k_train_003373
5,460
no_license
[ { "docstring": "Method to override inbuilt :func:`__missing__`, check if `key` is part of `Iterable` range if if is insert `key` in the dict with value of `Iterable` range and return same value. . Parameters: key (:class:`int`): Key to be searched in the dict. Returns: :class:`int` or :class:`str` or :class:`tu...
2
stack_v2_sparse_classes_30k_train_018496
Implement the Python class `RangeDict` described below. Class description: Defines a dictionary that can use immutable iterables such as tuples, as keys so that anything in the range can be queried from the dictionary. Example: >>> range_dict = RangeDict() >>> range_dict[(100,105)] = 5 >>> range_dict[107] = 3 >>> rang...
Implement the Python class `RangeDict` described below. Class description: Defines a dictionary that can use immutable iterables such as tuples, as keys so that anything in the range can be queried from the dictionary. Example: >>> range_dict = RangeDict() >>> range_dict[(100,105)] = 5 >>> range_dict[107] = 3 >>> rang...
ffb2593ef79426e1a708c4c9f1464eb5a19e4a16
<|skeleton|> class RangeDict: """Defines a dictionary that can use immutable iterables such as tuples, as keys so that anything in the range can be queried from the dictionary. Example: >>> range_dict = RangeDict() >>> range_dict[(100,105)] = 5 >>> range_dict[107] = 3 >>> range_dict[101] 5 >>> range_dict.get(101) 5...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RangeDict: """Defines a dictionary that can use immutable iterables such as tuples, as keys so that anything in the range can be queried from the dictionary. Example: >>> range_dict = RangeDict() >>> range_dict[(100,105)] = 5 >>> range_dict[107] = 3 >>> range_dict[101] 5 >>> range_dict.get(101) 5 >>> range_di...
the_stack_v2_python_sparse
hdx_ahcd/utils/utils.py
vshia/hdx-data-extraction-ahcd
train
0
70f9553d80bd7ebd981f9f855e99f0ce93ffd8b1
[ "if len(nums) < 2:\n return True\none_chance = False\nfor i in range(len(nums) - 1):\n if nums[i] > nums[i + 1]:\n if not one_chance:\n one_chance = True\n else:\n return False\nreturn True", "if len(nums) < 2:\n return True\nlast = nums[0]\nindex = 1\none_chance = Fal...
<|body_start_0|> if len(nums) < 2: return True one_chance = False for i in range(len(nums) - 1): if nums[i] > nums[i + 1]: if not one_chance: one_chance = True else: return False return True <...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def _checkPossibility(self, nums): """:type nums: List[int] :rtype: bool""" <|body_0|> def __checkPossibility(self, nums): """:type nums: List[int] :rtype: bool""" <|body_1|> def checkPossibility(self, nums): """:type nums: List[int] :r...
stack_v2_sparse_classes_36k_train_003374
3,075
permissive
[ { "docstring": ":type nums: List[int] :rtype: bool", "name": "_checkPossibility", "signature": "def _checkPossibility(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: bool", "name": "__checkPossibility", "signature": "def __checkPossibility(self, nums)" }, { "docstri...
3
stack_v2_sparse_classes_30k_train_002851
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def _checkPossibility(self, nums): :type nums: List[int] :rtype: bool - def __checkPossibility(self, nums): :type nums: List[int] :rtype: bool - def checkPossibility(self, nums):...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def _checkPossibility(self, nums): :type nums: List[int] :rtype: bool - def __checkPossibility(self, nums): :type nums: List[int] :rtype: bool - def checkPossibility(self, nums):...
0dd67edca4e0b0323cb5a7239f02ea46383cd15a
<|skeleton|> class Solution: def _checkPossibility(self, nums): """:type nums: List[int] :rtype: bool""" <|body_0|> def __checkPossibility(self, nums): """:type nums: List[int] :rtype: bool""" <|body_1|> def checkPossibility(self, nums): """:type nums: List[int] :r...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def _checkPossibility(self, nums): """:type nums: List[int] :rtype: bool""" if len(nums) < 2: return True one_chance = False for i in range(len(nums) - 1): if nums[i] > nums[i + 1]: if not one_chance: one_cha...
the_stack_v2_python_sparse
665.non-decreasing-array.py
windard/leeeeee
train
0
e3444f0f65c68ffc8c264445b411017eb4b67aeb
[ "super().__init__(whatsThis=whats_this, itemChanged=self._part_changed)\nself._page = page\nself.setHeaderLabels([title])", "page = self._page\nproject = page.project\nparts = project.parts\nif itm.checkState(col) == Qt.Checked:\n parts.append(itm.part_name)\nelse:\n parts.remove(itm.part_name)\npage.update...
<|body_start_0|> super().__init__(whatsThis=whats_this, itemChanged=self._part_changed) self._page = page self.setHeaderLabels([title]) <|end_body_0|> <|body_start_1|> page = self._page project = page.project parts = project.parts if itm.checkState(col) == Qt.Che...
An editor for selecting a number of interdependent parts and packages.
PartsEditor
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PartsEditor: """An editor for selecting a number of interdependent parts and packages.""" def __init__(self, page, title, whats_this): """Initialise the editor.""" <|body_0|> def _part_changed(self, itm, col): """Invoked when a part changes.""" <|body_1|>...
stack_v2_sparse_classes_36k_train_003375
13,213
permissive
[ { "docstring": "Initialise the editor.", "name": "__init__", "signature": "def __init__(self, page, title, whats_this)" }, { "docstring": "Invoked when a part changes.", "name": "_part_changed", "signature": "def _part_changed(self, itm, col)" } ]
2
stack_v2_sparse_classes_30k_train_007905
Implement the Python class `PartsEditor` described below. Class description: An editor for selecting a number of interdependent parts and packages. Method signatures and docstrings: - def __init__(self, page, title, whats_this): Initialise the editor. - def _part_changed(self, itm, col): Invoked when a part changes.
Implement the Python class `PartsEditor` described below. Class description: An editor for selecting a number of interdependent parts and packages. Method signatures and docstrings: - def __init__(self, page, title, whats_this): Initialise the editor. - def _part_changed(self, itm, col): Invoked when a part changes. ...
4ed2b1b9a2407afcbffdf304020d42b81c4c8cdc
<|skeleton|> class PartsEditor: """An editor for selecting a number of interdependent parts and packages.""" def __init__(self, page, title, whats_this): """Initialise the editor.""" <|body_0|> def _part_changed(self, itm, col): """Invoked when a part changes.""" <|body_1|>...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PartsEditor: """An editor for selecting a number of interdependent parts and packages.""" def __init__(self, page, title, whats_this): """Initialise the editor.""" super().__init__(whatsThis=whats_this, itemChanged=self._part_changed) self._page = page self.setHeaderLabels...
the_stack_v2_python_sparse
note/demo/pyqt_demo/pyqtdeploy-3.3.0/pyqtdeploy/gui/packages_page.py
onsunsl/onsunsl.github.io
train
1
ac941628f5159146ba3fc3e85c36d4294c8eceee
[ "super(monitor, self).pre_run(step, level_number)\nL = step.levels[0]\nbx_max = np.amax(abs(L.u[0][..., 0]))\nself.add_to_stats(process=step.status.slot, time=L.time, level=-1, iter=step.status.iter, sweep=L.status.sweep, type='bx_max', value=bx_max)", "super(monitor, self).post_step(step, level_number)\nL = step...
<|body_start_0|> super(monitor, self).pre_run(step, level_number) L = step.levels[0] bx_max = np.amax(abs(L.u[0][..., 0])) self.add_to_stats(process=step.status.slot, time=L.time, level=-1, iter=step.status.iter, sweep=L.status.sweep, type='bx_max', value=bx_max) <|end_body_0|> <|body_s...
monitor
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class monitor: def pre_run(self, step, level_number): """Overwrite standard post step hook Args: step (pySDC.Step.step): the current step level_number (int): the current level number""" <|body_0|> def post_step(self, step, level_number): """Overwrite standard post step hoo...
stack_v2_sparse_classes_36k_train_003376
1,481
permissive
[ { "docstring": "Overwrite standard post step hook Args: step (pySDC.Step.step): the current step level_number (int): the current level number", "name": "pre_run", "signature": "def pre_run(self, step, level_number)" }, { "docstring": "Overwrite standard post step hook Args: step (pySDC.Step.step...
2
null
Implement the Python class `monitor` described below. Class description: Implement the monitor class. Method signatures and docstrings: - def pre_run(self, step, level_number): Overwrite standard post step hook Args: step (pySDC.Step.step): the current step level_number (int): the current level number - def post_step...
Implement the Python class `monitor` described below. Class description: Implement the monitor class. Method signatures and docstrings: - def pre_run(self, step, level_number): Overwrite standard post step hook Args: step (pySDC.Step.step): the current step level_number (int): the current level number - def post_step...
1a51834bedffd4472e344bed28f4d766614b1537
<|skeleton|> class monitor: def pre_run(self, step, level_number): """Overwrite standard post step hook Args: step (pySDC.Step.step): the current step level_number (int): the current level number""" <|body_0|> def post_step(self, step, level_number): """Overwrite standard post step hoo...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class monitor: def pre_run(self, step, level_number): """Overwrite standard post step hook Args: step (pySDC.Step.step): the current step level_number (int): the current level number""" super(monitor, self).pre_run(step, level_number) L = step.levels[0] bx_max = np.amax(abs(L.u[0][.....
the_stack_v2_python_sparse
pySDC/playgrounds/deprecated/Dedalus/Dynamo_monitor.py
Parallel-in-Time/pySDC
train
30
fe15c9bfa4e5a2c0314ab4fba28d5c206524fcdd
[ "super(MultiheadAttentionContainer, self).__init__()\nself.nhead = nhead\nself.in_proj_container = in_proj_container\nself.attention_layer = attention_layer\nself.out_proj = out_proj\nself.batch_first = batch_first", "if self.batch_first:\n query, key, value = (query.transpose(-3, -2), key.transpose(-3, -2), v...
<|body_start_0|> super(MultiheadAttentionContainer, self).__init__() self.nhead = nhead self.in_proj_container = in_proj_container self.attention_layer = attention_layer self.out_proj = out_proj self.batch_first = batch_first <|end_body_0|> <|body_start_1|> if se...
MultiheadAttentionContainer
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MultiheadAttentionContainer: def __init__(self, nhead, in_proj_container, attention_layer, out_proj, batch_first=False) -> None: """A multi-head attention container Args: nhead: the number of heads in the multiheadattention model in_proj_container: A container of multi-head in-projection...
stack_v2_sparse_classes_36k_train_003377
13,955
permissive
[ { "docstring": "A multi-head attention container Args: nhead: the number of heads in the multiheadattention model in_proj_container: A container of multi-head in-projection linear layers (a.k.a nn.Linear). attention_layer: The custom attention layer. The input sent from MHA container to the attention layer is i...
2
stack_v2_sparse_classes_30k_train_021488
Implement the Python class `MultiheadAttentionContainer` described below. Class description: Implement the MultiheadAttentionContainer class. Method signatures and docstrings: - def __init__(self, nhead, in_proj_container, attention_layer, out_proj, batch_first=False) -> None: A multi-head attention container Args: n...
Implement the Python class `MultiheadAttentionContainer` described below. Class description: Implement the MultiheadAttentionContainer class. Method signatures and docstrings: - def __init__(self, nhead, in_proj_container, attention_layer, out_proj, batch_first=False) -> None: A multi-head attention container Args: n...
45e4b8ca3615016625de15326a14668c8b58595d
<|skeleton|> class MultiheadAttentionContainer: def __init__(self, nhead, in_proj_container, attention_layer, out_proj, batch_first=False) -> None: """A multi-head attention container Args: nhead: the number of heads in the multiheadattention model in_proj_container: A container of multi-head in-projection...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MultiheadAttentionContainer: def __init__(self, nhead, in_proj_container, attention_layer, out_proj, batch_first=False) -> None: """A multi-head attention container Args: nhead: the number of heads in the multiheadattention model in_proj_container: A container of multi-head in-projection linear layers...
the_stack_v2_python_sparse
torchtext/nn/modules/multiheadattention.py
pytorch/text
train
3,640
f06cb35527d7a7276caeb09b9a543b2c3e54f776
[ "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')", "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')" ]
<|body_start_0|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') <|end_body_0|> <|body_start_1|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not im...
Missing associated documentation comment in .proto file.
RVizServicer
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RVizServicer: """Missing associated documentation comment in .proto file.""" def run_code(self, request, context): """Missing associated documentation comment in .proto file.""" <|body_0|> def create_instance(self, request, context): """Missing associated documen...
stack_v2_sparse_classes_36k_train_003378
3,787
permissive
[ { "docstring": "Missing associated documentation comment in .proto file.", "name": "run_code", "signature": "def run_code(self, request, context)" }, { "docstring": "Missing associated documentation comment in .proto file.", "name": "create_instance", "signature": "def create_instance(se...
2
stack_v2_sparse_classes_30k_train_017493
Implement the Python class `RVizServicer` described below. Class description: Missing associated documentation comment in .proto file. Method signatures and docstrings: - def run_code(self, request, context): Missing associated documentation comment in .proto file. - def create_instance(self, request, context): Missi...
Implement the Python class `RVizServicer` described below. Class description: Missing associated documentation comment in .proto file. Method signatures and docstrings: - def run_code(self, request, context): Missing associated documentation comment in .proto file. - def create_instance(self, request, context): Missi...
03c9e59779a30e2f6dedf2732ad8a46e6ac3c9f0
<|skeleton|> class RVizServicer: """Missing associated documentation comment in .proto file.""" def run_code(self, request, context): """Missing associated documentation comment in .proto file.""" <|body_0|> def create_instance(self, request, context): """Missing associated documen...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RVizServicer: """Missing associated documentation comment in .proto file.""" def run_code(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') ...
the_stack_v2_python_sparse
visualization/panda/rpc/rviz_pb2_grpc.py
kazuki0824/wrs
train
1
4426add7b5f9689b4e400e9186adacc6f6ed3704
[ "super(ESPCN, self).__init__()\nself.feature_map_layer = nn.Sequential(nn.Conv2d(in_channels=num_channels, kernel_size=(5, 5), out_channels=64, padding=(2, 2)), nn.Tanh(), nn.Conv2d(in_channels=64, kernel_size=(3, 3), out_channels=32, padding=(1, 1)), nn.Tanh())\nself.sub_pixel_layer = nn.Sequential(nn.Conv2d(in_ch...
<|body_start_0|> super(ESPCN, self).__init__() self.feature_map_layer = nn.Sequential(nn.Conv2d(in_channels=num_channels, kernel_size=(5, 5), out_channels=64, padding=(2, 2)), nn.Tanh(), nn.Conv2d(in_channels=64, kernel_size=(3, 3), out_channels=32, padding=(1, 1)), nn.Tanh()) self.sub_pixel_lay...
ESPCN
[ "GPL-1.0-or-later", "MIT", "Apache-2.0", "BSD-2-Clause", "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ESPCN: def __init__(self, num_channels, scaling_factor): """ESPCN Model class :param num_channels (int): Number of channels in input image :param scaling_factor (int): Factor to scale-up the input image by""" <|body_0|> def forward(self, x): """:param x: input image ...
stack_v2_sparse_classes_36k_train_003379
4,204
permissive
[ { "docstring": "ESPCN Model class :param num_channels (int): Number of channels in input image :param scaling_factor (int): Factor to scale-up the input image by", "name": "__init__", "signature": "def __init__(self, num_channels, scaling_factor)" }, { "docstring": ":param x: input image :return...
2
stack_v2_sparse_classes_30k_train_011856
Implement the Python class `ESPCN` described below. Class description: Implement the ESPCN class. Method signatures and docstrings: - def __init__(self, num_channels, scaling_factor): ESPCN Model class :param num_channels (int): Number of channels in input image :param scaling_factor (int): Factor to scale-up the inp...
Implement the Python class `ESPCN` described below. Class description: Implement the ESPCN class. Method signatures and docstrings: - def __init__(self, num_channels, scaling_factor): ESPCN Model class :param num_channels (int): Number of channels in input image :param scaling_factor (int): Factor to scale-up the inp...
92acc188d3a0f634de58463b6676e70df83ef808
<|skeleton|> class ESPCN: def __init__(self, num_channels, scaling_factor): """ESPCN Model class :param num_channels (int): Number of channels in input image :param scaling_factor (int): Factor to scale-up the input image by""" <|body_0|> def forward(self, x): """:param x: input image ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ESPCN: def __init__(self, num_channels, scaling_factor): """ESPCN Model class :param num_channels (int): Number of channels in input image :param scaling_factor (int): Factor to scale-up the input image by""" super(ESPCN, self).__init__() self.feature_map_layer = nn.Sequential(nn.Conv2...
the_stack_v2_python_sparse
PyTorch/dev/cv/image_classification/ESPCN_ID2919_for_PyTorch/model.py
Ascend/ModelZoo-PyTorch
train
23
dd1b2ab3685550b08a033c006d0eed383876b1b6
[ "def quick_sort(l, r):\n if l >= r:\n return\n i, j = (l, r)\n while i < j:\n while strs[j] + strs[l] >= strs[l] + strs[j] and i < j:\n j -= 1\n while strs[i] + strs[l] <= strs[l] + strs[i] and i < j:\n i += 1\n strs[i], strs[j] = (strs[j], strs[i])\n st...
<|body_start_0|> def quick_sort(l, r): if l >= r: return i, j = (l, r) while i < j: while strs[j] + strs[l] >= strs[l] + strs[j] and i < j: j -= 1 while strs[i] + strs[l] <= strs[l] + strs[i] and i < j: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def minNumber(self, nums: List[int]) -> str: """按照字典序,小的排前面 对于字符串 a,b 如果 a+b > b+a b字典序在a前面""" <|body_0|> def minNumber2(self, nums: List[int]) -> str: """使用内置sort""" <|body_1|> <|end_skeleton|> <|body_start_0|> def quick_sort(l, r): ...
stack_v2_sparse_classes_36k_train_003380
1,792
no_license
[ { "docstring": "按照字典序,小的排前面 对于字符串 a,b 如果 a+b > b+a b字典序在a前面", "name": "minNumber", "signature": "def minNumber(self, nums: List[int]) -> str" }, { "docstring": "使用内置sort", "name": "minNumber2", "signature": "def minNumber2(self, nums: List[int]) -> str" } ]
2
stack_v2_sparse_classes_30k_val_000228
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minNumber(self, nums: List[int]) -> str: 按照字典序,小的排前面 对于字符串 a,b 如果 a+b > b+a b字典序在a前面 - def minNumber2(self, nums: List[int]) -> str: 使用内置sort
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minNumber(self, nums: List[int]) -> str: 按照字典序,小的排前面 对于字符串 a,b 如果 a+b > b+a b字典序在a前面 - def minNumber2(self, nums: List[int]) -> str: 使用内置sort <|skeleton|> class Solution: ...
c92a5ddcc56e3f69be1e6fb25e9c8ed277e57ee0
<|skeleton|> class Solution: def minNumber(self, nums: List[int]) -> str: """按照字典序,小的排前面 对于字符串 a,b 如果 a+b > b+a b字典序在a前面""" <|body_0|> def minNumber2(self, nums: List[int]) -> str: """使用内置sort""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def minNumber(self, nums: List[int]) -> str: """按照字典序,小的排前面 对于字符串 a,b 如果 a+b > b+a b字典序在a前面""" def quick_sort(l, r): if l >= r: return i, j = (l, r) while i < j: while strs[j] + strs[l] >= strs[l] + strs[j] and i < j...
the_stack_v2_python_sparse
SwordOffer/SwordOffer_45.py
EachenKuang/LeetCode
train
28
4eca387528e53aa20835173db4bbc588aa27c96d
[ "super().__init__()\nassert d % h == 0, 'd must divide by h'\nself.dk = d // h\nself.h = h\nself.d = d\nself.n1 = nn.Linear(d, d)\nself.n2 = nn.Linear(d, d)\nself.n3 = nn.Linear(d, d)\nself.n4 = nn.Linear(d, d)\nself.dropout = nn.Dropout(drop)", "N, _, d = Q.size()\nq = self.n1(Q).view(N, -1, self.h, self.dk).tra...
<|body_start_0|> super().__init__() assert d % h == 0, 'd must divide by h' self.dk = d // h self.h = h self.d = d self.n1 = nn.Linear(d, d) self.n2 = nn.Linear(d, d) self.n3 = nn.Linear(d, d) self.n4 = nn.Linear(d, d) self.dropout = nn.Dro...
MultiAttentionLayer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MultiAttentionLayer: def __init__(self, d, h, drop=0.1): """d: hidden size h:split factor""" <|body_0|> def forward(self, Q, K, V, mask=None): """Q:(N,T1,d) K:(N,T2,d) V:(N,T2,d) mask:(N,T1,T2) return out:(N,T1,d) p_attn:(N,T1,T2)""" <|body_1|> <|end_skeleto...
stack_v2_sparse_classes_36k_train_003381
11,927
no_license
[ { "docstring": "d: hidden size h:split factor", "name": "__init__", "signature": "def __init__(self, d, h, drop=0.1)" }, { "docstring": "Q:(N,T1,d) K:(N,T2,d) V:(N,T2,d) mask:(N,T1,T2) return out:(N,T1,d) p_attn:(N,T1,T2)", "name": "forward", "signature": "def forward(self, Q, K, V, mask...
2
stack_v2_sparse_classes_30k_train_006005
Implement the Python class `MultiAttentionLayer` described below. Class description: Implement the MultiAttentionLayer class. Method signatures and docstrings: - def __init__(self, d, h, drop=0.1): d: hidden size h:split factor - def forward(self, Q, K, V, mask=None): Q:(N,T1,d) K:(N,T2,d) V:(N,T2,d) mask:(N,T1,T2) r...
Implement the Python class `MultiAttentionLayer` described below. Class description: Implement the MultiAttentionLayer class. Method signatures and docstrings: - def __init__(self, d, h, drop=0.1): d: hidden size h:split factor - def forward(self, Q, K, V, mask=None): Q:(N,T1,d) K:(N,T2,d) V:(N,T2,d) mask:(N,T1,T2) r...
24e60f24b6e442db22507adddd6bf3e2c343c013
<|skeleton|> class MultiAttentionLayer: def __init__(self, d, h, drop=0.1): """d: hidden size h:split factor""" <|body_0|> def forward(self, Q, K, V, mask=None): """Q:(N,T1,d) K:(N,T2,d) V:(N,T2,d) mask:(N,T1,T2) return out:(N,T1,d) p_attn:(N,T1,T2)""" <|body_1|> <|end_skeleto...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MultiAttentionLayer: def __init__(self, d, h, drop=0.1): """d: hidden size h:split factor""" super().__init__() assert d % h == 0, 'd must divide by h' self.dk = d // h self.h = h self.d = d self.n1 = nn.Linear(d, d) self.n2 = nn.Linear(d, d) ...
the_stack_v2_python_sparse
daily/8/pytorch_tutoral/nmt/model.py
mckjzhangxk/deepAI
train
1
d3057d3ad245e86a0463a8a313acff8fa0de3c61
[ "qs = super(DocsItaliaProjectViewSet, self).get_queryset()\ntags = self.request.query_params.get('tags', None)\nif tags:\n tags = tags.split(',')\n qs = qs.filter(tags__slug__in=tags).distinct()\npublisher = self.request.query_params.get('publisher', None)\nif publisher:\n qs = qs.filter(publisherproject__...
<|body_start_0|> qs = super(DocsItaliaProjectViewSet, self).get_queryset() tags = self.request.query_params.get('tags', None) if tags: tags = tags.split(',') qs = qs.filter(tags__slug__in=tags).distinct() publisher = self.request.query_params.get('publisher', None...
Like :py:class:`ProjectViewSet` but using slug as lookup key.
DocsItaliaProjectViewSet
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DocsItaliaProjectViewSet: """Like :py:class:`ProjectViewSet` but using slug as lookup key.""" def get_queryset(self): """Filter projects by tags, publisher and project passed as query parameters. e.g. ?tags=tag1,tag2, ?publisher=publisher-slug, ?project=project-slug""" <|body...
stack_v2_sparse_classes_36k_train_003382
2,665
permissive
[ { "docstring": "Filter projects by tags, publisher and project passed as query parameters. e.g. ?tags=tag1,tag2, ?publisher=publisher-slug, ?project=project-slug", "name": "get_queryset", "signature": "def get_queryset(self)" }, { "docstring": "Returns project for user or 404.", "name": "get...
3
stack_v2_sparse_classes_30k_train_002880
Implement the Python class `DocsItaliaProjectViewSet` described below. Class description: Like :py:class:`ProjectViewSet` but using slug as lookup key. Method signatures and docstrings: - def get_queryset(self): Filter projects by tags, publisher and project passed as query parameters. e.g. ?tags=tag1,tag2, ?publishe...
Implement the Python class `DocsItaliaProjectViewSet` described below. Class description: Like :py:class:`ProjectViewSet` but using slug as lookup key. Method signatures and docstrings: - def get_queryset(self): Filter projects by tags, publisher and project passed as query parameters. e.g. ?tags=tag1,tag2, ?publishe...
649965d7589eb1d30efdc7906c3ee7dc5a9e3656
<|skeleton|> class DocsItaliaProjectViewSet: """Like :py:class:`ProjectViewSet` but using slug as lookup key.""" def get_queryset(self): """Filter projects by tags, publisher and project passed as query parameters. e.g. ?tags=tag1,tag2, ?publisher=publisher-slug, ?project=project-slug""" <|body...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DocsItaliaProjectViewSet: """Like :py:class:`ProjectViewSet` but using slug as lookup key.""" def get_queryset(self): """Filter projects by tags, publisher and project passed as query parameters. e.g. ?tags=tag1,tag2, ?publisher=publisher-slug, ?project=project-slug""" qs = super(DocsItal...
the_stack_v2_python_sparse
readthedocs/docsitalia/views/api.py
italia/docs.italia.it
train
19
e7d38fb853f97126921e62b40ab73fa12aab5dfd
[ "widths = ColumnWidths(max_column_width=max_column_width)\nfor line in self:\n if isinstance(line, _Marker):\n widths = widths.Merge(line.CalculateColumnWidths(max_column_width, indent_length))\nreturn widths", "for line in self:\n if isinstance(line, _Marker):\n line.Print(output, indent_leng...
<|body_start_0|> widths = ColumnWidths(max_column_width=max_column_width) for line in self: if isinstance(line, _Marker): widths = widths.Merge(line.CalculateColumnWidths(max_column_width, indent_length)) return widths <|end_body_0|> <|body_start_1|> for line...
Marker class for a list of lines.
Lines
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Lines: """Marker class for a list of lines.""" def CalculateColumnWidths(self, max_column_width=None, indent_length=0): """See _Marker base class.""" <|body_0|> def Print(self, output, indent_length, column_widths): """See _Marker base class.""" <|body_1|...
stack_v2_sparse_classes_36k_train_003383
17,042
permissive
[ { "docstring": "See _Marker base class.", "name": "CalculateColumnWidths", "signature": "def CalculateColumnWidths(self, max_column_width=None, indent_length=0)" }, { "docstring": "See _Marker base class.", "name": "Print", "signature": "def Print(self, output, indent_length, column_widt...
3
null
Implement the Python class `Lines` described below. Class description: Marker class for a list of lines. Method signatures and docstrings: - def CalculateColumnWidths(self, max_column_width=None, indent_length=0): See _Marker base class. - def Print(self, output, indent_length, column_widths): See _Marker base class....
Implement the Python class `Lines` described below. Class description: Marker class for a list of lines. Method signatures and docstrings: - def CalculateColumnWidths(self, max_column_width=None, indent_length=0): See _Marker base class. - def Print(self, output, indent_length, column_widths): See _Marker base class....
392abf004b16203030e6efd2f0af24db7c8d669e
<|skeleton|> class Lines: """Marker class for a list of lines.""" def CalculateColumnWidths(self, max_column_width=None, indent_length=0): """See _Marker base class.""" <|body_0|> def Print(self, output, indent_length, column_widths): """See _Marker base class.""" <|body_1|...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Lines: """Marker class for a list of lines.""" def CalculateColumnWidths(self, max_column_width=None, indent_length=0): """See _Marker base class.""" widths = ColumnWidths(max_column_width=max_column_width) for line in self: if isinstance(line, _Marker): ...
the_stack_v2_python_sparse
lib/googlecloudsdk/core/resource/custom_printer_base.py
google-cloud-sdk-unofficial/google-cloud-sdk
train
9
324c32dbd0feaf6df90e4eea5a3b994a3912f845
[ "root_div = html_tags.div(cls='content-block', style='margin-bottom:40px;')\n\ndef get_th(heading_name):\n return html_tags.th(heading_name, cls='text-muted')\nwith root_div:\n html_tags.legend('Geometry Information')\n with html_tags.table(cls='custom-table'):\n with html_tags.tbody():\n ...
<|body_start_0|> root_div = html_tags.div(cls='content-block', style='margin-bottom:40px;') def get_th(heading_name): return html_tags.th(heading_name, cls='text-muted') with root_div: html_tags.legend('Geometry Information') with html_tags.table(cls='custom-...
GeometryInformation
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GeometryInformation: def get_html(self, pretty=True): """Generates html code for displaying data for this metadata element""" <|body_0|> def get_html_form(cls, resource, element=None, allow_edit=True, file_type=False): """Generates html form code for an instance of t...
stack_v2_sparse_classes_36k_train_003384
48,694
permissive
[ { "docstring": "Generates html code for displaying data for this metadata element", "name": "get_html", "signature": "def get_html(self, pretty=True)" }, { "docstring": "Generates html form code for an instance of this metadata element so that this element can be edited", "name": "get_html_f...
2
null
Implement the Python class `GeometryInformation` described below. Class description: Implement the GeometryInformation class. Method signatures and docstrings: - def get_html(self, pretty=True): Generates html code for displaying data for this metadata element - def get_html_form(cls, resource, element=None, allow_ed...
Implement the Python class `GeometryInformation` described below. Class description: Implement the GeometryInformation class. Method signatures and docstrings: - def get_html(self, pretty=True): Generates html code for displaying data for this metadata element - def get_html_form(cls, resource, element=None, allow_ed...
69855813052243c702c9b0108d2eac3f4f1a768f
<|skeleton|> class GeometryInformation: def get_html(self, pretty=True): """Generates html code for displaying data for this metadata element""" <|body_0|> def get_html_form(cls, resource, element=None, allow_edit=True, file_type=False): """Generates html form code for an instance of t...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GeometryInformation: def get_html(self, pretty=True): """Generates html code for displaying data for this metadata element""" root_div = html_tags.div(cls='content-block', style='margin-bottom:40px;') def get_th(heading_name): return html_tags.th(heading_name, cls='text-mu...
the_stack_v2_python_sparse
hs_file_types/models/geofeature.py
hydroshare/hydroshare
train
207
f9bfd597d31abee0c5cbab3baf4f0efc3a171ad8
[ "context = super().get_context_data(**kwargs)\nuser = self.get_object()\ncontext['summary'] = {'comments_count': Comment.objects.filter(user=user).count(), 'likes_count': Likes.objects.filter(user=user).count(), 'posts': Post.objects.filter(user=user).count()}\ncontext['last_comments'] = Comment.objects.filter(user...
<|body_start_0|> context = super().get_context_data(**kwargs) user = self.get_object() context['summary'] = {'comments_count': Comment.objects.filter(user=user).count(), 'likes_count': Likes.objects.filter(user=user).count(), 'posts': Post.objects.filter(user=user).count()} context['last...
Form view for content deletion. Loaded embedded in a modal.
RemoveSpamUserView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RemoveSpamUserView: """Form view for content deletion. Loaded embedded in a modal.""" def get_context_data(self, **kwargs): """Insert the form and url construction data into the context.""" <|body_0|> def delete(self, request, *args, **kwargs): """Call the `deact...
stack_v2_sparse_classes_36k_train_003385
1,887
no_license
[ { "docstring": "Insert the form and url construction data into the context.", "name": "get_context_data", "signature": "def get_context_data(self, **kwargs)" }, { "docstring": "Call the `deactivate_user_and_remove_content()` method on the fetched object and then redirect to the success URL.", ...
2
null
Implement the Python class `RemoveSpamUserView` described below. Class description: Form view for content deletion. Loaded embedded in a modal. Method signatures and docstrings: - def get_context_data(self, **kwargs): Insert the form and url construction data into the context. - def delete(self, request, *args, **kwa...
Implement the Python class `RemoveSpamUserView` described below. Class description: Form view for content deletion. Loaded embedded in a modal. Method signatures and docstrings: - def get_context_data(self, **kwargs): Insert the form and url construction data into the context. - def delete(self, request, *args, **kwa...
960aed85f8438109bed9883321891305e1db8b10
<|skeleton|> class RemoveSpamUserView: """Form view for content deletion. Loaded embedded in a modal.""" def get_context_data(self, **kwargs): """Insert the form and url construction data into the context.""" <|body_0|> def delete(self, request, *args, **kwargs): """Call the `deact...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RemoveSpamUserView: """Form view for content deletion. Loaded embedded in a modal.""" def get_context_data(self, **kwargs): """Insert the form and url construction data into the context.""" context = super().get_context_data(**kwargs) user = self.get_object() context['summ...
the_stack_v2_python_sparse
dillo/views/moderation.py
armadillica/dillo
train
79
1f3bbab0d664322575448a7c240fc15fa17872d3
[ "super().__init__()\nself.mha1 = MultiHeadAttention(dm, h)\nself.mha2 = MultiHeadAttention(dm, h)\nself.dense_hidden = tf.keras.layers.Dense(units=hidden, activation='relu')\nself.dense_output = tf.keras.layers.Dense(units=dm)\nself.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-06)\nself.layernorm2 = t...
<|body_start_0|> super().__init__() self.mha1 = MultiHeadAttention(dm, h) self.mha2 = MultiHeadAttention(dm, h) self.dense_hidden = tf.keras.layers.Dense(units=hidden, activation='relu') self.dense_output = tf.keras.layers.Dense(units=dm) self.layernorm1 = tf.keras.layers...
class DecoderBlock
DecoderBlock
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DecoderBlock: """class DecoderBlock""" def __init__(self, dm, h, hidden, drop_rate=0.1): """Class constructor""" <|body_0|> def call(self, x, encoder_output, training, look_ahead_mask, padding_mask): """Method that returns a tensor of shape (batch, target_seq_len...
stack_v2_sparse_classes_36k_train_003386
2,054
no_license
[ { "docstring": "Class constructor", "name": "__init__", "signature": "def __init__(self, dm, h, hidden, drop_rate=0.1)" }, { "docstring": "Method that returns a tensor of shape (batch, target_seq_len, dm) containing the block’s output", "name": "call", "signature": "def call(self, x, enc...
2
stack_v2_sparse_classes_30k_train_005306
Implement the Python class `DecoderBlock` described below. Class description: class DecoderBlock Method signatures and docstrings: - def __init__(self, dm, h, hidden, drop_rate=0.1): Class constructor - def call(self, x, encoder_output, training, look_ahead_mask, padding_mask): Method that returns a tensor of shape (...
Implement the Python class `DecoderBlock` described below. Class description: class DecoderBlock Method signatures and docstrings: - def __init__(self, dm, h, hidden, drop_rate=0.1): Class constructor - def call(self, x, encoder_output, training, look_ahead_mask, padding_mask): Method that returns a tensor of shape (...
c7b6ea4c37b7c5dc41e63cdb8142b3cdfb3e1d23
<|skeleton|> class DecoderBlock: """class DecoderBlock""" def __init__(self, dm, h, hidden, drop_rate=0.1): """Class constructor""" <|body_0|> def call(self, x, encoder_output, training, look_ahead_mask, padding_mask): """Method that returns a tensor of shape (batch, target_seq_len...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DecoderBlock: """class DecoderBlock""" def __init__(self, dm, h, hidden, drop_rate=0.1): """Class constructor""" super().__init__() self.mha1 = MultiHeadAttention(dm, h) self.mha2 = MultiHeadAttention(dm, h) self.dense_hidden = tf.keras.layers.Dense(units=hidden, a...
the_stack_v2_python_sparse
supervised_learning/0x11-attention/8-transformer_decoder_block.py
linkjavier/holbertonschool-machine_learning
train
0
7ac295ed35185f950aa7350e807a0fa1e858b3d5
[ "if isinstance(den, (pd.DataFrame, pd.Series)):\n den = den.values\nif isinstance(num, (pd.DataFrame, pd.Series)):\n num = num.values\nrevden = den[::-1]\nrevnum = num[::-1].reshape(-1, 1)\nnew_num = np.full_like(revnum, np.nan, dtype=float)\nnew_den = np.full_like(revden, np.nan, dtype=float)\nn, p = revnum....
<|body_start_0|> if isinstance(den, (pd.DataFrame, pd.Series)): den = den.values if isinstance(num, (pd.DataFrame, pd.Series)): num = num.values revden = den[::-1] revnum = num[::-1].reshape(-1, 1) new_num = np.full_like(revnum, np.nan, dtype=float) ...
Sensor class to fit a signal using Covid counts from Change HC outpatient data.
CHCSensor
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CHCSensor: """Sensor class to fit a signal using Covid counts from Change HC outpatient data.""" def backfill(num, den, k=Config.MAX_BACKFILL_WINDOW, min_visits_to_fill=Config.MIN_CUM_VISITS): """Adjust for retroactively added observations (backfill) by using a variable length smooth...
stack_v2_sparse_classes_36k_train_003387
4,582
permissive
[ { "docstring": "Adjust for retroactively added observations (backfill) by using a variable length smoother. The smoother starts from the RHS and moves leftwards (backwards through time). We cumulatively sum the total visits (denominator), until we have observed some minimum number of counts, then calculate the ...
2
null
Implement the Python class `CHCSensor` described below. Class description: Sensor class to fit a signal using Covid counts from Change HC outpatient data. Method signatures and docstrings: - def backfill(num, den, k=Config.MAX_BACKFILL_WINDOW, min_visits_to_fill=Config.MIN_CUM_VISITS): Adjust for retroactively added ...
Implement the Python class `CHCSensor` described below. Class description: Sensor class to fit a signal using Covid counts from Change HC outpatient data. Method signatures and docstrings: - def backfill(num, den, k=Config.MAX_BACKFILL_WINDOW, min_visits_to_fill=Config.MIN_CUM_VISITS): Adjust for retroactively added ...
0c0ca18f38892c850565edf8bed9d2acaf234354
<|skeleton|> class CHCSensor: """Sensor class to fit a signal using Covid counts from Change HC outpatient data.""" def backfill(num, den, k=Config.MAX_BACKFILL_WINDOW, min_visits_to_fill=Config.MIN_CUM_VISITS): """Adjust for retroactively added observations (backfill) by using a variable length smooth...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CHCSensor: """Sensor class to fit a signal using Covid counts from Change HC outpatient data.""" def backfill(num, den, k=Config.MAX_BACKFILL_WINDOW, min_visits_to_fill=Config.MIN_CUM_VISITS): """Adjust for retroactively added observations (backfill) by using a variable length smoother. The smoot...
the_stack_v2_python_sparse
changehc/delphi_changehc/sensor.py
alexcoda/covidcast-indicators
train
0
95d3a68d45c51471b8cabec5092c4fbde27973b0
[ "ss = sum(nums)\nif ss & 1 == 0:\n target = ss >> 1\n cur = {0}\n for i in nums:\n cur |= {i + x for x in cur}\n if target in cur:\n return True\nreturn False", "ss = sum(nums)\nif ss & 1:\n return False\nhalf = ss / 2\ndp = [False] * (half + 1)\ndp[0] = True\nfor n in nums:\n...
<|body_start_0|> ss = sum(nums) if ss & 1 == 0: target = ss >> 1 cur = {0} for i in nums: cur |= {i + x for x in cur} if target in cur: return True return False <|end_body_0|> <|body_start_1|> ss = s...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def canPartition(self, nums): """:type nums: List[int] :rtype: bool 概念 總和 / 2 的值為target.""" <|body_0|> def rewritedp(self, nums): """:type nums: List[int] :rtype: bool 概念 總和 / 2 的值為target.""" <|body_1|> <|end_skeleton|> <|body_start_0|> ss...
stack_v2_sparse_classes_36k_train_003388
1,997
no_license
[ { "docstring": ":type nums: List[int] :rtype: bool 概念 總和 / 2 的值為target.", "name": "canPartition", "signature": "def canPartition(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: bool 概念 總和 / 2 的值為target.", "name": "rewritedp", "signature": "def rewritedp(self, nums)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def canPartition(self, nums): :type nums: List[int] :rtype: bool 概念 總和 / 2 的值為target. - def rewritedp(self, nums): :type nums: List[int] :rtype: bool 概念 總和 / 2 的值為target.
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def canPartition(self, nums): :type nums: List[int] :rtype: bool 概念 總和 / 2 的值為target. - def rewritedp(self, nums): :type nums: List[int] :rtype: bool 概念 總和 / 2 的值為target. <|skel...
6350568d16b0f8c49a020f055bb6d72e2705ea56
<|skeleton|> class Solution: def canPartition(self, nums): """:type nums: List[int] :rtype: bool 概念 總和 / 2 的值為target.""" <|body_0|> def rewritedp(self, nums): """:type nums: List[int] :rtype: bool 概念 總和 / 2 的值為target.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def canPartition(self, nums): """:type nums: List[int] :rtype: bool 概念 總和 / 2 的值為target.""" ss = sum(nums) if ss & 1 == 0: target = ss >> 1 cur = {0} for i in nums: cur |= {i + x for x in cur} if target in cu...
the_stack_v2_python_sparse
co_fb/416_Partition_Equal_Subset_Sum.py
vsdrun/lc_public
train
6
c85cf8903c0fea89158f771f1fad49626b078a21
[ "self.num = 0\nself.num_list = []\nself.sort_num_list = None\nself.k = k\nself.m = m", "if len(self.num_list) < self.m:\n self.num_list.append(num)\nelse:\n self.num_list.pop(0)\n self.num_list.append(num)\nif len(self.num_list) == self.m:\n self.sort_num_list = copy.deepcopy(self.num_list)\n self....
<|body_start_0|> self.num = 0 self.num_list = [] self.sort_num_list = None self.k = k self.m = m <|end_body_0|> <|body_start_1|> if len(self.num_list) < self.m: self.num_list.append(num) else: self.num_list.pop(0) self.num_list...
MKAverage
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MKAverage: def __init__(self, m, k): """:type m: int :type k: int""" <|body_0|> def addElement(self, num): """:type num: int :rtype: None""" <|body_1|> def calculateMKAverage(self): """:rtype: int""" <|body_2|> <|end_skeleton|> <|body_s...
stack_v2_sparse_classes_36k_train_003389
881
no_license
[ { "docstring": ":type m: int :type k: int", "name": "__init__", "signature": "def __init__(self, m, k)" }, { "docstring": ":type num: int :rtype: None", "name": "addElement", "signature": "def addElement(self, num)" }, { "docstring": ":rtype: int", "name": "calculateMKAverage...
3
stack_v2_sparse_classes_30k_train_020390
Implement the Python class `MKAverage` described below. Class description: Implement the MKAverage class. Method signatures and docstrings: - def __init__(self, m, k): :type m: int :type k: int - def addElement(self, num): :type num: int :rtype: None - def calculateMKAverage(self): :rtype: int
Implement the Python class `MKAverage` described below. Class description: Implement the MKAverage class. Method signatures and docstrings: - def __init__(self, m, k): :type m: int :type k: int - def addElement(self, num): :type num: int :rtype: None - def calculateMKAverage(self): :rtype: int <|skeleton|> class MKA...
d34d4b592d05e9e0e724d8834eaf9587a64c5034
<|skeleton|> class MKAverage: def __init__(self, m, k): """:type m: int :type k: int""" <|body_0|> def addElement(self, num): """:type num: int :rtype: None""" <|body_1|> def calculateMKAverage(self): """:rtype: int""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MKAverage: def __init__(self, m, k): """:type m: int :type k: int""" self.num = 0 self.num_list = [] self.sort_num_list = None self.k = k self.m = m def addElement(self, num): """:type num: int :rtype: None""" if len(self.num_list) < self.m:...
the_stack_v2_python_sparse
LeetCode算法题/1825_求出MK平均值/求出MK平均值.py
exueyuanAlgorithm/AlgorithmDemo
train
0
327da6abc07a82011d66b2f7f0e0f52448c528e0
[ "if not head:\n return head\ncur = head\npre = None\nr = cur\nwhile cur:\n t = cur.next\n cur.next = pre\n r = cur\n pre = cur\n cur = t\nreturn r", "if not head or not head.next:\n return head\nnode = self.reverseList(head.next)\nhead.next.next = head\nhead.next = None\nreturn node" ]
<|body_start_0|> if not head: return head cur = head pre = None r = cur while cur: t = cur.next cur.next = pre r = cur pre = cur cur = t return r <|end_body_0|> <|body_start_1|> if not head o...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def reverseList1(self, head): """:type head: ListNode :rtype: ListNode""" <|body_0|> def reverseList(self, head): """:type head: ListNode :rtype: ListNode""" <|body_1|> <|end_skeleton|> <|body_start_0|> if not head: return head...
stack_v2_sparse_classes_36k_train_003390
945
no_license
[ { "docstring": ":type head: ListNode :rtype: ListNode", "name": "reverseList1", "signature": "def reverseList1(self, head)" }, { "docstring": ":type head: ListNode :rtype: ListNode", "name": "reverseList", "signature": "def reverseList(self, head)" } ]
2
stack_v2_sparse_classes_30k_train_002577
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def reverseList1(self, head): :type head: ListNode :rtype: ListNode - def reverseList(self, head): :type head: ListNode :rtype: ListNode
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def reverseList1(self, head): :type head: ListNode :rtype: ListNode - def reverseList(self, head): :type head: ListNode :rtype: ListNode <|skeleton|> class Solution: def re...
e5b018493bbd12edcdcd0434f35d9c358106d391
<|skeleton|> class Solution: def reverseList1(self, head): """:type head: ListNode :rtype: ListNode""" <|body_0|> def reverseList(self, head): """:type head: ListNode :rtype: ListNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def reverseList1(self, head): """:type head: ListNode :rtype: ListNode""" if not head: return head cur = head pre = None r = cur while cur: t = cur.next cur.next = pre r = cur pre = cur ...
the_stack_v2_python_sparse
py/leetcode/206.py
wfeng1991/learnpy
train
0
e6deece59f9a12d4cf3ffe3c02cfa42c714e4810
[ "if not root:\n return []\ndic = collections.defaultdict(list)\nqueue = collections.deque()\nqueue.append((root, 0))\nwhile queue:\n root, index = queue.popleft()\n dic[index].append(root.val)\n if root.left:\n queue.append((root.left, index - 1))\n if root.right:\n queue.append((root.r...
<|body_start_0|> if not root: return [] dic = collections.defaultdict(list) queue = collections.deque() queue.append((root, 0)) while queue: root, index = queue.popleft() dic[index].append(root.val) if root.left: que...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def verticalOrder1(self, root: TreeNode) -> List[List[int]]: """思路:BFS @param root: @return:""" <|body_0|> def verticalOrder1(self, root: TreeNode) -> List[List[int]]: """思路:DFS @param root: @return:""" <|body_1|> <|end_skeleton|> <|body_start_0|>...
stack_v2_sparse_classes_36k_train_003391
2,501
no_license
[ { "docstring": "思路:BFS @param root: @return:", "name": "verticalOrder1", "signature": "def verticalOrder1(self, root: TreeNode) -> List[List[int]]" }, { "docstring": "思路:DFS @param root: @return:", "name": "verticalOrder1", "signature": "def verticalOrder1(self, root: TreeNode) -> List[L...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def verticalOrder1(self, root: TreeNode) -> List[List[int]]: 思路:BFS @param root: @return: - def verticalOrder1(self, root: TreeNode) -> List[List[int]]: 思路:DFS @param root: @retu...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def verticalOrder1(self, root: TreeNode) -> List[List[int]]: 思路:BFS @param root: @return: - def verticalOrder1(self, root: TreeNode) -> List[List[int]]: 思路:DFS @param root: @retu...
e43ee86c5a8cdb808da09b4b6138e10275abadb5
<|skeleton|> class Solution: def verticalOrder1(self, root: TreeNode) -> List[List[int]]: """思路:BFS @param root: @return:""" <|body_0|> def verticalOrder1(self, root: TreeNode) -> List[List[int]]: """思路:DFS @param root: @return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def verticalOrder1(self, root: TreeNode) -> List[List[int]]: """思路:BFS @param root: @return:""" if not root: return [] dic = collections.defaultdict(list) queue = collections.deque() queue.append((root, 0)) while queue: root, in...
the_stack_v2_python_sparse
LeetCode/树(Binary Tree)/314. 二叉树的垂直遍历.py
yiming1012/MyLeetCode
train
2
4ac3ae517b293d32799713461cc27b28f4ab130b
[ "result = []\n\ndef preorder(node):\n if node:\n result.append(node.val)\n preorder(node.left)\n preorder(node.right)\npreorder(root)\nreturn ' '.join(map(str, result))", "data = list(map(int, data.split()))\n\ndef build(minValue, maxValue):\n if data and minValue < data[0] < maxValue:\...
<|body_start_0|> result = [] def preorder(node): if node: result.append(node.val) preorder(node.left) preorder(node.right) preorder(root) return ' '.join(map(str, result)) <|end_body_0|> <|body_start_1|> data = list(ma...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|> <|body_...
stack_v2_sparse_classes_36k_train_003392
1,814
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_018243
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:...
3aab1747a1e6a77de808073e8735f89704940496
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" result = [] def preorder(node): if node: result.append(node.val) preorder(node.left) preorder(node.right) pre...
the_stack_v2_python_sparse
leetcode/questions/bstTreeSerializeAndDeserialize.py
ziqingW/pythonPlayground
train
0
63e7273bb76585495884a34bc281ef7b0271f90c
[ "name = validated_data['name']\nemail = validated_data['email']\nuser = User.objects.create(name=name, email=email)\nuser.set_password(validated_data['password'])\nuser.save()\nreturn user", "if len(value) < 6:\n raise serializers.ValidationError('the password at least 6 long,please try again.')\nreturn value"...
<|body_start_0|> name = validated_data['name'] email = validated_data['email'] user = User.objects.create(name=name, email=email) user.set_password(validated_data['password']) user.save() return user <|end_body_0|> <|body_start_1|> if len(value) < 6: ...
usr crate serialize
UserCreateSerializer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserCreateSerializer: """usr crate serialize""" def create(self, validated_data): """custom user""" <|body_0|> def validate_password(self, value): """check password""" <|body_1|> def validate_name(self, value): """validate user name""" ...
stack_v2_sparse_classes_36k_train_003393
4,048
no_license
[ { "docstring": "custom user", "name": "create", "signature": "def create(self, validated_data)" }, { "docstring": "check password", "name": "validate_password", "signature": "def validate_password(self, value)" }, { "docstring": "validate user name", "name": "validate_name", ...
3
stack_v2_sparse_classes_30k_val_001004
Implement the Python class `UserCreateSerializer` described below. Class description: usr crate serialize Method signatures and docstrings: - def create(self, validated_data): custom user - def validate_password(self, value): check password - def validate_name(self, value): validate user name
Implement the Python class `UserCreateSerializer` described below. Class description: usr crate serialize Method signatures and docstrings: - def create(self, validated_data): custom user - def validate_password(self, value): check password - def validate_name(self, value): validate user name <|skeleton|> class User...
2401a28cfd3ab12b2744706cfb5ee5b41962bd01
<|skeleton|> class UserCreateSerializer: """usr crate serialize""" def create(self, validated_data): """custom user""" <|body_0|> def validate_password(self, value): """check password""" <|body_1|> def validate_name(self, value): """validate user name""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UserCreateSerializer: """usr crate serialize""" def create(self, validated_data): """custom user""" name = validated_data['name'] email = validated_data['email'] user = User.objects.create(name=name, email=email) user.set_password(validated_data['password']) ...
the_stack_v2_python_sparse
droplet/accounts/serializers.py
qxs820624/django
train
1
2c12afdc1e69d238023ae3865f7eee477a864361
[ "if file_path is None:\n return False\ntry:\n if os.path.exists(file_path):\n os.remove(file_path)\nexcept Exception as ex:\n if ignore_errors:\n return False\n raise ex\nreturn True", "if directory_path is None:\n return False\ntry:\n if os.path.exists(directory_path):\n sh...
<|body_start_0|> if file_path is None: return False try: if os.path.exists(file_path): os.remove(file_path) except Exception as ex: if ignore_errors: return False raise ex return True <|end_body_0|> <|body_s...
Utilities for reading/writing to and from files.
CommonIOUtils
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CommonIOUtils: """Utilities for reading/writing to and from files.""" def delete_file(file_path: str, ignore_errors: bool=False) -> bool: """delete_file(file_path, ignore_errors=False) Delete a file. :param file_path: The file to delete. :type file_path: str :param ignore_errors: If ...
stack_v2_sparse_classes_36k_train_003394
4,270
permissive
[ { "docstring": "delete_file(file_path, ignore_errors=False) Delete a file. :param file_path: The file to delete. :type file_path: str :param ignore_errors: If True, any exceptions thrown will be ignored (Useful in preventing infinite loops) :type ignore_errors: bool, optional :return: True if successful. False ...
4
stack_v2_sparse_classes_30k_train_019816
Implement the Python class `CommonIOUtils` described below. Class description: Utilities for reading/writing to and from files. Method signatures and docstrings: - def delete_file(file_path: str, ignore_errors: bool=False) -> bool: delete_file(file_path, ignore_errors=False) Delete a file. :param file_path: The file ...
Implement the Python class `CommonIOUtils` described below. Class description: Utilities for reading/writing to and from files. Method signatures and docstrings: - def delete_file(file_path: str, ignore_errors: bool=False) -> bool: delete_file(file_path, ignore_errors=False) Delete a file. :param file_path: The file ...
b59ea7e5f4bd01d3b3bd7603843d525a9c179867
<|skeleton|> class CommonIOUtils: """Utilities for reading/writing to and from files.""" def delete_file(file_path: str, ignore_errors: bool=False) -> bool: """delete_file(file_path, ignore_errors=False) Delete a file. :param file_path: The file to delete. :type file_path: str :param ignore_errors: If ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CommonIOUtils: """Utilities for reading/writing to and from files.""" def delete_file(file_path: str, ignore_errors: bool=False) -> bool: """delete_file(file_path, ignore_errors=False) Delete a file. :param file_path: The file to delete. :type file_path: str :param ignore_errors: If True, any exc...
the_stack_v2_python_sparse
src/sims4communitylib/utils/common_io_utils.py
velocist/TS4CheatsInfo
train
1
b7bc715fd7b6460deea4fbf804552d2a1260175c
[ "self.bonding_mode = bonding_mode\nself.name = name\nself.slaves = slaves", "if dictionary is None:\n return None\nbonding_mode = dictionary.get('bondingMode')\nname = dictionary.get('name')\nslaves = dictionary.get('slaves')\nreturn cls(bonding_mode, name, slaves)" ]
<|body_start_0|> self.bonding_mode = bonding_mode self.name = name self.slaves = slaves <|end_body_0|> <|body_start_1|> if dictionary is None: return None bonding_mode = dictionary.get('bondingMode') name = dictionary.get('name') slaves = dictionary.g...
Implementation of the 'CreateBondParameters' model. Specifies the parameters needed to create a bond. Attributes: bonding_mode (BondingModeEnum): Specifies the bonding mode to use for this bond. If not specified, this value will default to 'kActiveBackup'. 'kActiveBackup' indicates active backup bonding mode. 'k802_3ad...
CreateBondParameters
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CreateBondParameters: """Implementation of the 'CreateBondParameters' model. Specifies the parameters needed to create a bond. Attributes: bonding_mode (BondingModeEnum): Specifies the bonding mode to use for this bond. If not specified, this value will default to 'kActiveBackup'. 'kActiveBackup'...
stack_v2_sparse_classes_36k_train_003395
2,083
permissive
[ { "docstring": "Constructor for the CreateBondParameters class", "name": "__init__", "signature": "def __init__(self, bonding_mode=None, name=None, slaves=None)" }, { "docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of t...
2
stack_v2_sparse_classes_30k_train_017349
Implement the Python class `CreateBondParameters` described below. Class description: Implementation of the 'CreateBondParameters' model. Specifies the parameters needed to create a bond. Attributes: bonding_mode (BondingModeEnum): Specifies the bonding mode to use for this bond. If not specified, this value will defa...
Implement the Python class `CreateBondParameters` described below. Class description: Implementation of the 'CreateBondParameters' model. Specifies the parameters needed to create a bond. Attributes: bonding_mode (BondingModeEnum): Specifies the bonding mode to use for this bond. If not specified, this value will defa...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class CreateBondParameters: """Implementation of the 'CreateBondParameters' model. Specifies the parameters needed to create a bond. Attributes: bonding_mode (BondingModeEnum): Specifies the bonding mode to use for this bond. If not specified, this value will default to 'kActiveBackup'. 'kActiveBackup'...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CreateBondParameters: """Implementation of the 'CreateBondParameters' model. Specifies the parameters needed to create a bond. Attributes: bonding_mode (BondingModeEnum): Specifies the bonding mode to use for this bond. If not specified, this value will default to 'kActiveBackup'. 'kActiveBackup' indicates ac...
the_stack_v2_python_sparse
cohesity_management_sdk/models/create_bond_parameters.py
cohesity/management-sdk-python
train
24
d0ab132b3cb579e5158664726323eb7c121cab1d
[ "self.graph = Graph('http://IP//:7474', username='neo4j', password='xxxxx')\nself.links = []\nself.nodes = []", "select_name = '南京审计大学'\nnodes_data_all = self.graph.run('MATCH (n) RETURN n').data()\nnodes_list = []\nfor node in nodes_data_all:\n nodes_list.append(node['n']['name'])\nif select_name in nodes_lis...
<|body_start_0|> self.graph = Graph('http://IP//:7474', username='neo4j', password='xxxxx') self.links = [] self.nodes = [] <|end_body_0|> <|body_start_1|> select_name = '南京审计大学' nodes_data_all = self.graph.run('MATCH (n) RETURN n').data() nodes_list = [] for nod...
知识图谱数据接口
Neo4jToJson
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Neo4jToJson: """知识图谱数据接口""" def __init__(self): """初始化数据""" <|body_0|> def post(self): """与前端交互""" <|body_1|> def get_links(self, links_data): """知识图谱关系数据获取""" <|body_2|> def get_select_nodes(self, nodes_data): """获取知识图谱中...
stack_v2_sparse_classes_36k_train_003396
3,850
permissive
[ { "docstring": "初始化数据", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "与前端交互", "name": "post", "signature": "def post(self)" }, { "docstring": "知识图谱关系数据获取", "name": "get_links", "signature": "def get_links(self, links_data)" }, { "docstri...
5
stack_v2_sparse_classes_30k_train_002869
Implement the Python class `Neo4jToJson` described below. Class description: 知识图谱数据接口 Method signatures and docstrings: - def __init__(self): 初始化数据 - def post(self): 与前端交互 - def get_links(self, links_data): 知识图谱关系数据获取 - def get_select_nodes(self, nodes_data): 获取知识图谱中所选择的节点数据 - def get_all_nodes(self, nodes_data): 获取知...
Implement the Python class `Neo4jToJson` described below. Class description: 知识图谱数据接口 Method signatures and docstrings: - def __init__(self): 初始化数据 - def post(self): 与前端交互 - def get_links(self, links_data): 知识图谱关系数据获取 - def get_select_nodes(self, nodes_data): 获取知识图谱中所选择的节点数据 - def get_all_nodes(self, nodes_data): 获取知...
be120ce2bb94a8e8395630218985f5e51ae087d9
<|skeleton|> class Neo4jToJson: """知识图谱数据接口""" def __init__(self): """初始化数据""" <|body_0|> def post(self): """与前端交互""" <|body_1|> def get_links(self, links_data): """知识图谱关系数据获取""" <|body_2|> def get_select_nodes(self, nodes_data): """获取知识图谱中...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Neo4jToJson: """知识图谱数据接口""" def __init__(self): """初始化数据""" self.graph = Graph('http://IP//:7474', username='neo4j', password='xxxxx') self.links = [] self.nodes = [] def post(self): """与前端交互""" select_name = '南京审计大学' nodes_data_all = self.grap...
the_stack_v2_python_sparse
KnowledgeMapping/spark/connNeo4j/read_neo4j.py
nickliqian/keep_learning
train
8
b761155f673cc22acd2b9dd7f35dba9a81d581cd
[ "dict_string_set = set()\nres = 0\nfor string in A:\n odd_counts = dict()\n even_counts = dict()\n for i in range(len(string)):\n if i % 2:\n odd_counts[string[i]] = odd_counts.get(string[i], 0) + 1\n else:\n even_counts[string[i]] = even_counts.get(string[i], 0) + 1\n ...
<|body_start_0|> dict_string_set = set() res = 0 for string in A: odd_counts = dict() even_counts = dict() for i in range(len(string)): if i % 2: odd_counts[string[i]] = odd_counts.get(string[i], 0) + 1 else:...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def numSpecialEquivGroups(self, A): """:type A: List[str] :rtype: int""" <|body_0|> def dictToString(self, dict_left, dict_right): """Use a string to represent the elemnts of dict_left and dict_right""" <|body_1|> <|end_skeleton|> <|body_start_0|>...
stack_v2_sparse_classes_36k_train_003397
3,688
no_license
[ { "docstring": ":type A: List[str] :rtype: int", "name": "numSpecialEquivGroups", "signature": "def numSpecialEquivGroups(self, A)" }, { "docstring": "Use a string to represent the elemnts of dict_left and dict_right", "name": "dictToString", "signature": "def dictToString(self, dict_lef...
2
stack_v2_sparse_classes_30k_train_021479
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def numSpecialEquivGroups(self, A): :type A: List[str] :rtype: int - def dictToString(self, dict_left, dict_right): Use a string to represent the elemnts of dict_left and dict_ri...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def numSpecialEquivGroups(self, A): :type A: List[str] :rtype: int - def dictToString(self, dict_left, dict_right): Use a string to represent the elemnts of dict_left and dict_ri...
f96a2273c6831a8035e1adacfa452f73c599ae16
<|skeleton|> class Solution: def numSpecialEquivGroups(self, A): """:type A: List[str] :rtype: int""" <|body_0|> def dictToString(self, dict_left, dict_right): """Use a string to represent the elemnts of dict_left and dict_right""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def numSpecialEquivGroups(self, A): """:type A: List[str] :rtype: int""" dict_string_set = set() res = 0 for string in A: odd_counts = dict() even_counts = dict() for i in range(len(string)): if i % 2: ...
the_stack_v2_python_sparse
Python/GroupsofSpecial-EquivalentStrings.py
here0009/LeetCode
train
1
da9b2161bf3721eb876540e9928a3a2f3738fa30
[ "self.X = X_init\nself.Y = Y_init\nself.l = l\nself.sigma_f = sigma_f\nself.K = self.kernel(X_init, X_init)", "X = np.zeros((X1.shape[0], X2.shape[0]))\nfor m in range(X1.shape[0]):\n for n in range(X2.shape[0]):\n X[m, n] = (X1[m] - X2[n]) ** 2\nk = self.sigma_f ** 2 * np.exp(-X / (2 * self.l ** 2))\nr...
<|body_start_0|> self.X = X_init self.Y = Y_init self.l = l self.sigma_f = sigma_f self.K = self.kernel(X_init, X_init) <|end_body_0|> <|body_start_1|> X = np.zeros((X1.shape[0], X2.shape[0])) for m in range(X1.shape[0]): for n in range(X2.shape[0]): ...
Gaussian Process class
GaussianProcess
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GaussianProcess: """Gaussian Process class""" def __init__(self, X_init, Y_init, l=1, sigma_f=1): """Initializer method""" <|body_0|> def kernel(self, X1, X2): """Calculates the Kernel""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.X = X_i...
stack_v2_sparse_classes_36k_train_003398
725
no_license
[ { "docstring": "Initializer method", "name": "__init__", "signature": "def __init__(self, X_init, Y_init, l=1, sigma_f=1)" }, { "docstring": "Calculates the Kernel", "name": "kernel", "signature": "def kernel(self, X1, X2)" } ]
2
null
Implement the Python class `GaussianProcess` described below. Class description: Gaussian Process class Method signatures and docstrings: - def __init__(self, X_init, Y_init, l=1, sigma_f=1): Initializer method - def kernel(self, X1, X2): Calculates the Kernel
Implement the Python class `GaussianProcess` described below. Class description: Gaussian Process class Method signatures and docstrings: - def __init__(self, X_init, Y_init, l=1, sigma_f=1): Initializer method - def kernel(self, X1, X2): Calculates the Kernel <|skeleton|> class GaussianProcess: """Gaussian Proc...
b5e8f1253309567ca7be71b9575a150de1be3820
<|skeleton|> class GaussianProcess: """Gaussian Process class""" def __init__(self, X_init, Y_init, l=1, sigma_f=1): """Initializer method""" <|body_0|> def kernel(self, X1, X2): """Calculates the Kernel""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GaussianProcess: """Gaussian Process class""" def __init__(self, X_init, Y_init, l=1, sigma_f=1): """Initializer method""" self.X = X_init self.Y = Y_init self.l = l self.sigma_f = sigma_f self.K = self.kernel(X_init, X_init) def kernel(self, X1, X2): ...
the_stack_v2_python_sparse
unsupervised_learning/0x03-hyperparameter_tuning/0-gp.py
jadsm98/holbertonschool-machine_learning
train
0
9796a40d6b3946ffeeb4989b72535ce12509c877
[ "super(EulerResNet, self).__init__()\nself.inplanes = 64\nself.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False)\nself.bn1 = nn.BatchNorm2d(64)\nself.relu = nn.ReLU(inplace=True)\nself.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\nself.layer1 = self._make_layer(block, 64, layers...
<|body_start_0|> super(EulerResNet, self).__init__() self.inplanes = 64 self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = nn.BatchNorm2d(64) self.relu = nn.ReLU(inplace=True) self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, paddi...
Implements EulerResNet, which is used for regression for the the three Euler angles returned from HopeNet.
EulerResNet
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EulerResNet: """Implements EulerResNet, which is used for regression for the the three Euler angles returned from HopeNet.""" def __init__(self, block, layers, n_classes=1000): """Instantiates an EulerResNet object. Parameters ---------- block : layers : list (of ints) List containin...
stack_v2_sparse_classes_36k_train_003399
9,784
no_license
[ { "docstring": "Instantiates an EulerResNet object. Parameters ---------- block : layers : list (of ints) List containing layer sizes for each ``block`` instance. n_classes : int, optional The number of output classes in the regression network, by default 1000. Returns ------- None", "name": "__init__", ...
3
stack_v2_sparse_classes_30k_train_012277
Implement the Python class `EulerResNet` described below. Class description: Implements EulerResNet, which is used for regression for the the three Euler angles returned from HopeNet. Method signatures and docstrings: - def __init__(self, block, layers, n_classes=1000): Instantiates an EulerResNet object. Parameters ...
Implement the Python class `EulerResNet` described below. Class description: Implements EulerResNet, which is used for regression for the the three Euler angles returned from HopeNet. Method signatures and docstrings: - def __init__(self, block, layers, n_classes=1000): Instantiates an EulerResNet object. Parameters ...
a7c30481822ecb945e3ff6ad184d104361a40ed1
<|skeleton|> class EulerResNet: """Implements EulerResNet, which is used for regression for the the three Euler angles returned from HopeNet.""" def __init__(self, block, layers, n_classes=1000): """Instantiates an EulerResNet object. Parameters ---------- block : layers : list (of ints) List containin...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EulerResNet: """Implements EulerResNet, which is used for regression for the the three Euler angles returned from HopeNet.""" def __init__(self, block, layers, n_classes=1000): """Instantiates an EulerResNet object. Parameters ---------- block : layers : list (of ints) List containing layer sizes...
the_stack_v2_python_sparse
cheapfake/hopenet/models.py
hu-simon/cheapfake
train
0