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
25a37b381847da5cc83a0ef0fb4ca098ce5af34f
[ "is_markerless = node_types.MARKERLESS_REGEX.match\nprefix = list(takewhile(lambda l: not is_markerless(l), node['label']))\nif 'intro' in prefix:\n title = node.get('title', '').rstrip(':')\n return 'Intro: ' + title\nelif len(prefix) > 1:\n label = 'Section ' + '.'.join(prefix[1:])\n count = len(node[...
<|body_start_0|> is_markerless = node_types.MARKERLESS_REGEX.match prefix = list(takewhile(lambda l: not is_markerless(l), node['label'])) if 'intro' in prefix: title = node.get('title', '').rstrip(':') return 'Intro: ' + title elif len(prefix) > 1: la...
PreambleHTMLBuilder
[ "CC0-1.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PreambleHTMLBuilder: def human_label(node): """Derive a human-readable description for this node. Override""" <|body_0|> def process_node(self, node, indexes=None): """Overrides with custom, additional processing""" <|body_1|> <|end_skeleton|> <|body_start_...
stack_v2_sparse_classes_36k_train_007200
9,837
permissive
[ { "docstring": "Derive a human-readable description for this node. Override", "name": "human_label", "signature": "def human_label(node)" }, { "docstring": "Overrides with custom, additional processing", "name": "process_node", "signature": "def process_node(self, node, indexes=None)" ...
2
stack_v2_sparse_classes_30k_train_009236
Implement the Python class `PreambleHTMLBuilder` described below. Class description: Implement the PreambleHTMLBuilder class. Method signatures and docstrings: - def human_label(node): Derive a human-readable description for this node. Override - def process_node(self, node, indexes=None): Overrides with custom, addi...
Implement the Python class `PreambleHTMLBuilder` described below. Class description: Implement the PreambleHTMLBuilder class. Method signatures and docstrings: - def human_label(node): Derive a human-readable description for this node. Override - def process_node(self, node, indexes=None): Overrides with custom, addi...
4035701a953409bbb1987d371edc6630fd97a862
<|skeleton|> class PreambleHTMLBuilder: def human_label(node): """Derive a human-readable description for this node. Override""" <|body_0|> def process_node(self, node, indexes=None): """Overrides with custom, additional processing""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PreambleHTMLBuilder: def human_label(node): """Derive a human-readable description for this node. Override""" is_markerless = node_types.MARKERLESS_REGEX.match prefix = list(takewhile(lambda l: not is_markerless(l), node['label'])) if 'intro' in prefix: title = node...
the_stack_v2_python_sparse
regulations/generator/html_builder.py
fecgov/regulations-site
train
1
278f2a40cbc7c597776c698e8fe156404811c79b
[ "super().__init__()\nif resnet == 18:\n self.resnet = resnet18(pretrained=True)\nelif resnet == 34:\n self.resnet = resnet34(pretrained=True)\nelif resnet == 50:\n self.resnet = resnet50(pretrained=True)\nelif resnet == 101:\n self.resnet = resnet101(pretrained=True)\nelif resnet == 152:\n self.resne...
<|body_start_0|> super().__init__() if resnet == 18: self.resnet = resnet18(pretrained=True) elif resnet == 34: self.resnet = resnet34(pretrained=True) elif resnet == 50: self.resnet = resnet50(pretrained=True) elif resnet == 101: s...
A dummy detector based on the features extracted from a pretrained ResNet. The model generates a feature map based on an image. Let's call 'embedding' all the features for a location in the feature map. Using a pooling strategy we can reduce the embedding size and get an embedding over a kernel size in the feature map....
ResnetDetector
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ResnetDetector: """A dummy detector based on the features extracted from a pretrained ResNet. The model generates a feature map based on an image. Let's call 'embedding' all the features for a location in the feature map. Using a pooling strategy we can reduce the embedding size and get an embedd...
stack_v2_sparse_classes_36k_train_007201
5,809
no_license
[ { "docstring": "Initialize the model. Arguments: resnet (int, optional): The ResNet to use as feature extractor. dim (int, optional): The dimension of the embeddings to generate. pool (str, optional): The pool strategy to use. Options: 'avg' or 'max'. kernels (list of int, optional): The size of the kernels to ...
3
null
Implement the Python class `ResnetDetector` described below. Class description: A dummy detector based on the features extracted from a pretrained ResNet. The model generates a feature map based on an image. Let's call 'embedding' all the features for a location in the feature map. Using a pooling strategy we can redu...
Implement the Python class `ResnetDetector` described below. Class description: A dummy detector based on the features extracted from a pretrained ResNet. The model generates a feature map based on an image. Let's call 'embedding' all the features for a location in the feature map. Using a pooling strategy we can redu...
a22aa5b00369c2692bf4fa537bce20144d14d5cb
<|skeleton|> class ResnetDetector: """A dummy detector based on the features extracted from a pretrained ResNet. The model generates a feature map based on an image. Let's call 'embedding' all the features for a location in the feature map. Using a pooling strategy we can reduce the embedding size and get an embedd...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ResnetDetector: """A dummy detector based on the features extracted from a pretrained ResNet. The model generates a feature map based on an image. Let's call 'embedding' all the features for a location in the feature map. Using a pooling strategy we can reduce the embedding size and get an embedding over a ke...
the_stack_v2_python_sparse
torchsight/models/resnet_detector.py
SetaSouto/torchsight
train
2
b464c2ebe673d67598ea8f8dacdd5fba17859461
[ "self.Wz = np.random.normal(size=(i + h, h))\nself.bz = np.zeros((1, h))\nself.Wr = np.random.normal(size=(i + h, h))\nself.br = np.zeros((1, h))\nself.Wh = np.random.normal(size=(i + h, h))\nself.bh = np.zeros((1, h))\nself.Wy = np.random.normal(size=(h, o))\nself.by = np.zeros((1, o))", "X = np.concatenate((h_p...
<|body_start_0|> self.Wz = np.random.normal(size=(i + h, h)) self.bz = np.zeros((1, h)) self.Wr = np.random.normal(size=(i + h, h)) self.br = np.zeros((1, h)) self.Wh = np.random.normal(size=(i + h, h)) self.bh = np.zeros((1, h)) self.Wy = np.random.normal(size=(h...
GRUCell class represents a gated recurrent unit.
GRUCell
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GRUCell: """GRUCell class represents a gated recurrent unit.""" def __init__(self, i, h, o): """Initializer. Args: i: dimensionality of the data. h: dimensionality of the hidden state. o: dimensionality of the outputs.""" <|body_0|> def forward(self, h_prev, x_t): ...
stack_v2_sparse_classes_36k_train_007202
1,619
no_license
[ { "docstring": "Initializer. Args: i: dimensionality of the data. h: dimensionality of the hidden state. o: dimensionality of the outputs.", "name": "__init__", "signature": "def __init__(self, i, h, o)" }, { "docstring": "performs forward propagation for one time step. Args: h_prev: (numpy.ndar...
2
null
Implement the Python class `GRUCell` described below. Class description: GRUCell class represents a gated recurrent unit. Method signatures and docstrings: - def __init__(self, i, h, o): Initializer. Args: i: dimensionality of the data. h: dimensionality of the hidden state. o: dimensionality of the outputs. - def fo...
Implement the Python class `GRUCell` described below. Class description: GRUCell class represents a gated recurrent unit. Method signatures and docstrings: - def __init__(self, i, h, o): Initializer. Args: i: dimensionality of the data. h: dimensionality of the hidden state. o: dimensionality of the outputs. - def fo...
75274394adb52d740f6cd4000cc00bbde44b9b72
<|skeleton|> class GRUCell: """GRUCell class represents a gated recurrent unit.""" def __init__(self, i, h, o): """Initializer. Args: i: dimensionality of the data. h: dimensionality of the hidden state. o: dimensionality of the outputs.""" <|body_0|> def forward(self, h_prev, x_t): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GRUCell: """GRUCell class represents a gated recurrent unit.""" def __init__(self, i, h, o): """Initializer. Args: i: dimensionality of the data. h: dimensionality of the hidden state. o: dimensionality of the outputs.""" self.Wz = np.random.normal(size=(i + h, h)) self.bz = np.ze...
the_stack_v2_python_sparse
supervised_learning/0x0D-RNNs/2-gru_cell.py
jdarangop/holbertonschool-machine_learning
train
2
d4ba11fd5a9899cdfdc3bf550688a6ed4fc481fa
[ "super().define(spec)\nspec.input('nnkp_file', valid_type=SinglefileData, help='A SinglefileData containing the .nnkp file generated by wannier90.x -pp')\nspec.input('parent_folder', valid_type=(RemoteData, FolderData), help='The output folder of a pw.x calculation')\nspec.output('output_parameters', valid_type=Dic...
<|body_start_0|> super().define(spec) spec.input('nnkp_file', valid_type=SinglefileData, help='A SinglefileData containing the .nnkp file generated by wannier90.x -pp') spec.input('parent_folder', valid_type=(RemoteData, FolderData), help='The output folder of a pw.x calculation') spec.o...
`CalcJob` implementation for the pw2wannier.x code of Quantum ESPRESSO. For more information, refer to http://www.quantum-espresso.org/ and http://www.wannier.org/
Pw2wannier90Calculation
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Pw2wannier90Calculation: """`CalcJob` implementation for the pw2wannier.x code of Quantum ESPRESSO. For more information, refer to http://www.quantum-espresso.org/ and http://www.wannier.org/""" def define(cls, spec): """Define the process specification.""" <|body_0|> de...
stack_v2_sparse_classes_36k_train_007203
2,758
permissive
[ { "docstring": "Define the process specification.", "name": "define", "signature": "def define(cls, spec)" }, { "docstring": "Prepare the calculation job for submission by transforming input nodes into input files. In addition to the input files being written to the sandbox folder, a `CalcInfo` ...
2
stack_v2_sparse_classes_30k_train_015244
Implement the Python class `Pw2wannier90Calculation` described below. Class description: `CalcJob` implementation for the pw2wannier.x code of Quantum ESPRESSO. For more information, refer to http://www.quantum-espresso.org/ and http://www.wannier.org/ Method signatures and docstrings: - def define(cls, spec): Define...
Implement the Python class `Pw2wannier90Calculation` described below. Class description: `CalcJob` implementation for the pw2wannier.x code of Quantum ESPRESSO. For more information, refer to http://www.quantum-espresso.org/ and http://www.wannier.org/ Method signatures and docstrings: - def define(cls, spec): Define...
7263f92ccabcfc9f828b9da5473e1aefbc4b8eca
<|skeleton|> class Pw2wannier90Calculation: """`CalcJob` implementation for the pw2wannier.x code of Quantum ESPRESSO. For more information, refer to http://www.quantum-espresso.org/ and http://www.wannier.org/""" def define(cls, spec): """Define the process specification.""" <|body_0|> de...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Pw2wannier90Calculation: """`CalcJob` implementation for the pw2wannier.x code of Quantum ESPRESSO. For more information, refer to http://www.quantum-espresso.org/ and http://www.wannier.org/""" def define(cls, spec): """Define the process specification.""" super().define(spec) sp...
the_stack_v2_python_sparse
src/aiida_quantumespresso/calculations/pw2wannier90.py
aiidateam/aiida-quantumespresso
train
56
e9106ab6d800b414e4c34861e06a476967d131bc
[ "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...
Template rpc Function(Request) returns (Message) {}
RouteServicer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RouteServicer: """Template rpc Function(Request) returns (Message) {}""" def InitialiseAlgorithm(self, request, context): """Initialise indicator, strategy, parameters""" <|body_0|> def GetStatistics(self, request, context): """Get statistics""" <|body_1|...
stack_v2_sparse_classes_36k_train_007204
3,635
no_license
[ { "docstring": "Initialise indicator, strategy, parameters", "name": "InitialiseAlgorithm", "signature": "def InitialiseAlgorithm(self, request, context)" }, { "docstring": "Get statistics", "name": "GetStatistics", "signature": "def GetStatistics(self, request, context)" } ]
2
stack_v2_sparse_classes_30k_train_008789
Implement the Python class `RouteServicer` described below. Class description: Template rpc Function(Request) returns (Message) {} Method signatures and docstrings: - def InitialiseAlgorithm(self, request, context): Initialise indicator, strategy, parameters - def GetStatistics(self, request, context): Get statistics
Implement the Python class `RouteServicer` described below. Class description: Template rpc Function(Request) returns (Message) {} Method signatures and docstrings: - def InitialiseAlgorithm(self, request, context): Initialise indicator, strategy, parameters - def GetStatistics(self, request, context): Get statistics...
2e8cb1ebe40385e9326eb44d1989ae7eb8d8bd08
<|skeleton|> class RouteServicer: """Template rpc Function(Request) returns (Message) {}""" def InitialiseAlgorithm(self, request, context): """Initialise indicator, strategy, parameters""" <|body_0|> def GetStatistics(self, request, context): """Get statistics""" <|body_1|...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RouteServicer: """Template rpc Function(Request) returns (Message) {}""" def InitialiseAlgorithm(self, request, context): """Initialise indicator, strategy, parameters""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise N...
the_stack_v2_python_sparse
.ipynb_checkpoints/route_pb2_grpc-checkpoint.py
CryptopoolSpace/Idle-Trading-Hero
train
0
6efa253af6e9cf2cb89ee7a94d1e75b9634c7ab4
[ "self.traversal = []\nnew_node = NodeBST(value, level_here)\nif not self.item:\n self.item = new_node\nelif value < self.item:\n self.left = self.left and self.left._addNextNode(value, level_here + 1) or new_node\nelse:\n self.right = self.right and self.right._addNextNode(value, level_here + 1) or new_nod...
<|body_start_0|> self.traversal = [] new_node = NodeBST(value, level_here) if not self.item: self.item = new_node elif value < self.item: self.left = self.left and self.left._addNextNode(value, level_here + 1) or new_node else: self.right = sel...
NodeBST
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NodeBST: def _addNextNode(self, value, level_here=1): """Aux for self.addNode(value): for BST, best O(1), worst O(log n)""" <|body_0|> def _searchForNode(self, value): """Traverse the tree looking for the node. For BST it is O(logn) if the tree is balanced, otherwise...
stack_v2_sparse_classes_36k_train_007205
3,234
permissive
[ { "docstring": "Aux for self.addNode(value): for BST, best O(1), worst O(log n)", "name": "_addNextNode", "signature": "def _addNextNode(self, value, level_here=1)" }, { "docstring": "Traverse the tree looking for the node. For BST it is O(logn) if the tree is balanced, otherwise it can be O(n)"...
2
stack_v2_sparse_classes_30k_train_014014
Implement the Python class `NodeBST` described below. Class description: Implement the NodeBST class. Method signatures and docstrings: - def _addNextNode(self, value, level_here=1): Aux for self.addNode(value): for BST, best O(1), worst O(log n) - def _searchForNode(self, value): Traverse the tree looking for the no...
Implement the Python class `NodeBST` described below. Class description: Implement the NodeBST class. Method signatures and docstrings: - def _addNextNode(self, value, level_here=1): Aux for self.addNode(value): for BST, best O(1), worst O(log n) - def _searchForNode(self, value): Traverse the tree looking for the no...
5107f16df0af7ac20a52be772bd3bc46b2d4e8f6
<|skeleton|> class NodeBST: def _addNextNode(self, value, level_here=1): """Aux for self.addNode(value): for BST, best O(1), worst O(log n)""" <|body_0|> def _searchForNode(self, value): """Traverse the tree looking for the node. For BST it is O(logn) if the tree is balanced, otherwise...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NodeBST: def _addNextNode(self, value, level_here=1): """Aux for self.addNode(value): for BST, best O(1), worst O(log n)""" self.traversal = [] new_node = NodeBST(value, level_here) if not self.item: self.item = new_node elif value < self.item: s...
the_stack_v2_python_sparse
src/further_examples/trees_graphs/binary_search_tree.py
ricardo64/Over-100-Exercises-Python-and-Algorithms
train
5
b21620639463b2e4632c167fabfe9d5edc10f3c7
[ "nums.sort()\nidx = 1\nwhile idx < len(nums):\n if nums[idx] != nums[idx - 1]:\n return nums[idx - 1]\n else:\n idx += 2\nelse:\n return nums[-1]", "sumof = 0\ni = 0\nwhile i < len(nums):\n sumof = sumof ^ nums[i]\n print(sumof)\n i = i + 1\nreturn sumof" ]
<|body_start_0|> nums.sort() idx = 1 while idx < len(nums): if nums[idx] != nums[idx - 1]: return nums[idx - 1] else: idx += 2 else: return nums[-1] <|end_body_0|> <|body_start_1|> sumof = 0 i = 0 ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def singleNumber(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def _singleNumber(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> nums.sort() idx = 1 while ...
stack_v2_sparse_classes_36k_train_007206
1,064
no_license
[ { "docstring": ":type nums: List[int] :rtype: int", "name": "singleNumber", "signature": "def singleNumber(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: int", "name": "_singleNumber", "signature": "def _singleNumber(self, nums)" } ]
2
stack_v2_sparse_classes_30k_train_019778
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def singleNumber(self, nums): :type nums: List[int] :rtype: int - def _singleNumber(self, nums): :type nums: List[int] :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def singleNumber(self, nums): :type nums: List[int] :rtype: int - def _singleNumber(self, nums): :type nums: List[int] :rtype: int <|skeleton|> class Solution: def singleNu...
3e72dcaa579f4ae6f587898dd316fce8189b3d6a
<|skeleton|> class Solution: def singleNumber(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def _singleNumber(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def singleNumber(self, nums): """:type nums: List[int] :rtype: int""" nums.sort() idx = 1 while idx < len(nums): if nums[idx] != nums[idx - 1]: return nums[idx - 1] else: idx += 2 else: return...
the_stack_v2_python_sparse
problems100_200/136_Single_Number.py
Provinm/leetcode_archive
train
0
42a3c0f5e91bf8939ca22df830cfad0989c6fd6a
[ "if not proto_obj.last_update_source:\n raise GameModelError('No update source specified in Game creation.')\nreturn Game(id_str=proto_obj.id_str, teams=[Team.FromProto(tm) for tm in proto_obj.teams], scores=proto_obj.scores, name=proto_obj.name, tournament_id=proto_obj.tournament_id_str, tournament_name=proto_o...
<|body_start_0|> if not proto_obj.last_update_source: raise GameModelError('No update source specified in Game creation.') return Game(id_str=proto_obj.id_str, teams=[Team.FromProto(tm) for tm in proto_obj.teams], scores=proto_obj.scores, name=proto_obj.name, tournament_id=proto_obj.tourname...
Information about a single game including all sources.
Game
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Game: """Information about a single game including all sources.""" def FromProto(cls, proto_obj): """Builds a Game object from a protobuf object.""" <|body_0|> def FromTweet(cls, twt, teams, scores, division, age_bracket, league): """Builds a Game object from a t...
stack_v2_sparse_classes_36k_train_007207
18,736
permissive
[ { "docstring": "Builds a Game object from a protobuf object.", "name": "FromProto", "signature": "def FromProto(cls, proto_obj)" }, { "docstring": "Builds a Game object from a tweet and the specified teams. Args: twt: The tweets.Tweet object teams: A list of exactly two Team objects derived from...
4
stack_v2_sparse_classes_30k_train_015141
Implement the Python class `Game` described below. Class description: Information about a single game including all sources. Method signatures and docstrings: - def FromProto(cls, proto_obj): Builds a Game object from a protobuf object. - def FromTweet(cls, twt, teams, scores, division, age_bracket, league): Builds a...
Implement the Python class `Game` described below. Class description: Information about a single game including all sources. Method signatures and docstrings: - def FromProto(cls, proto_obj): Builds a Game object from a protobuf object. - def FromTweet(cls, twt, teams, scores, division, age_bracket, league): Builds a...
58197798a0a3a4fbcd54ffa0a2fab2e865985bfd
<|skeleton|> class Game: """Information about a single game including all sources.""" def FromProto(cls, proto_obj): """Builds a Game object from a protobuf object.""" <|body_0|> def FromTweet(cls, twt, teams, scores, division, age_bracket, league): """Builds a Game object from a t...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Game: """Information about a single game including all sources.""" def FromProto(cls, proto_obj): """Builds a Game object from a protobuf object.""" if not proto_obj.last_update_source: raise GameModelError('No update source specified in Game creation.') return Game(id...
the_stack_v2_python_sparse
game_model.py
martincochran/score-minion
train
0
2ff3fc6943cc2a3f7b2f073e5adf2279db3cc719
[ "self.begin = Block()\nself.end = Block()\nself.begin.after = self.end\nself.end.before = self.begin\nself.mapping = {}", "if not key in self.mapping:\n current_block = self.begin\nelse:\n current_block = self.mapping[key]\n current_block.keys.remove(key)\nif current_block.val + 1 != current_block.after....
<|body_start_0|> self.begin = Block() self.end = Block() self.begin.after = self.end self.end.before = self.begin self.mapping = {} <|end_body_0|> <|body_start_1|> if not key in self.mapping: current_block = self.begin else: current_block ...
AllOne
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AllOne: def __init__(self): """Initialize your data structure here.""" <|body_0|> def inc(self, key: str) -> None: """Inserts a new key <Key> with value 1. Or increments an existing key by 1.""" <|body_1|> def dec(self, key: str) -> None: """Decr...
stack_v2_sparse_classes_36k_train_007208
3,495
permissive
[ { "docstring": "Initialize your data structure here.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Inserts a new key <Key> with value 1. Or increments an existing key by 1.", "name": "inc", "signature": "def inc(self, key: str) -> None" }, { "docstrin...
5
null
Implement the Python class `AllOne` described below. Class description: Implement the AllOne class. Method signatures and docstrings: - def __init__(self): Initialize your data structure here. - def inc(self, key: str) -> None: Inserts a new key <Key> with value 1. Or increments an existing key by 1. - def dec(self, ...
Implement the Python class `AllOne` described below. Class description: Implement the AllOne class. Method signatures and docstrings: - def __init__(self): Initialize your data structure here. - def inc(self, key: str) -> None: Inserts a new key <Key> with value 1. Or increments an existing key by 1. - def dec(self, ...
eb7f2fb142b8a30d987c5ac8002a96ead0aa56f4
<|skeleton|> class AllOne: def __init__(self): """Initialize your data structure here.""" <|body_0|> def inc(self, key: str) -> None: """Inserts a new key <Key> with value 1. Or increments an existing key by 1.""" <|body_1|> def dec(self, key: str) -> None: """Decr...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AllOne: def __init__(self): """Initialize your data structure here.""" self.begin = Block() self.end = Block() self.begin.after = self.end self.end.before = self.begin self.mapping = {} def inc(self, key: str) -> None: """Inserts a new key <Key> wit...
the_stack_v2_python_sparse
python/432.全O(1)的数据结构.py
Wanger-SJTU/leetcode-solutions
train
1
ed41bfc5515008d62eee2b4e11ec55f39c8710c4
[ "query = request.GET.get('q')\nsort = request.GET.get('sort', 'name')\nasearch = Server.objects.filter(id=kwargs['id']).first()\nform = ServerEditForm(instance=asearch)\nlist_server = None\nif query:\n list_server = Server.objects.filter(Q(name__icontains=query))\nelse:\n list_server = Server.objects.all()\np...
<|body_start_0|> query = request.GET.get('q') sort = request.GET.get('sort', 'name') asearch = Server.objects.filter(id=kwargs['id']).first() form = ServerEditForm(instance=asearch) list_server = None if query: list_server = Server.objects.filter(Q(name__icont...
Clase para editar los servidores
ServerEditView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ServerEditView: """Clase para editar los servidores""" def get(self, request, *args, **kwargs): """Método get""" <|body_0|> def post(self, request, *args, **kwargs): """Método post""" <|body_1|> <|end_skeleton|> <|body_start_0|> query = request....
stack_v2_sparse_classes_36k_train_007209
22,221
no_license
[ { "docstring": "Método get", "name": "get", "signature": "def get(self, request, *args, **kwargs)" }, { "docstring": "Método post", "name": "post", "signature": "def post(self, request, *args, **kwargs)" } ]
2
stack_v2_sparse_classes_30k_train_001183
Implement the Python class `ServerEditView` described below. Class description: Clase para editar los servidores Method signatures and docstrings: - def get(self, request, *args, **kwargs): Método get - def post(self, request, *args, **kwargs): Método post
Implement the Python class `ServerEditView` described below. Class description: Clase para editar los servidores Method signatures and docstrings: - def get(self, request, *args, **kwargs): Método get - def post(self, request, *args, **kwargs): Método post <|skeleton|> class ServerEditView: """Clase para editar ...
e28e2d968372609ad396c42fb572a00c2410a117
<|skeleton|> class ServerEditView: """Clase para editar los servidores""" def get(self, request, *args, **kwargs): """Método get""" <|body_0|> def post(self, request, *args, **kwargs): """Método post""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ServerEditView: """Clase para editar los servidores""" def get(self, request, *args, **kwargs): """Método get""" query = request.GET.get('q') sort = request.GET.get('sort', 'name') asearch = Server.objects.filter(id=kwargs['id']).first() form = ServerEditForm(insta...
the_stack_v2_python_sparse
list/views.py
damaos/server_list2
train
0
67be9e4ddf187ba142ea695f636c91308125f766
[ "cap = cv2.VideoCapture(video_path)\n_, frame = cap.read()\nfig, ax = plt.subplots(figsize=(20, 10))\nax.imshow(frame)\nxlims = ax.get_xlim()\nylims = ax.get_ylim()\nax.set_xticks(np.arange(xlims[0], xlims[-1], 50))\nax.set_yticks(np.arange(ylims[0], ylims[-1], -50))\nax.grid(visible=True, color='white', lw=0.5, al...
<|body_start_0|> cap = cv2.VideoCapture(video_path) _, frame = cap.read() fig, ax = plt.subplots(figsize=(20, 10)) ax.imshow(frame) xlims = ax.get_xlim() ylims = ax.get_ylim() ax.set_xticks(np.arange(xlims[0], xlims[-1], 50)) ax.set_yticks(np.arange(ylims[...
DLCPoseEstimationSelection
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DLCPoseEstimationSelection: def get_video_crop(cls, video_path): """Queries the user to determine the cropping parameters for a given video Parameters ---------- video_path : str path to the video file Returns ------- crop_ints : list list of 4 integers [x min, x max, y min, y max]""" ...
stack_v2_sparse_classes_36k_train_007210
16,324
permissive
[ { "docstring": "Queries the user to determine the cropping parameters for a given video Parameters ---------- video_path : str path to the video file Returns ------- crop_ints : list list of 4 integers [x min, x max, y min, y max]", "name": "get_video_crop", "signature": "def get_video_crop(cls, video_p...
2
stack_v2_sparse_classes_30k_train_018959
Implement the Python class `DLCPoseEstimationSelection` described below. Class description: Implement the DLCPoseEstimationSelection class. Method signatures and docstrings: - def get_video_crop(cls, video_path): Queries the user to determine the cropping parameters for a given video Parameters ---------- video_path ...
Implement the Python class `DLCPoseEstimationSelection` described below. Class description: Implement the DLCPoseEstimationSelection class. Method signatures and docstrings: - def get_video_crop(cls, video_path): Queries the user to determine the cropping parameters for a given video Parameters ---------- video_path ...
b396f1caad76d7f90b70d9937ea108a92a2fb074
<|skeleton|> class DLCPoseEstimationSelection: def get_video_crop(cls, video_path): """Queries the user to determine the cropping parameters for a given video Parameters ---------- video_path : str path to the video file Returns ------- crop_ints : list list of 4 integers [x min, x max, y min, y max]""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DLCPoseEstimationSelection: def get_video_crop(cls, video_path): """Queries the user to determine the cropping parameters for a given video Parameters ---------- video_path : str path to the video file Returns ------- crop_ints : list list of 4 integers [x min, x max, y min, y max]""" cap = cv...
the_stack_v2_python_sparse
src/spyglass/position/v1/position_dlc_pose_estimation.py
LorenFrankLab/spyglass
train
46
1e31d43762e4fa63dc32a1b9216399a47d518d83
[ "test_class = CLFMonitor('')\ntest_class.hit_average = {'current_hit_count': (AVERAGE_TRAFFIC_TOLERANCE + 1) * AVERAGE_TRAFFIC_INTERVAL, 'average_count': 0, 'last_taken': datetime.now() - timedelta(seconds=AVERAGE_TRAFFIC_INTERVAL + 10)}\ntest_class.update_average()\nself.assertTrue(test_class.high_traffic_mode)", ...
<|body_start_0|> test_class = CLFMonitor('') test_class.hit_average = {'current_hit_count': (AVERAGE_TRAFFIC_TOLERANCE + 1) * AVERAGE_TRAFFIC_INTERVAL, 'average_count': 0, 'last_taken': datetime.now() - timedelta(seconds=AVERAGE_TRAFFIC_INTERVAL + 10)} test_class.update_average() self.as...
Test the alert case.
TestAlerts
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestAlerts: """Test the alert case.""" def test_high_traffic_exceed(self): """Test to see if there is high traffic.""" <|body_0|> def test_high_traffic_recede(self): """Test to see if the recession of traffic is understood.""" <|body_1|> <|end_skeleton|>...
stack_v2_sparse_classes_36k_train_007211
1,696
no_license
[ { "docstring": "Test to see if there is high traffic.", "name": "test_high_traffic_exceed", "signature": "def test_high_traffic_exceed(self)" }, { "docstring": "Test to see if the recession of traffic is understood.", "name": "test_high_traffic_recede", "signature": "def test_high_traffi...
2
stack_v2_sparse_classes_30k_train_008014
Implement the Python class `TestAlerts` described below. Class description: Test the alert case. Method signatures and docstrings: - def test_high_traffic_exceed(self): Test to see if there is high traffic. - def test_high_traffic_recede(self): Test to see if the recession of traffic is understood.
Implement the Python class `TestAlerts` described below. Class description: Test the alert case. Method signatures and docstrings: - def test_high_traffic_exceed(self): Test to see if there is high traffic. - def test_high_traffic_recede(self): Test to see if the recession of traffic is understood. <|skeleton|> clas...
509e418042a54f314f74e5326d89c584aeecf171
<|skeleton|> class TestAlerts: """Test the alert case.""" def test_high_traffic_exceed(self): """Test to see if there is high traffic.""" <|body_0|> def test_high_traffic_recede(self): """Test to see if the recession of traffic is understood.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestAlerts: """Test the alert case.""" def test_high_traffic_exceed(self): """Test to see if there is high traffic.""" test_class = CLFMonitor('') test_class.hit_average = {'current_hit_count': (AVERAGE_TRAFFIC_TOLERANCE + 1) * AVERAGE_TRAFFIC_INTERVAL, 'average_count': 0, 'last_t...
the_stack_v2_python_sparse
pre2022/Datadog/interview/test_high_traffic_alerts.py
sinanm89/Interview-Questions
train
1
b78075e72465eb318933fba9584ae4154540b444
[ "if not b:\n need_seconds = a[0]\nelse:\n need_seconds = self.least_need_second(a, b)\nhours = need_seconds // 3600\nmins = (need_seconds - hours * 3600) // 60\nseconds = need_seconds % 60\nif hours + 8 >= 12:\n end = 'pm'\n hours = hours + 8 - 12\n hours_str = ('0' if hours < 10 else '') + str(hours...
<|body_start_0|> if not b: need_seconds = a[0] else: need_seconds = self.least_need_second(a, b) hours = need_seconds // 3600 mins = (need_seconds - hours * 3600) // 60 seconds = need_seconds % 60 if hours + 8 >= 12: end = 'pm' ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def earlest_off_time(self, a, b): """Args: a: list[int] b: list[int] Return: str""" <|body_0|> def least_need_second(self, a, b): """Args: a: list[int] b: list[int] Return: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> if not b: ...
stack_v2_sparse_classes_36k_train_007212
2,060
no_license
[ { "docstring": "Args: a: list[int] b: list[int] Return: str", "name": "earlest_off_time", "signature": "def earlest_off_time(self, a, b)" }, { "docstring": "Args: a: list[int] b: list[int] Return: int", "name": "least_need_second", "signature": "def least_need_second(self, a, b)" } ]
2
stack_v2_sparse_classes_30k_train_009219
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def earlest_off_time(self, a, b): Args: a: list[int] b: list[int] Return: str - def least_need_second(self, a, b): Args: a: list[int] b: list[int] Return: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def earlest_off_time(self, a, b): Args: a: list[int] b: list[int] Return: str - def least_need_second(self, a, b): Args: a: list[int] b: list[int] Return: int <|skeleton|> class...
101bce2fac8b188a4eb2f5e017293d21ad0ecb21
<|skeleton|> class Solution: def earlest_off_time(self, a, b): """Args: a: list[int] b: list[int] Return: str""" <|body_0|> def least_need_second(self, a, b): """Args: a: list[int] b: list[int] Return: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def earlest_off_time(self, a, b): """Args: a: list[int] b: list[int] Return: str""" if not b: need_seconds = a[0] else: need_seconds = self.least_need_second(a, b) hours = need_seconds // 3600 mins = (need_seconds - hours * 3600) // 60 ...
the_stack_v2_python_sparse
秋招/网易/3.py
AiZhanghan/Leetcode
train
0
ee544876b8cc667ea4be09384f3a8058bef3930b
[ "ret = BaseUtils()\ntry:\n queryset = models.Course.objects.all()\n ser = CourseSerializer(instance=queryset, many=True)\n ret.data = ser.data\n ret.code = 1000\nexcept Exception as e:\n ret.code = 1001\n ret.error = '获取课程失败'\nreturn Response(ret.dict)", "ret = {'code': 1000, 'data': None}\nset ...
<|body_start_0|> ret = BaseUtils() try: queryset = models.Course.objects.all() ser = CourseSerializer(instance=queryset, many=True) ret.data = ser.data ret.code = 1000 except Exception as e: ret.code = 1001 ret.error = '获取课程...
CourseView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CourseView: def list(self, request, *args, **kwargs): """课程列表 :param request: :param args: :param kwargs: :return:""" <|body_0|> def post(self, request, *args, **kwargs): """创建课程 :param request: :param args: :param kwargs: :return:""" <|body_1|> def retr...
stack_v2_sparse_classes_36k_train_007213
2,869
no_license
[ { "docstring": "课程列表 :param request: :param args: :param kwargs: :return:", "name": "list", "signature": "def list(self, request, *args, **kwargs)" }, { "docstring": "创建课程 :param request: :param args: :param kwargs: :return:", "name": "post", "signature": "def post(self, request, *args, ...
4
stack_v2_sparse_classes_30k_train_017838
Implement the Python class `CourseView` described below. Class description: Implement the CourseView class. Method signatures and docstrings: - def list(self, request, *args, **kwargs): 课程列表 :param request: :param args: :param kwargs: :return: - def post(self, request, *args, **kwargs): 创建课程 :param request: :param ar...
Implement the Python class `CourseView` described below. Class description: Implement the CourseView class. Method signatures and docstrings: - def list(self, request, *args, **kwargs): 课程列表 :param request: :param args: :param kwargs: :return: - def post(self, request, *args, **kwargs): 创建课程 :param request: :param ar...
306ce096537ac3e71ee7530ee58b43a9c3f25489
<|skeleton|> class CourseView: def list(self, request, *args, **kwargs): """课程列表 :param request: :param args: :param kwargs: :return:""" <|body_0|> def post(self, request, *args, **kwargs): """创建课程 :param request: :param args: :param kwargs: :return:""" <|body_1|> def retr...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CourseView: def list(self, request, *args, **kwargs): """课程列表 :param request: :param args: :param kwargs: :return:""" ret = BaseUtils() try: queryset = models.Course.objects.all() ser = CourseSerializer(instance=queryset, many=True) ret.data = ser.da...
the_stack_v2_python_sparse
luffapi/views/course.py
xxt123456/luffcity
train
0
1c6c69e12eccccc3287fa81fdd1566bbcab1641a
[ "if columns_drop is not None:\n if isinstance(columns_drop, list) or isinstance(columns_drop, tuple):\n self.columns_drop = columns_drop\n else:\n raise NameError('Invalid type {}'.format(type(columns_drop)))\nelse:\n self.columns_drop = columns_drop\nself.random_state = random_state", "if ...
<|body_start_0|> if columns_drop is not None: if isinstance(columns_drop, list) or isinstance(columns_drop, tuple): self.columns_drop = columns_drop else: raise NameError('Invalid type {}'.format(type(columns_drop))) else: self.columns_...
This transformer drop features. Attributes ---------- columns: list of columns to transformer [n_columns] Examples -------- For usage examples, please see https://jaisenbe58r.github.io/MLearner/user_guide/preprocessing/DropFeatures/
DropFeatures
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DropFeatures: """This transformer drop features. Attributes ---------- columns: list of columns to transformer [n_columns] Examples -------- For usage examples, please see https://jaisenbe58r.github.io/MLearner/user_guide/preprocessing/DropFeatures/""" def __init__(self, columns_drop=None, r...
stack_v2_sparse_classes_36k_train_007214
6,690
permissive
[ { "docstring": "Init replace missing values.", "name": "__init__", "signature": "def __init__(self, columns_drop=None, random_state=99)" }, { "docstring": "Gets the columns to make a replace missing values. Parameters ---------- X : {Dataframe}, shape = [n_samples, n_features] Dataframe, where n...
3
stack_v2_sparse_classes_30k_train_018065
Implement the Python class `DropFeatures` described below. Class description: This transformer drop features. Attributes ---------- columns: list of columns to transformer [n_columns] Examples -------- For usage examples, please see https://jaisenbe58r.github.io/MLearner/user_guide/preprocessing/DropFeatures/ Method ...
Implement the Python class `DropFeatures` described below. Class description: This transformer drop features. Attributes ---------- columns: list of columns to transformer [n_columns] Examples -------- For usage examples, please see https://jaisenbe58r.github.io/MLearner/user_guide/preprocessing/DropFeatures/ Method ...
e768a4cad150b35fb5bf543ab28aa23764af51d9
<|skeleton|> class DropFeatures: """This transformer drop features. Attributes ---------- columns: list of columns to transformer [n_columns] Examples -------- For usage examples, please see https://jaisenbe58r.github.io/MLearner/user_guide/preprocessing/DropFeatures/""" def __init__(self, columns_drop=None, r...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DropFeatures: """This transformer drop features. Attributes ---------- columns: list of columns to transformer [n_columns] Examples -------- For usage examples, please see https://jaisenbe58r.github.io/MLearner/user_guide/preprocessing/DropFeatures/""" def __init__(self, columns_drop=None, random_state=9...
the_stack_v2_python_sparse
mlearner/preprocessing/feature_selector.py
jaisenbe58r/MLearner
train
9
68c5ba3641ce0f63a61c465a6d2964ade0dddf21
[ "ser = CreatePurseSerializer(data=wallet, partial=True)\nif ser.is_valid():\n ser.save()", "serializer = PayCertificationSerializer(data=data_info, partial=True)\nif serializer.is_valid():\n serializer.save()", "serializer = EnterpriseCertificationSerializer(data=data)\nif serializer.is_valid():\n seri...
<|body_start_0|> ser = CreatePurseSerializer(data=wallet, partial=True) if ser.is_valid(): ser.save() <|end_body_0|> <|body_start_1|> serializer = PayCertificationSerializer(data=data_info, partial=True) if serializer.is_valid(): serializer.save() <|end_body_1|> ...
Serializers_obj
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Serializers_obj: def createpurse(self, wallet): """调起支付接口保存""" <|body_0|> def pay(self, data_info): """支付保存""" <|body_1|> def enterprise(self, data): """认证企业保存""" <|body_2|> def recordupdate(self, obj, data): """订单记录更新""" ...
stack_v2_sparse_classes_36k_train_007215
2,067
no_license
[ { "docstring": "调起支付接口保存", "name": "createpurse", "signature": "def createpurse(self, wallet)" }, { "docstring": "支付保存", "name": "pay", "signature": "def pay(self, data_info)" }, { "docstring": "认证企业保存", "name": "enterprise", "signature": "def enterprise(self, data)" },...
4
stack_v2_sparse_classes_30k_train_003443
Implement the Python class `Serializers_obj` described below. Class description: Implement the Serializers_obj class. Method signatures and docstrings: - def createpurse(self, wallet): 调起支付接口保存 - def pay(self, data_info): 支付保存 - def enterprise(self, data): 认证企业保存 - def recordupdate(self, obj, data): 订单记录更新
Implement the Python class `Serializers_obj` described below. Class description: Implement the Serializers_obj class. Method signatures and docstrings: - def createpurse(self, wallet): 调起支付接口保存 - def pay(self, data_info): 支付保存 - def enterprise(self, data): 认证企业保存 - def recordupdate(self, obj, data): 订单记录更新 <|skeleto...
3c18d5d5727db1562438edea66ef15f54b378e33
<|skeleton|> class Serializers_obj: def createpurse(self, wallet): """调起支付接口保存""" <|body_0|> def pay(self, data_info): """支付保存""" <|body_1|> def enterprise(self, data): """认证企业保存""" <|body_2|> def recordupdate(self, obj, data): """订单记录更新""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Serializers_obj: def createpurse(self, wallet): """调起支付接口保存""" ser = CreatePurseSerializer(data=wallet, partial=True) if ser.is_valid(): ser.save() def pay(self, data_info): """支付保存""" serializer = PayCertificationSerializer(data=data_info, partial=True...
the_stack_v2_python_sparse
up_down_chain/up_down_chain/app/Users/utils.py
wang18722/Up_down_chain
train
0
982f13d184a5f1397a39b3ff9b4a0c7317a33f17
[ "if money_string.startswith('-'):\n raise ValueError('金额不能为负数!!')\ntry:\n money_number = float(money_string)\n return money_number\nexcept:\n raise ValueError('货币的金额必须为数字!')", "while True:\n RMB_string = input('请输入要转换的金额:')\n RMB_number = 0.0\n try:\n RMB_number = MoneyTransfer.check_n...
<|body_start_0|> if money_string.startswith('-'): raise ValueError('金额不能为负数!!') try: money_number = float(money_string) return money_number except: raise ValueError('货币的金额必须为数字!') <|end_body_0|> <|body_start_1|> while True: RMB...
MoneyTransfer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MoneyTransfer: def check_number(money_string: str): """校验输入的金额是否有效 :return:""" <|body_0|> def input_money(): """输入人命币金额,并做校验 :return:""" <|body_1|> def build_chinese_money(money: str): """实现数字转换为大写 :param money: :return:""" <|body_2|> ...
stack_v2_sparse_classes_36k_train_007216
5,126
no_license
[ { "docstring": "校验输入的金额是否有效 :return:", "name": "check_number", "signature": "def check_number(money_string: str)" }, { "docstring": "输入人命币金额,并做校验 :return:", "name": "input_money", "signature": "def input_money()" }, { "docstring": "实现数字转换为大写 :param money: :return:", "name": "...
4
null
Implement the Python class `MoneyTransfer` described below. Class description: Implement the MoneyTransfer class. Method signatures and docstrings: - def check_number(money_string: str): 校验输入的金额是否有效 :return: - def input_money(): 输入人命币金额,并做校验 :return: - def build_chinese_money(money: str): 实现数字转换为大写 :param money: :ret...
Implement the Python class `MoneyTransfer` described below. Class description: Implement the MoneyTransfer class. Method signatures and docstrings: - def check_number(money_string: str): 校验输入的金额是否有效 :return: - def input_money(): 输入人命币金额,并做校验 :return: - def build_chinese_money(money: str): 实现数字转换为大写 :param money: :ret...
23cb26865c1a5fc42cd50ef15e4c2619ce363289
<|skeleton|> class MoneyTransfer: def check_number(money_string: str): """校验输入的金额是否有效 :return:""" <|body_0|> def input_money(): """输入人命币金额,并做校验 :return:""" <|body_1|> def build_chinese_money(money: str): """实现数字转换为大写 :param money: :return:""" <|body_2|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MoneyTransfer: def check_number(money_string: str): """校验输入的金额是否有效 :return:""" if money_string.startswith('-'): raise ValueError('金额不能为负数!!') try: money_number = float(money_string) return money_number except: raise ValueError('货币...
the_stack_v2_python_sparse
Demo/第一季案例/第七章list集合/7.4.py
iezyzhang/Project
train
0
a784f23fc81cbdcc2f8ae412a38a01ae5c4fce04
[ "super(CommentWidget, self).__init__(parent)\nself.setupUi(self)\nself.setFrameShadow(self.Sunken)\nself.setFrameStyle(self.StyledPanel)\nself.setFrameShadow(self.Sunken)\nuser_pix = get_icon('glyphicons_003_user.png', aspix=True)\nself.user_lb.setPixmap(user_pix)", "item = index.internalPointer()\nnote = item.in...
<|body_start_0|> super(CommentWidget, self).__init__(parent) self.setupUi(self) self.setFrameShadow(self.Sunken) self.setFrameStyle(self.StyledPanel) self.setFrameShadow(self.Sunken) user_pix = get_icon('glyphicons_003_user.png', aspix=True) self.user_lb.setPixmap...
A widget to display comments
CommentWidget
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CommentWidget: """A widget to display comments""" def __init__(self, parent=None): """Create a new CommentWidget :param parent: widget parent :type parent: QtGui.QWidget :raises: None""" <|body_0|> def set_index(self, index): """Display the data of the given inde...
stack_v2_sparse_classes_36k_train_007217
1,313
permissive
[ { "docstring": "Create a new CommentWidget :param parent: widget parent :type parent: QtGui.QWidget :raises: None", "name": "__init__", "signature": "def __init__(self, parent=None)" }, { "docstring": "Display the data of the given index :param index: the index to paint :type index: QtCore.QMode...
2
stack_v2_sparse_classes_30k_train_009075
Implement the Python class `CommentWidget` described below. Class description: A widget to display comments Method signatures and docstrings: - def __init__(self, parent=None): Create a new CommentWidget :param parent: widget parent :type parent: QtGui.QWidget :raises: None - def set_index(self, index): Display the d...
Implement the Python class `CommentWidget` described below. Class description: A widget to display comments Method signatures and docstrings: - def __init__(self, parent=None): Create a new CommentWidget :param parent: widget parent :type parent: QtGui.QWidget :raises: None - def set_index(self, index): Display the d...
bac2280ca49940355270e4b69400ce9976ab2e6f
<|skeleton|> class CommentWidget: """A widget to display comments""" def __init__(self, parent=None): """Create a new CommentWidget :param parent: widget parent :type parent: QtGui.QWidget :raises: None""" <|body_0|> def set_index(self, index): """Display the data of the given inde...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CommentWidget: """A widget to display comments""" def __init__(self, parent=None): """Create a new CommentWidget :param parent: widget parent :type parent: QtGui.QWidget :raises: None""" super(CommentWidget, self).__init__(parent) self.setupUi(self) self.setFrameShadow(sel...
the_stack_v2_python_sparse
src/jukeboxcore/gui/widgets/commentwidget.py
JukeboxPipeline/jukebox-core
train
2
345ad731bfd65c3607ff6c3cf78a4c6ff6db7a3e
[ "if root is None:\n return ''\nans = []\nqueue = deque()\nqueue.append(root)\nwhile queue:\n top = queue.popleft()\n if top != None:\n ans.append(str(top.val))\n queue.append(top.left)\n queue.append(top.right)\n else:\n ans.append(str('null'))\nwhile ans[-1] == 'null':\n ...
<|body_start_0|> if root is None: return '' ans = [] queue = deque() queue.append(root) while queue: top = queue.popleft() if top != None: ans.append(str(top.val)) queue.append(top.left) queue.app...
Codec
[ "Apache-2.0" ]
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_007218
1,826
permissive
[ { "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_016376
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:...
b0705013eea8517ba7742730cd14ea8601b83c70
<|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""" if root is None: return '' ans = [] queue = deque() queue.append(root) while queue: top = queue.popleft() if top != No...
the_stack_v2_python_sparse
python/q297/q297.py
MatthewTsan/Leetcode
train
0
cbeba69753a83bd8ca5cfa143f9bbb6fe0d10b58
[ "self.temperature = temperatureFcn\nself.neighbor = neighborFcn\nself.energy = energyFcn\nself.probability = probabilityFcn", "stateHistory = []\nenergyHistory = []\ncurrentState = copy.deepcopy(initialState)\ncurrentEnergy = self.energy(currentState)\nfor fraction in np.linspace(0, 1, numIterations):\n if sav...
<|body_start_0|> self.temperature = temperatureFcn self.neighbor = neighborFcn self.energy = energyFcn self.probability = probabilityFcn <|end_body_0|> <|body_start_1|> stateHistory = [] energyHistory = [] currentState = copy.deepcopy(initialState) curren...
SimulatedAnnealing
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SimulatedAnnealing: def __init__(self, temperatureFcn, neighborFcn, energyFcn, probabilityFcn): """temperatureFcn is a function whcih takes the fraction of iterations as a parameter to simulate cooling without quenching neighborFcn is a function which takes the current state as a paramet...
stack_v2_sparse_classes_36k_train_007219
2,895
permissive
[ { "docstring": "temperatureFcn is a function whcih takes the fraction of iterations as a parameter to simulate cooling without quenching neighborFcn is a function which takes the current state as a parameter and returns a candidate state to test energyFcn takes a state and evaluates its energy, i.e. the functio...
2
stack_v2_sparse_classes_30k_val_000043
Implement the Python class `SimulatedAnnealing` described below. Class description: Implement the SimulatedAnnealing class. Method signatures and docstrings: - def __init__(self, temperatureFcn, neighborFcn, energyFcn, probabilityFcn): temperatureFcn is a function whcih takes the fraction of iterations as a parameter...
Implement the Python class `SimulatedAnnealing` described below. Class description: Implement the SimulatedAnnealing class. Method signatures and docstrings: - def __init__(self, temperatureFcn, neighborFcn, energyFcn, probabilityFcn): temperatureFcn is a function whcih takes the fraction of iterations as a parameter...
a05f6f2797ca47546609f125ebfca806839be8ad
<|skeleton|> class SimulatedAnnealing: def __init__(self, temperatureFcn, neighborFcn, energyFcn, probabilityFcn): """temperatureFcn is a function whcih takes the fraction of iterations as a parameter to simulate cooling without quenching neighborFcn is a function which takes the current state as a paramet...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SimulatedAnnealing: def __init__(self, temperatureFcn, neighborFcn, energyFcn, probabilityFcn): """temperatureFcn is a function whcih takes the fraction of iterations as a parameter to simulate cooling without quenching neighborFcn is a function which takes the current state as a parameter and returns...
the_stack_v2_python_sparse
optimization/optimization/simulatedannealing.py
doreiss/topcondmat_python_ucla
train
0
2d38b33e2636bc1ec99784cc23de2ea956052afb
[ "for rec in self:\n if rec.date_from and rec.date_to:\n f_date = datetime.strptime(rec.date_from, OE_DATEFORMAT)\n e_date = datetime.strptime(rec.date_to, OE_DATEFORMAT)\n delta = e_date - f_date\n rec.number_of_days = delta.days + 1", "worked_day_lines = []\nfor contract in contracts.filte...
<|body_start_0|> for rec in self: if rec.date_from and rec.date_to: f_date = datetime.strptime(rec.date_from, OE_DATEFORMAT) e_date = datetime.strptime(rec.date_to, OE_DATEFORMAT) delta = e_date - f_date rec.number_of_days = delta.days + 1 <|en...
HRPayslip
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HRPayslip: def compute_number_of_days(self): """:return:""" <|body_0|> def get_worked_day_lines_from_timesheets(self, contracts, date_from, date_to): """:param contracts: :param date_from: :param date_to: :return:""" <|body_1|> def get_worked_day_lines(s...
stack_v2_sparse_classes_36k_train_007220
3,163
no_license
[ { "docstring": ":return:", "name": "compute_number_of_days", "signature": "def compute_number_of_days(self)" }, { "docstring": ":param contracts: :param date_from: :param date_to: :return:", "name": "get_worked_day_lines_from_timesheets", "signature": "def get_worked_day_lines_from_times...
3
stack_v2_sparse_classes_30k_train_019046
Implement the Python class `HRPayslip` described below. Class description: Implement the HRPayslip class. Method signatures and docstrings: - def compute_number_of_days(self): :return: - def get_worked_day_lines_from_timesheets(self, contracts, date_from, date_to): :param contracts: :param date_from: :param date_to: ...
Implement the Python class `HRPayslip` described below. Class description: Implement the HRPayslip class. Method signatures and docstrings: - def compute_number_of_days(self): :return: - def get_worked_day_lines_from_timesheets(self, contracts, date_from, date_to): :param contracts: :param date_from: :param date_to: ...
437cf88c26a23b54efeed903233be6ee5d9a16aa
<|skeleton|> class HRPayslip: def compute_number_of_days(self): """:return:""" <|body_0|> def get_worked_day_lines_from_timesheets(self, contracts, date_from, date_to): """:param contracts: :param date_from: :param date_to: :return:""" <|body_1|> def get_worked_day_lines(s...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class HRPayslip: def compute_number_of_days(self): """:return:""" for rec in self: if rec.date_from and rec.date_to: f_date = datetime.strptime(rec.date_from, OE_DATEFORMAT) e_date = datetime.strptime(rec.date_to, OE_DATEFORMAT) delta = e_date ...
the_stack_v2_python_sparse
sapcle_dxb/custom-addons/hr_timesheet_ess/models/hr_payslip.py
ketulpatel35/sapcle
train
0
234d8f9428720d59412569902d46807a4146d1e2
[ "super(OSMCoord, self).__init__()\nself.long = 0\nself.lat = 0\nself.x = 0\nself.y = 0\nself.z = 0\nself.tilt = 0", "coord = OSMCoord()\ncoord.OSMID = osmid\ncoord.long = long\ncoord.lat = lat\ncoord.x, coord.y = Projection.project(coord.long, coord.lat)\nOSMCoord.coordDictionnary[osmid] = coord", "coord = OSMC...
<|body_start_0|> super(OSMCoord, self).__init__() self.long = 0 self.lat = 0 self.x = 0 self.y = 0 self.z = 0 self.tilt = 0 <|end_body_0|> <|body_start_1|> coord = OSMCoord() coord.OSMID = osmid coord.long = long coord.lat = lat ...
Represent an OSM coordinate.
OSMCoord
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OSMCoord: """Represent an OSM coordinate.""" def __init__(self): """Initialize the coordinate.""" <|body_0|> def add(osmid, long, lat): """Add a new coordinate to the list from longitude latitude.""" <|body_1|> def addFromXY(osmid, x, y, z): ...
stack_v2_sparse_classes_36k_train_007221
9,470
permissive
[ { "docstring": "Initialize the coordinate.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Add a new coordinate to the list from longitude latitude.", "name": "add", "signature": "def add(osmid, long, lat)" }, { "docstring": "Add a new coordinate to the...
6
null
Implement the Python class `OSMCoord` described below. Class description: Represent an OSM coordinate. Method signatures and docstrings: - def __init__(self): Initialize the coordinate. - def add(osmid, long, lat): Add a new coordinate to the list from longitude latitude. - def addFromXY(osmid, x, y, z): Add a new co...
Implement the Python class `OSMCoord` described below. Class description: Represent an OSM coordinate. Method signatures and docstrings: - def __init__(self): Initialize the coordinate. - def add(osmid, long, lat): Add a new coordinate to the list from longitude latitude. - def addFromXY(osmid, x, y, z): Add a new co...
8aba6eaae76989facf3442305c8089d3cc366bcf
<|skeleton|> class OSMCoord: """Represent an OSM coordinate.""" def __init__(self): """Initialize the coordinate.""" <|body_0|> def add(osmid, long, lat): """Add a new coordinate to the list from longitude latitude.""" <|body_1|> def addFromXY(osmid, x, y, z): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OSMCoord: """Represent an OSM coordinate.""" def __init__(self): """Initialize the coordinate.""" super(OSMCoord, self).__init__() self.long = 0 self.lat = 0 self.x = 0 self.y = 0 self.z = 0 self.tilt = 0 def add(osmid, long, lat): ...
the_stack_v2_python_sparse
resources/osm_importer/osm_objects.py
cyberbotics/webots
train
2,495
cb411fdfa95aa0d109b2d9fb8dff8e84e9fa03d5
[ "super(QNetworkConcat, self).__init__()\nself.take_additional_forward_arguments = True\nself.sequence_length = sequence_length\nself.repeat_size = repeat_size\nmx.random.seed(seed)\nself.net = gluon.nn.HybridSequential()\nwith self.net.name_scope():\n for i in range(number_of_conv_layers):\n self.net.add(...
<|body_start_0|> super(QNetworkConcat, self).__init__() self.take_additional_forward_arguments = True self.sequence_length = sequence_length self.repeat_size = repeat_size mx.random.seed(seed) self.net = gluon.nn.HybridSequential() with self.net.name_scope(): ...
QNetworkConcat
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class QNetworkConcat: def __init__(self, state_shape, action_size, starting_channels, number_of_conv_layers, number_of_dense_layers, number_of_hidden_states, kernel_size, repeat_size, activation_type, sequence_length, seed): """Initialize parameters and build model. Params ====== state_shape (...
stack_v2_sparse_classes_36k_train_007222
14,417
permissive
[ { "docstring": "Initialize parameters and build model. Params ====== state_shape (int, int, int): Dimension of each state action_size (int): Dimension of each action starting_channels (int): number_of_conv_layers (int) number_of_dense_layers (int) number_of_hidden_states (int) repeat_size (int) activation_type ...
2
stack_v2_sparse_classes_30k_train_019676
Implement the Python class `QNetworkConcat` described below. Class description: Implement the QNetworkConcat class. Method signatures and docstrings: - def __init__(self, state_shape, action_size, starting_channels, number_of_conv_layers, number_of_dense_layers, number_of_hidden_states, kernel_size, repeat_size, acti...
Implement the Python class `QNetworkConcat` described below. Class description: Implement the QNetworkConcat class. Method signatures and docstrings: - def __init__(self, state_shape, action_size, starting_channels, number_of_conv_layers, number_of_dense_layers, number_of_hidden_states, kernel_size, repeat_size, acti...
5baa886c17fa2cf53dd0146493281de717771d81
<|skeleton|> class QNetworkConcat: def __init__(self, state_shape, action_size, starting_channels, number_of_conv_layers, number_of_dense_layers, number_of_hidden_states, kernel_size, repeat_size, activation_type, sequence_length, seed): """Initialize parameters and build model. Params ====== state_shape (...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class QNetworkConcat: def __init__(self, state_shape, action_size, starting_channels, number_of_conv_layers, number_of_dense_layers, number_of_hidden_states, kernel_size, repeat_size, activation_type, sequence_length, seed): """Initialize parameters and build model. Params ====== state_shape (int, int, int)...
the_stack_v2_python_sparse
source/MXNetEnv/training/training_src/networks/qnetworks.py
awslabs/sagemaker-battlesnake-ai
train
91
dd38600399b8106b57463ac7eae946f51ec4a6ef
[ "self.k = k\nself.X = None\nself.labels = None\nself.cluster_centers = None", "ran_index = np.random.choice(np.arange(0, len(X)), self.k)\ncentres = [X[i] for i in ran_index]\nprev_labels = np.zeros(len(X))\ni = 0\nwhile True:\n labels = []\n for x in X:\n labels.append(np.argmin([np.linalg.norm(x - ...
<|body_start_0|> self.k = k self.X = None self.labels = None self.cluster_centers = None <|end_body_0|> <|body_start_1|> ran_index = np.random.choice(np.arange(0, len(X)), self.k) centres = [X[i] for i in ran_index] prev_labels = np.zeros(len(X)) i = 0 ...
MyKMeans
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MyKMeans: def __init__(self, k=3): """K-means clustering model :k: int, number of clusters""" <|body_0|> def fit(self, X): """Train the K-means clustering model Parameters ---------- X: ndarray of shape (m, n) sample data where row represent sample and column represe...
stack_v2_sparse_classes_36k_train_007223
3,479
no_license
[ { "docstring": "K-means clustering model :k: int, number of clusters", "name": "__init__", "signature": "def __init__(self, k=3)" }, { "docstring": "Train the K-means clustering model Parameters ---------- X: ndarray of shape (m, n) sample data where row represent sample and column represent fea...
3
stack_v2_sparse_classes_30k_train_013777
Implement the Python class `MyKMeans` described below. Class description: Implement the MyKMeans class. Method signatures and docstrings: - def __init__(self, k=3): K-means clustering model :k: int, number of clusters - def fit(self, X): Train the K-means clustering model Parameters ---------- X: ndarray of shape (m,...
Implement the Python class `MyKMeans` described below. Class description: Implement the MyKMeans class. Method signatures and docstrings: - def __init__(self, k=3): K-means clustering model :k: int, number of clusters - def fit(self, X): Train the K-means clustering model Parameters ---------- X: ndarray of shape (m,...
8ec0b7780af84cc196939227fddfde07033ef10d
<|skeleton|> class MyKMeans: def __init__(self, k=3): """K-means clustering model :k: int, number of clusters""" <|body_0|> def fit(self, X): """Train the K-means clustering model Parameters ---------- X: ndarray of shape (m, n) sample data where row represent sample and column represe...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MyKMeans: def __init__(self, k=3): """K-means clustering model :k: int, number of clusters""" self.k = k self.X = None self.labels = None self.cluster_centers = None def fit(self, X): """Train the K-means clustering model Parameters ---------- X: ndarray of...
the_stack_v2_python_sparse
machine-learning/unsupervised.py
qige96/programming-practice
train
1
a0e1aad5f216f37fb593a0ccfd86e3f96c545624
[ "st = set(wordList)\nif endWord not in st:\n return 0\nm = len(beginWord)\nvisited = set()\nqueue = collections.deque()\nvisited.add(beginWord)\nqueue.append((beginWord, 1))\nwhile queue:\n cur, step = queue.popleft()\n if cur == endWord:\n return step\n new_list = list(cur)\n for i in range(m...
<|body_start_0|> st = set(wordList) if endWord not in st: return 0 m = len(beginWord) visited = set() queue = collections.deque() visited.add(beginWord) queue.append((beginWord, 1)) while queue: cur, step = queue.popleft() ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def ladderLength1(self, beginWord: str, endWord: str, wordList: List[str]) -> int: """思路:单向BFS @param beginWord: @param endWord: @param wordList: @return:""" <|body_0|> def ladderLength2(self, beginWord: str, endWord: str, wordList: List[str]) -> int: """思路...
stack_v2_sparse_classes_36k_train_007224
3,686
no_license
[ { "docstring": "思路:单向BFS @param beginWord: @param endWord: @param wordList: @return:", "name": "ladderLength1", "signature": "def ladderLength1(self, beginWord: str, endWord: str, wordList: List[str]) -> int" }, { "docstring": "思路:双向BFS @param beginWord: @param endWord: @param wordList: @return:...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def ladderLength1(self, beginWord: str, endWord: str, wordList: List[str]) -> int: 思路:单向BFS @param beginWord: @param endWord: @param wordList: @return: - def ladderLength2(self, ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def ladderLength1(self, beginWord: str, endWord: str, wordList: List[str]) -> int: 思路:单向BFS @param beginWord: @param endWord: @param wordList: @return: - def ladderLength2(self, ...
e43ee86c5a8cdb808da09b4b6138e10275abadb5
<|skeleton|> class Solution: def ladderLength1(self, beginWord: str, endWord: str, wordList: List[str]) -> int: """思路:单向BFS @param beginWord: @param endWord: @param wordList: @return:""" <|body_0|> def ladderLength2(self, beginWord: str, endWord: str, wordList: List[str]) -> int: """思路...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def ladderLength1(self, beginWord: str, endWord: str, wordList: List[str]) -> int: """思路:单向BFS @param beginWord: @param endWord: @param wordList: @return:""" st = set(wordList) if endWord not in st: return 0 m = len(beginWord) visited = set() ...
the_stack_v2_python_sparse
LeetCode/广度优先搜索(BFS)/127. 单词接龙.py
yiming1012/MyLeetCode
train
2
66e82b10565295776b2d233ffe48370631c5fd94
[ "if not node:\n return None\nroot = UndirectedGraphNode(node.label)\nd_old_copy = {node: root}\ncur_layer = [node]\nself.bfs(cur_layer, d_old_copy)\nreturn root", "while cur_layer:\n node = cur_layer.pop()\n for nb in node.neighbors:\n if nb not in d_old_copy:\n d_old_copy[nb] = Undirec...
<|body_start_0|> if not node: return None root = UndirectedGraphNode(node.label) d_old_copy = {node: root} cur_layer = [node] self.bfs(cur_layer, d_old_copy) return root <|end_body_0|> <|body_start_1|> while cur_layer: node = cur_layer.pop...
Solution description
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: """Solution description""" def cloneGraph(self, node): """Solution function description""" <|body_0|> def bfs(self, cur_layer, d_old_copy): """breadth first""" <|body_1|> def dfs(self, node, d_old_copy): """depth first""" <|...
stack_v2_sparse_classes_36k_train_007225
1,512
permissive
[ { "docstring": "Solution function description", "name": "cloneGraph", "signature": "def cloneGraph(self, node)" }, { "docstring": "breadth first", "name": "bfs", "signature": "def bfs(self, cur_layer, d_old_copy)" }, { "docstring": "depth first", "name": "dfs", "signature...
3
stack_v2_sparse_classes_30k_train_015736
Implement the Python class `Solution` described below. Class description: Solution description Method signatures and docstrings: - def cloneGraph(self, node): Solution function description - def bfs(self, cur_layer, d_old_copy): breadth first - def dfs(self, node, d_old_copy): depth first
Implement the Python class `Solution` described below. Class description: Solution description Method signatures and docstrings: - def cloneGraph(self, node): Solution function description - def bfs(self, cur_layer, d_old_copy): breadth first - def dfs(self, node, d_old_copy): depth first <|skeleton|> class Solution...
869ee24c50c08403b170e8f7868699185e9dfdd1
<|skeleton|> class Solution: """Solution description""" def cloneGraph(self, node): """Solution function description""" <|body_0|> def bfs(self, cur_layer, d_old_copy): """breadth first""" <|body_1|> def dfs(self, node, d_old_copy): """depth first""" <|...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: """Solution description""" def cloneGraph(self, node): """Solution function description""" if not node: return None root = UndirectedGraphNode(node.label) d_old_copy = {node: root} cur_layer = [node] self.bfs(cur_layer, d_old_copy) ...
the_stack_v2_python_sparse
133.clone.graph/1.py
cerebrumaize/leetcode
train
0
3f773d82bf47dac9ab99bae68035a060837accc1
[ "changes = 0\ntable_differences = TableDiff(table1.get_name())\ntable_differences.from_table = table1\ntable1_columns = table1.get_columns()\ntable2_columns = table2.get_columns()\nfor column_name, column in table2_columns.items():\n if not table1.has_column(column_name):\n table_differences.added_columns...
<|body_start_0|> changes = 0 table_differences = TableDiff(table1.get_name()) table_differences.from_table = table1 table1_columns = table1.get_columns() table2_columns = table2.get_columns() for column_name, column in table2_columns.items(): if not table1.has...
Compares two Schemas and return an instance of SchemaDiff.
Comparator
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Comparator: """Compares two Schemas and return an instance of SchemaDiff.""" def diff_table(self, table1, table2): """Returns the difference between the tables table1 and table2. :type table1: Table :type table2: Table :rtype: TableDiff""" <|body_0|> def detect_column_re...
stack_v2_sparse_classes_36k_train_007226
7,301
permissive
[ { "docstring": "Returns the difference between the tables table1 and table2. :type table1: Table :type table2: Table :rtype: TableDiff", "name": "diff_table", "signature": "def diff_table(self, table1, table2)" }, { "docstring": "Try to find columns that only changed their names. :type table_dif...
3
null
Implement the Python class `Comparator` described below. Class description: Compares two Schemas and return an instance of SchemaDiff. Method signatures and docstrings: - def diff_table(self, table1, table2): Returns the difference between the tables table1 and table2. :type table1: Table :type table2: Table :rtype: ...
Implement the Python class `Comparator` described below. Class description: Compares two Schemas and return an instance of SchemaDiff. Method signatures and docstrings: - def diff_table(self, table1, table2): Returns the difference between the tables table1 and table2. :type table1: Table :type table2: Table :rtype: ...
fa4c428c063f1828b8035a76115752ea0c7c2bb0
<|skeleton|> class Comparator: """Compares two Schemas and return an instance of SchemaDiff.""" def diff_table(self, table1, table2): """Returns the difference between the tables table1 and table2. :type table1: Table :type table2: Table :rtype: TableDiff""" <|body_0|> def detect_column_re...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Comparator: """Compares two Schemas and return an instance of SchemaDiff.""" def diff_table(self, table1, table2): """Returns the difference between the tables table1 and table2. :type table1: Table :type table2: Table :rtype: TableDiff""" changes = 0 table_differences = TableDiff...
the_stack_v2_python_sparse
orator/dbal/comparator.py
MakarenaLabs/Orator-Google-App-Engine
train
2
34758b74c20c1808fa799542d45298d54c82e1f4
[ "startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('chuci_yfch_yuwan_zhurh', 'chuci_yfch_yuwan_zhurh')\n\ndef select(R, s):\n return [t for t in R if s(t)]\n\ndef product(R, S):\n return [(t, u) for t in R for u in S]\n\ndef project(R, p):\n retu...
<|body_start_0|> startTime = datetime.datetime.now() client = dml.pymongo.MongoClient() repo = client.repo repo.authenticate('chuci_yfch_yuwan_zhurh', 'chuci_yfch_yuwan_zhurh') def select(R, s): return [t for t in R if s(t)] def product(R, S): re...
unemploy_gov_sparkgov__output
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class unemploy_gov_sparkgov__output: def execute(trial=False): """Retrieve some data sets (not using the API here for the sake of simplicity).""" <|body_0|> def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): """Create the provenance document descr...
stack_v2_sparse_classes_36k_train_007227
5,978
no_license
[ { "docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).", "name": "execute", "signature": "def execute(trial=False)" }, { "docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d...
2
stack_v2_sparse_classes_30k_train_019078
Implement the Python class `unemploy_gov_sparkgov__output` described below. Class description: Implement the unemploy_gov_sparkgov__output class. Method signatures and docstrings: - def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity). - def provenance(doc=prov.model.P...
Implement the Python class `unemploy_gov_sparkgov__output` described below. Class description: Implement the unemploy_gov_sparkgov__output class. Method signatures and docstrings: - def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity). - def provenance(doc=prov.model.P...
90284cf3debbac36eead07b8d2339cdd191b86cf
<|skeleton|> class unemploy_gov_sparkgov__output: def execute(trial=False): """Retrieve some data sets (not using the API here for the sake of simplicity).""" <|body_0|> def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): """Create the provenance document descr...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class unemploy_gov_sparkgov__output: def execute(trial=False): """Retrieve some data sets (not using the API here for the sake of simplicity).""" startTime = datetime.datetime.now() client = dml.pymongo.MongoClient() repo = client.repo repo.authenticate('chuci_yfch_yuwan_zhur...
the_stack_v2_python_sparse
chuci_yfch_yuwan_zhurh/unemploy_gov_sparkgov__output.py
maximega/course-2019-spr-proj
train
2
30fccf698a03705ae1754884cb07ff212b9b89a2
[ "super(FactorizationMachineModel, self).__init__()\nself.fm = FMLayer(dropout_p)\nself.bias = nn.Parameter(torch.zeros((1, 1)))\nnn.init.uniform_(self.bias.data)", "fm_first = feat_inputs.sum(dim='N').rename(E='O')\nfm_second = self.fm(emb_inputs).sum(dim='O', keepdim=True)\noutputs = fm_second + fm_first + self....
<|body_start_0|> super(FactorizationMachineModel, self).__init__() self.fm = FMLayer(dropout_p) self.bias = nn.Parameter(torch.zeros((1, 1))) nn.init.uniform_(self.bias.data) <|end_body_0|> <|body_start_1|> fm_first = feat_inputs.sum(dim='N').rename(E='O') fm_second = se...
Model class of Factorization Machine (FM). Factoization Machine is a model to calculate interactions between fields in the following way: :math:`\\^{y}(x) := b_{0} + \\sum_{i=1}^{n} w_{i} x_{i} + \\sum_{i=1}^{n} \\sum_{j=1+1}^{n} <v_{i},v_{j}> x_{i} x_{j}` :Reference: #. `Steffen Rendle, 2010. Factorization Machine <ht...
FactorizationMachineModel
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FactorizationMachineModel: """Model class of Factorization Machine (FM). Factoization Machine is a model to calculate interactions between fields in the following way: :math:`\\^{y}(x) := b_{0} + \\sum_{i=1}^{n} w_{i} x_{i} + \\sum_{i=1}^{n} \\sum_{j=1+1}^{n} <v_{i},v_{j}> x_{i} x_{j}` :Reference...
stack_v2_sparse_classes_36k_train_007228
2,805
permissive
[ { "docstring": "Initialize FactorizationMachineModel Args: embed_size (int): Size of embedding tensor num_fields (int): Number of inputs' fields dropout_p (float, optional): Probability of Dropout in FM. Defaults to 0.0. Attributions: fm (nn.Module): Module of factorization machine layer. bias (nn.Parameter): P...
2
stack_v2_sparse_classes_30k_val_000143
Implement the Python class `FactorizationMachineModel` described below. Class description: Model class of Factorization Machine (FM). Factoization Machine is a model to calculate interactions between fields in the following way: :math:`\\^{y}(x) := b_{0} + \\sum_{i=1}^{n} w_{i} x_{i} + \\sum_{i=1}^{n} \\sum_{j=1+1}^{n...
Implement the Python class `FactorizationMachineModel` described below. Class description: Model class of Factorization Machine (FM). Factoization Machine is a model to calculate interactions between fields in the following way: :math:`\\^{y}(x) := b_{0} + \\sum_{i=1}^{n} w_{i} x_{i} + \\sum_{i=1}^{n} \\sum_{j=1+1}^{n...
07a6a38c7eb44225f2b22f332081f697c3b92894
<|skeleton|> class FactorizationMachineModel: """Model class of Factorization Machine (FM). Factoization Machine is a model to calculate interactions between fields in the following way: :math:`\\^{y}(x) := b_{0} + \\sum_{i=1}^{n} w_{i} x_{i} + \\sum_{i=1}^{n} \\sum_{j=1+1}^{n} <v_{i},v_{j}> x_{i} x_{j}` :Reference...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FactorizationMachineModel: """Model class of Factorization Machine (FM). Factoization Machine is a model to calculate interactions between fields in the following way: :math:`\\^{y}(x) := b_{0} + \\sum_{i=1}^{n} w_{i} x_{i} + \\sum_{i=1}^{n} \\sum_{j=1+1}^{n} <v_{i},v_{j}> x_{i} x_{j}` :Reference: #. `Steffen...
the_stack_v2_python_sparse
torecsys/models/ctr/factorization_machine.py
zwcdp/torecsys
train
0
7d9bf2116c10a31a231cb84a3090654679ba8a43
[ "res = list(s)\nfor i in range(len(s)):\n if res[i] == ' ':\n res[i] = '%20'\nres = ''.join(res)\nreturn res", "res = []\nfor c in s:\n if c == ' ':\n res.append('%20')\n else:\n res.append(c)\nreturn ''.join(res)" ]
<|body_start_0|> res = list(s) for i in range(len(s)): if res[i] == ' ': res[i] = '%20' res = ''.join(res) return res <|end_body_0|> <|body_start_1|> res = [] for c in s: if c == ' ': res.append('%20') e...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def replaceSpace(self, s: str) -> str: """不是最佳答案 将字符串转换为list,然后对list中各个元素遍历,若为空格,则替换,最后将list进行拼接为字符串""" <|body_0|> def replaceSpace(self, s: str) -> str: """最佳答案 创建新的列表,遍历字符串中的每个字符,判断是否为空格进行对应的append,最后在join到一起形成字符串""" <|body_1|> <|end_skeleton|> ...
stack_v2_sparse_classes_36k_train_007229
869
no_license
[ { "docstring": "不是最佳答案 将字符串转换为list,然后对list中各个元素遍历,若为空格,则替换,最后将list进行拼接为字符串", "name": "replaceSpace", "signature": "def replaceSpace(self, s: str) -> str" }, { "docstring": "最佳答案 创建新的列表,遍历字符串中的每个字符,判断是否为空格进行对应的append,最后在join到一起形成字符串", "name": "replaceSpace", "signature": "def replaceSpace...
2
stack_v2_sparse_classes_30k_train_001201
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def replaceSpace(self, s: str) -> str: 不是最佳答案 将字符串转换为list,然后对list中各个元素遍历,若为空格,则替换,最后将list进行拼接为字符串 - def replaceSpace(self, s: str) -> str: 最佳答案 创建新的列表,遍历字符串中的每个字符,判断是否为空格进行对应的app...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def replaceSpace(self, s: str) -> str: 不是最佳答案 将字符串转换为list,然后对list中各个元素遍历,若为空格,则替换,最后将list进行拼接为字符串 - def replaceSpace(self, s: str) -> str: 最佳答案 创建新的列表,遍历字符串中的每个字符,判断是否为空格进行对应的app...
0ec1a89e5b1e3d32af4da9693e9e5c36d4cd42eb
<|skeleton|> class Solution: def replaceSpace(self, s: str) -> str: """不是最佳答案 将字符串转换为list,然后对list中各个元素遍历,若为空格,则替换,最后将list进行拼接为字符串""" <|body_0|> def replaceSpace(self, s: str) -> str: """最佳答案 创建新的列表,遍历字符串中的每个字符,判断是否为空格进行对应的append,最后在join到一起形成字符串""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def replaceSpace(self, s: str) -> str: """不是最佳答案 将字符串转换为list,然后对list中各个元素遍历,若为空格,则替换,最后将list进行拼接为字符串""" res = list(s) for i in range(len(s)): if res[i] == ' ': res[i] = '%20' res = ''.join(res) return res def replaceSpace(self,...
the_stack_v2_python_sparse
5.py
zhiweiguo/my_leetcode
train
1
bb4ed7ecc38c0ddad08851cd79753922faff89e4
[ "assert input.size(0) == target.size(0)\nN = input.size(0)\ntmp1 = input.exp().sum(axis=1)\ntmp2 = input[:, target].diag().exp()\nloss = -1 / N * (tmp2 / tmp1).log().sum()\nreturn loss", "assert input.size(0) == target.size(0)\nN = input.size(0)\nexp = input.exp()\nsum = exp.sum(axis=1)\ngrad = 1 / N * (exp.T / s...
<|body_start_0|> assert input.size(0) == target.size(0) N = input.size(0) tmp1 = input.exp().sum(axis=1) tmp2 = input[:, target].diag().exp() loss = -1 / N * (tmp2 / tmp1).log().sum() return loss <|end_body_0|> <|body_start_1|> assert input.size(0) == target.size...
Class representing the cross entropy loss.
LossCrossEntropy
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LossCrossEntropy: """Class representing the cross entropy loss.""" def forward(self, input, target): """Computes the cross entropy loss given the input tensor and the target tensor. Args: input -- tensor of size (N, D) target -- tensor of size (N, 1) Returns: loss -- cross entropy lo...
stack_v2_sparse_classes_36k_train_007230
2,642
permissive
[ { "docstring": "Computes the cross entropy loss given the input tensor and the target tensor. Args: input -- tensor of size (N, D) target -- tensor of size (N, 1) Returns: loss -- cross entropy loss between input and target", "name": "forward", "signature": "def forward(self, input, target)" }, { ...
2
stack_v2_sparse_classes_30k_train_020306
Implement the Python class `LossCrossEntropy` described below. Class description: Class representing the cross entropy loss. Method signatures and docstrings: - def forward(self, input, target): Computes the cross entropy loss given the input tensor and the target tensor. Args: input -- tensor of size (N, D) target -...
Implement the Python class `LossCrossEntropy` described below. Class description: Class representing the cross entropy loss. Method signatures and docstrings: - def forward(self, input, target): Computes the cross entropy loss given the input tensor and the target tensor. Args: input -- tensor of size (N, D) target -...
056b1be878b77c5a7dd5cff8d29ecb390be8b5de
<|skeleton|> class LossCrossEntropy: """Class representing the cross entropy loss.""" def forward(self, input, target): """Computes the cross entropy loss given the input tensor and the target tensor. Args: input -- tensor of size (N, D) target -- tensor of size (N, 1) Returns: loss -- cross entropy lo...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LossCrossEntropy: """Class representing the cross entropy loss.""" def forward(self, input, target): """Computes the cross entropy loss given the input tensor and the target tensor. Args: input -- tensor of size (N, D) target -- tensor of size (N, 1) Returns: loss -- cross entropy loss between in...
the_stack_v2_python_sparse
Proj2/modules/Losses.py
jouvemax/DeepLearning
train
0
76275827782ca3fb5408a39692d688d09b89efc1
[ "super().__init__(parse)\nself.table_name = parse['table_name']\nself.columns = parse['columns']\nself.index_name = parse['index_name']\ntry:\n self.index_type = parse['index_type']\nexcept KeyError:\n self.index_type = 'BTREE'\ntry:\n self.is_unique = bool(parse['unique'])\nexcept KeyError:\n self.is_u...
<|body_start_0|> super().__init__(parse) self.table_name = parse['table_name'] self.columns = parse['columns'] self.index_name = parse['index_name'] try: self.index_type = parse['index_type'] except KeyError: self.index_type = 'BTREE' try: ...
" CREATE INDEX ...
SQLExecIndexDefinition
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SQLExecIndexDefinition: """" CREATE INDEX ...""" def __init__(self, parse): """Create an index with given table_name (string) and columns (from parse tree).""" <|body_0|> def execute(self): """Execute the statement.""" <|body_1|> <|end_skeleton|> <|body...
stack_v2_sparse_classes_36k_train_007231
14,323
no_license
[ { "docstring": "Create an index with given table_name (string) and columns (from parse tree).", "name": "__init__", "signature": "def __init__(self, parse)" }, { "docstring": "Execute the statement.", "name": "execute", "signature": "def execute(self)" } ]
2
stack_v2_sparse_classes_30k_train_017937
Implement the Python class `SQLExecIndexDefinition` described below. Class description: " CREATE INDEX ... Method signatures and docstrings: - def __init__(self, parse): Create an index with given table_name (string) and columns (from parse tree). - def execute(self): Execute the statement.
Implement the Python class `SQLExecIndexDefinition` described below. Class description: " CREATE INDEX ... Method signatures and docstrings: - def __init__(self, parse): Create an index with given table_name (string) and columns (from parse tree). - def execute(self): Execute the statement. <|skeleton|> class SQLExe...
088210db213ad380bce115d2c40a948b7edf38fa
<|skeleton|> class SQLExecIndexDefinition: """" CREATE INDEX ...""" def __init__(self, parse): """Create an index with given table_name (string) and columns (from parse tree).""" <|body_0|> def execute(self): """Execute the statement.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SQLExecIndexDefinition: """" CREATE INDEX ...""" def __init__(self, parse): """Create an index with given table_name (string) and columns (from parse tree).""" super().__init__(parse) self.table_name = parse['table_name'] self.columns = parse['columns'] self.index_...
the_stack_v2_python_sparse
sqlexec.py
gradyDiakubama/cpsc5300py
train
0
0da3bdf964ace4cae40287a4ae3271996a53f819
[ "self.drive_owner_vec = drive_owner_vec\nself.restore_to_original = restore_to_original\nself.target_drive_id = target_drive_id\nself.target_folder_path = target_folder_path\nself.target_user = target_user", "if dictionary is None:\n return None\ndrive_owner_vec = None\nif dictionary.get('driveOwnerVec') != No...
<|body_start_0|> self.drive_owner_vec = drive_owner_vec self.restore_to_original = restore_to_original self.target_drive_id = target_drive_id self.target_folder_path = target_folder_path self.target_user = target_user <|end_body_0|> <|body_start_1|> if dictionary is None...
Implementation of the 'RestoreOneDriveParams' model. TODO: type description here. Attributes: drive_owner_vec (list of RestoreOneDriveParams_DriveOwner): The list of users/groups whose drives are being restored. restore_to_original (bool): Whether or not all drive items are restored to original location. target_drive_i...
RestoreOneDriveParams
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RestoreOneDriveParams: """Implementation of the 'RestoreOneDriveParams' model. TODO: type description here. Attributes: drive_owner_vec (list of RestoreOneDriveParams_DriveOwner): The list of users/groups whose drives are being restored. restore_to_original (bool): Whether or not all drive items ...
stack_v2_sparse_classes_36k_train_007232
3,814
permissive
[ { "docstring": "Constructor for the RestoreOneDriveParams class", "name": "__init__", "signature": "def __init__(self, drive_owner_vec=None, restore_to_original=None, target_drive_id=None, target_folder_path=None, target_user=None)" }, { "docstring": "Creates an instance of this model from a dic...
2
null
Implement the Python class `RestoreOneDriveParams` described below. Class description: Implementation of the 'RestoreOneDriveParams' model. TODO: type description here. Attributes: drive_owner_vec (list of RestoreOneDriveParams_DriveOwner): The list of users/groups whose drives are being restored. restore_to_original ...
Implement the Python class `RestoreOneDriveParams` described below. Class description: Implementation of the 'RestoreOneDriveParams' model. TODO: type description here. Attributes: drive_owner_vec (list of RestoreOneDriveParams_DriveOwner): The list of users/groups whose drives are being restored. restore_to_original ...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class RestoreOneDriveParams: """Implementation of the 'RestoreOneDriveParams' model. TODO: type description here. Attributes: drive_owner_vec (list of RestoreOneDriveParams_DriveOwner): The list of users/groups whose drives are being restored. restore_to_original (bool): Whether or not all drive items ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RestoreOneDriveParams: """Implementation of the 'RestoreOneDriveParams' model. TODO: type description here. Attributes: drive_owner_vec (list of RestoreOneDriveParams_DriveOwner): The list of users/groups whose drives are being restored. restore_to_original (bool): Whether or not all drive items are restored ...
the_stack_v2_python_sparse
cohesity_management_sdk/models/restore_one_drive_params.py
cohesity/management-sdk-python
train
24
c360dac1acdd63fd48f7468ea07e094b8f01bdb5
[ "self.obj_ids = []\nself.threshold = threshold\nself.client = None", "self.obj_ids.append(pointer.id_at_location)\nnr_objs_client = len(self.obj_ids)\nif nr_objs_client >= self.threshold:\n msg = GarbageCollectBatchedAction(ids_at_location=self.obj_ids, address=pointer.client.address)\n pointer.client.send_...
<|body_start_0|> self.obj_ids = [] self.threshold = threshold self.client = None <|end_body_0|> <|body_start_1|> self.obj_ids.append(pointer.id_at_location) nr_objs_client = len(self.obj_ids) if nr_objs_client >= self.threshold: msg = GarbageCollectBatchedAct...
The GCBatched Strategy.
GCBatched
[ "Python-2.0", "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GCBatched: """The GCBatched Strategy.""" def __init__(self, threshold: int=10) -> None: """Construct the GCBatched Strategy. Args: threshold (int): the threshold after which a message would be sent to delete all the objects that were cached Return: None""" <|body_0|> def...
stack_v2_sparse_classes_36k_train_007233
2,439
permissive
[ { "docstring": "Construct the GCBatched Strategy. Args: threshold (int): the threshold after which a message would be sent to delete all the objects that were cached Return: None", "name": "__init__", "signature": "def __init__(self, threshold: int=10) -> None" }, { "docstring": "Check if we pas...
3
stack_v2_sparse_classes_30k_train_004101
Implement the Python class `GCBatched` described below. Class description: The GCBatched Strategy. Method signatures and docstrings: - def __init__(self, threshold: int=10) -> None: Construct the GCBatched Strategy. Args: threshold (int): the threshold after which a message would be sent to delete all the objects tha...
Implement the Python class `GCBatched` described below. Class description: The GCBatched Strategy. Method signatures and docstrings: - def __init__(self, threshold: int=10) -> None: Construct the GCBatched Strategy. Args: threshold (int): the threshold after which a message would be sent to delete all the objects tha...
6477f64b63dc285059c3766deab3993653cead2e
<|skeleton|> class GCBatched: """The GCBatched Strategy.""" def __init__(self, threshold: int=10) -> None: """Construct the GCBatched Strategy. Args: threshold (int): the threshold after which a message would be sent to delete all the objects that were cached Return: None""" <|body_0|> def...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GCBatched: """The GCBatched Strategy.""" def __init__(self, threshold: int=10) -> None: """Construct the GCBatched Strategy. Args: threshold (int): the threshold after which a message would be sent to delete all the objects that were cached Return: None""" self.obj_ids = [] self.t...
the_stack_v2_python_sparse
packages/syft/src/syft/core/pointer/garbage_collection/gc_batched.py
Metrix1010/PySyft
train
2
8dc18a314224c615306e6e0f8b3b93d9062d961f
[ "client = LdapClient({'ldap_server_vendor': 'OpenLDAP', 'host': 'server_ip', 'connection_type': 'SSL', 'user_identifier_attribute': user_identifier_attribute})\nactual_result, dn = client._is_valid_dn(dn, client.USER_IDENTIFIER_ATTRIBUTE)\nassert (actual_result, dn) == expected_result", "client = LdapClient({'lda...
<|body_start_0|> client = LdapClient({'ldap_server_vendor': 'OpenLDAP', 'host': 'server_ip', 'connection_type': 'SSL', 'user_identifier_attribute': user_identifier_attribute}) actual_result, dn = client._is_valid_dn(dn, client.USER_IDENTIFIER_ATTRIBUTE) assert (actual_result, dn) == expected_res...
Contains unit tests for functions that deal with OpenLDAP server only.
TestsOpenLDAP
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestsOpenLDAP: """Contains unit tests for functions that deal with OpenLDAP server only.""" def test_is_valid_dn(self, dn, user_identifier_attribute, expected_result): """Given: - A DN and a user identifier attribute: 1. A valid DN. 2. Invalid DN. When: - Running the '_is_valid_dn()'...
stack_v2_sparse_classes_36k_train_007234
12,670
permissive
[ { "docstring": "Given: - A DN and a user identifier attribute: 1. A valid DN. 2. Invalid DN. When: - Running the '_is_valid_dn()' function. Then: - Verify that the DN is parsed correctly and that the user returned as expected.", "name": "test_is_valid_dn", "signature": "def test_is_valid_dn(self, dn, us...
2
stack_v2_sparse_classes_30k_train_010493
Implement the Python class `TestsOpenLDAP` described below. Class description: Contains unit tests for functions that deal with OpenLDAP server only. Method signatures and docstrings: - def test_is_valid_dn(self, dn, user_identifier_attribute, expected_result): Given: - A DN and a user identifier attribute: 1. A vali...
Implement the Python class `TestsOpenLDAP` described below. Class description: Contains unit tests for functions that deal with OpenLDAP server only. Method signatures and docstrings: - def test_is_valid_dn(self, dn, user_identifier_attribute, expected_result): Given: - A DN and a user identifier attribute: 1. A vali...
890def5a0e0ae8d6eaa538148249ddbc851dbb6b
<|skeleton|> class TestsOpenLDAP: """Contains unit tests for functions that deal with OpenLDAP server only.""" def test_is_valid_dn(self, dn, user_identifier_attribute, expected_result): """Given: - A DN and a user identifier attribute: 1. A valid DN. 2. Invalid DN. When: - Running the '_is_valid_dn()'...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestsOpenLDAP: """Contains unit tests for functions that deal with OpenLDAP server only.""" def test_is_valid_dn(self, dn, user_identifier_attribute, expected_result): """Given: - A DN and a user identifier attribute: 1. A valid DN. 2. Invalid DN. When: - Running the '_is_valid_dn()' function. Th...
the_stack_v2_python_sparse
Packs/OpenLDAP/Integrations/OpenLDAP/OpenLDAP_test.py
demisto/content
train
1,023
89fecd54bc1f885c366fe4130658e60b7039fa96
[ "with self.assertRaises(EOFError) as e:\n fileio.GetAtomsFromXyzq([])\nself.assertEqual(str(e.exception), 'XYZQ file is empty.')", "with self.assertRaises(IndexError) as e:\n fileio.GetAtomsFromXyzq([[], ['X', '0.0', '0.0', '0.0', '0.0']])\nself.assertEqual(str(e.exception), 'First line of XYZQ file must be...
<|body_start_0|> with self.assertRaises(EOFError) as e: fileio.GetAtomsFromXyzq([]) self.assertEqual(str(e.exception), 'XYZQ file is empty.') <|end_body_0|> <|body_start_1|> with self.assertRaises(IndexError) as e: fileio.GetAtomsFromXyzq([[], ['X', '0.0', '0.0', '0.0', ...
Unit tests for mmlib.fileio.GetAtomsFromXyzq method.
TestGetAtomsFromXyzq
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestGetAtomsFromXyzq: """Unit tests for mmlib.fileio.GetAtomsFromXyzq method.""" def testEmptyArray(self): """Asserts error raise for empty input.""" <|body_0|> def testEmptyFirstRow(self): """Asserts error raise for empty first row of input.""" <|body_1|...
stack_v2_sparse_classes_36k_train_007235
20,144
no_license
[ { "docstring": "Asserts error raise for empty input.", "name": "testEmptyArray", "signature": "def testEmptyArray(self)" }, { "docstring": "Asserts error raise for empty first row of input.", "name": "testEmptyFirstRow", "signature": "def testEmptyFirstRow(self)" }, { "docstring"...
6
stack_v2_sparse_classes_30k_train_007339
Implement the Python class `TestGetAtomsFromXyzq` described below. Class description: Unit tests for mmlib.fileio.GetAtomsFromXyzq method. Method signatures and docstrings: - def testEmptyArray(self): Asserts error raise for empty input. - def testEmptyFirstRow(self): Asserts error raise for empty first row of input....
Implement the Python class `TestGetAtomsFromXyzq` described below. Class description: Unit tests for mmlib.fileio.GetAtomsFromXyzq method. Method signatures and docstrings: - def testEmptyArray(self): Asserts error raise for empty input. - def testEmptyFirstRow(self): Asserts error raise for empty first row of input....
0ac31aac3070bba17e91c9922a2e32c569479e4d
<|skeleton|> class TestGetAtomsFromXyzq: """Unit tests for mmlib.fileio.GetAtomsFromXyzq method.""" def testEmptyArray(self): """Asserts error raise for empty input.""" <|body_0|> def testEmptyFirstRow(self): """Asserts error raise for empty first row of input.""" <|body_1|...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestGetAtomsFromXyzq: """Unit tests for mmlib.fileio.GetAtomsFromXyzq method.""" def testEmptyArray(self): """Asserts error raise for empty input.""" with self.assertRaises(EOFError) as e: fileio.GetAtomsFromXyzq([]) self.assertEqual(str(e.exception), 'XYZQ file is emp...
the_stack_v2_python_sparse
scripts/molecular_mechanics/mmlib/fileio_test.py
aledzib/Computational-Chemistry
train
1
5de33d881a2d9e16ab686acc6ebc63b78969eaa9
[ "acl.enforce('code_sources:create', context.ctx())\ncontent = pecan.request.text\nLOG.debug('Creating code source [names=%s, scope=%s, namespace=%s]', name, scope, namespace)\ndb_model = rest_utils.rest_retry_on_db_error(db_api.create_code_source)({'name': name, 'content': content, 'namespace': namespace, 'scope': ...
<|body_start_0|> acl.enforce('code_sources:create', context.ctx()) content = pecan.request.text LOG.debug('Creating code source [names=%s, scope=%s, namespace=%s]', name, scope, namespace) db_model = rest_utils.rest_retry_on_db_error(db_api.create_code_source)({'name': name, 'content': c...
CodeSourcesController
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CodeSourcesController: def post(self, name, scope='private', namespace=''): """Creates new code sources. :param name: Code source name (i.e. the name of the module). :param scope: Optional. Scope (private or public). :param namespace: Optional. The namespace to create the code sources in...
stack_v2_sparse_classes_36k_train_007236
8,557
permissive
[ { "docstring": "Creates new code sources. :param name: Code source name (i.e. the name of the module). :param scope: Optional. Scope (private or public). :param namespace: Optional. The namespace to create the code sources in.", "name": "post", "signature": "def post(self, name, scope='private', namespa...
5
stack_v2_sparse_classes_30k_train_019163
Implement the Python class `CodeSourcesController` described below. Class description: Implement the CodeSourcesController class. Method signatures and docstrings: - def post(self, name, scope='private', namespace=''): Creates new code sources. :param name: Code source name (i.e. the name of the module). :param scope...
Implement the Python class `CodeSourcesController` described below. Class description: Implement the CodeSourcesController class. Method signatures and docstrings: - def post(self, name, scope='private', namespace=''): Creates new code sources. :param name: Code source name (i.e. the name of the module). :param scope...
7baff017d0cf01d19c44055ad201ca59131b9f94
<|skeleton|> class CodeSourcesController: def post(self, name, scope='private', namespace=''): """Creates new code sources. :param name: Code source name (i.e. the name of the module). :param scope: Optional. Scope (private or public). :param namespace: Optional. The namespace to create the code sources in...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CodeSourcesController: def post(self, name, scope='private', namespace=''): """Creates new code sources. :param name: Code source name (i.e. the name of the module). :param scope: Optional. Scope (private or public). :param namespace: Optional. The namespace to create the code sources in.""" a...
the_stack_v2_python_sparse
mistral/api/controllers/v2/code_source.py
openstack/mistral
train
214
bb4890fd003e06fbfcd042e9ea1dab6510140379
[ "def helper(x, y, queryed):\n if x == y:\n return 1.0\n queryed.add(x)\n for n in equationsMapper[x]:\n if n in queryed:\n continue\n queryed.add(n)\n tmpRet = helper(n, y, queryed)\n if tmpRet > 0:\n return tmpRet * equationsMapper[x][n]\n return...
<|body_start_0|> def helper(x, y, queryed): if x == y: return 1.0 queryed.add(x) for n in equationsMapper[x]: if n in queryed: continue queryed.add(n) tmpRet = helper(n, y, queryed) ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def calcEquation(self, equations, values, queries): """:type equations: List[List[str]] :type values: List[float] :type queries: List[List[str]] :rtype: List[float]""" <|body_0|> def mapperFit(self, equations, values): """完成字典转换""" <|body_1|> d...
stack_v2_sparse_classes_36k_train_007237
3,313
no_license
[ { "docstring": ":type equations: List[List[str]] :type values: List[float] :type queries: List[List[str]] :rtype: List[float]", "name": "calcEquation", "signature": "def calcEquation(self, equations, values, queries)" }, { "docstring": "完成字典转换", "name": "mapperFit", "signature": "def map...
3
stack_v2_sparse_classes_30k_val_000269
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def calcEquation(self, equations, values, queries): :type equations: List[List[str]] :type values: List[float] :type queries: List[List[str]] :rtype: List[float] - def mapperFit(...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def calcEquation(self, equations, values, queries): :type equations: List[List[str]] :type values: List[float] :type queries: List[List[str]] :rtype: List[float] - def mapperFit(...
37056acad7a05b876832f72ac34d3d1a41e0dd22
<|skeleton|> class Solution: def calcEquation(self, equations, values, queries): """:type equations: List[List[str]] :type values: List[float] :type queries: List[List[str]] :rtype: List[float]""" <|body_0|> def mapperFit(self, equations, values): """完成字典转换""" <|body_1|> d...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def calcEquation(self, equations, values, queries): """:type equations: List[List[str]] :type values: List[float] :type queries: List[List[str]] :rtype: List[float]""" def helper(x, y, queryed): if x == y: return 1.0 queryed.add(x) ...
the_stack_v2_python_sparse
AlgorithmsPractice/python/399_medium_ Evaluate Division.py
Hubert-up/Lookoop
train
0
36ebfbd99598734f82e688a20403ec0c57c577b6
[ "self.generic_visit(node)\nif isinstance(node.ctx, ast.Load):\n args = [node.value, ast.Str(node.attr)]\n return to_call(to_name('getattr'), args)\nreturn node", "self.generic_visit(node)\ntarget = get_single_target(node)\nif isinstance(target, ast.Attribute):\n args = [target.value, ast.Str(target.attr)...
<|body_start_0|> self.generic_visit(node) if isinstance(node.ctx, ast.Load): args = [node.value, ast.Str(node.attr)] return to_call(to_name('getattr'), args) return node <|end_body_0|> <|body_start_1|> self.generic_visit(node) target = get_single_target(n...
Replace attribute getters/setters with function calls. Namely, the functions `getattr`, `setattr`, and `delattr`.
AttributesToFunctions
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AttributesToFunctions: """Replace attribute getters/setters with function calls. Namely, the functions `getattr`, `setattr`, and `delattr`.""" def visit_Attribute(self, node): """Convert attribute access to `getattr` call.""" <|body_0|> def visit_Assign(self, node): ...
stack_v2_sparse_classes_36k_train_007238
15,969
permissive
[ { "docstring": "Convert attribute access to `getattr` call.", "name": "visit_Attribute", "signature": "def visit_Attribute(self, node)" }, { "docstring": "Convert assignment to attributes to `setattr` call.", "name": "visit_Assign", "signature": "def visit_Assign(self, node)" }, { ...
3
stack_v2_sparse_classes_30k_train_006539
Implement the Python class `AttributesToFunctions` described below. Class description: Replace attribute getters/setters with function calls. Namely, the functions `getattr`, `setattr`, and `delattr`. Method signatures and docstrings: - def visit_Attribute(self, node): Convert attribute access to `getattr` call. - de...
Implement the Python class `AttributesToFunctions` described below. Class description: Replace attribute getters/setters with function calls. Namely, the functions `getattr`, `setattr`, and `delattr`. Method signatures and docstrings: - def visit_Attribute(self, node): Convert attribute access to `getattr` call. - de...
a6097d36c8863925c774f04155e2af6cc8cb3859
<|skeleton|> class AttributesToFunctions: """Replace attribute getters/setters with function calls. Namely, the functions `getattr`, `setattr`, and `delattr`.""" def visit_Attribute(self, node): """Convert attribute access to `getattr` call.""" <|body_0|> def visit_Assign(self, node): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AttributesToFunctions: """Replace attribute getters/setters with function calls. Namely, the functions `getattr`, `setattr`, and `delattr`.""" def visit_Attribute(self, node): """Convert attribute access to `getattr` call.""" self.generic_visit(node) if isinstance(node.ctx, ast.Lo...
the_stack_v2_python_sparse
flowgraph/trace/ast_transform.py
epatters/pyflowgraph
train
2
7fd36bc42ab35bc194c1b9a2fa17029d85bec702
[ "self.name = 'labchop'\nself.description = 'Reduce Lab Chops'\nself.procname = 'red'\nself.paramlist = []", "self.dataout = self.datain.copy()\nrphase = np.median(self.datain.table['R array'], axis=0)\nrquad = np.median(self.datain.table['R array Imag'], axis=0)\ntphase = np.median(self.datain.table['T array'], a...
<|body_start_0|> self.name = 'labchop' self.description = 'Reduce Lab Chops' self.procname = 'red' self.paramlist = [] <|end_body_0|> <|body_start_1|> self.dataout = self.datain.copy() rphase = np.median(self.datain.table['R array'], axis=0) rquad = np.median(sel...
Produce diagnostic data for lab chopping.
StepLabChop
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StepLabChop: """Produce diagnostic data for lab chopping.""" def setup(self): """Set parameters and metadata for the pipeline step. Output files have PRODTYPE = 'labchop', and are named with the step abbreviation 'RED'. There are currently no parameters defined for this step.""" ...
stack_v2_sparse_classes_36k_train_007239
2,732
permissive
[ { "docstring": "Set parameters and metadata for the pipeline step. Output files have PRODTYPE = 'labchop', and are named with the step abbreviation 'RED'. There are currently no parameters defined for this step.", "name": "setup", "signature": "def setup(self)" }, { "docstring": "Run the data re...
2
stack_v2_sparse_classes_30k_train_013453
Implement the Python class `StepLabChop` described below. Class description: Produce diagnostic data for lab chopping. Method signatures and docstrings: - def setup(self): Set parameters and metadata for the pipeline step. Output files have PRODTYPE = 'labchop', and are named with the step abbreviation 'RED'. There a...
Implement the Python class `StepLabChop` described below. Class description: Produce diagnostic data for lab chopping. Method signatures and docstrings: - def setup(self): Set parameters and metadata for the pipeline step. Output files have PRODTYPE = 'labchop', and are named with the step abbreviation 'RED'. There a...
493700340cd34d5f319af6f3a562a82135bb30dd
<|skeleton|> class StepLabChop: """Produce diagnostic data for lab chopping.""" def setup(self): """Set parameters and metadata for the pipeline step. Output files have PRODTYPE = 'labchop', and are named with the step abbreviation 'RED'. There are currently no parameters defined for this step.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class StepLabChop: """Produce diagnostic data for lab chopping.""" def setup(self): """Set parameters and metadata for the pipeline step. Output files have PRODTYPE = 'labchop', and are named with the step abbreviation 'RED'. There are currently no parameters defined for this step.""" self.name...
the_stack_v2_python_sparse
sofia_redux/instruments/hawc/steps/steplabchop.py
SOFIA-USRA/sofia_redux
train
12
f6f4c0d0004ae143068f6edd39b83b25cf58ae48
[ "tests = ['https://chromium.googlesource.com/chromiumos/manifest.git', 'test@abcdef.bla.com:39291/bla/manifest.git', 'test@abcdef.bla.com:39291/bla/manifest', 'test@abcdef.bla.com:39291/bla/Manifest-internal']\nfor test in tests:\n self.rc.SetDefaultCmdResult(output=test)\n self.assertFalse(repository.IsInter...
<|body_start_0|> tests = ['https://chromium.googlesource.com/chromiumos/manifest.git', 'test@abcdef.bla.com:39291/bla/manifest.git', 'test@abcdef.bla.com:39291/bla/manifest', 'test@abcdef.bla.com:39291/bla/Manifest-internal'] for test in tests: self.rc.SetDefaultCmdResult(output=test) ...
Test cases related to repository checkout methods.
RepositoryTests
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RepositoryTests: """Test cases related to repository checkout methods.""" def testExternalRepoCheckout(self): """Test we detect external checkouts properly.""" <|body_0|> def testInternalRepoCheckout(self): """Test we detect internal checkouts properly.""" ...
stack_v2_sparse_classes_36k_train_007240
6,078
permissive
[ { "docstring": "Test we detect external checkouts properly.", "name": "testExternalRepoCheckout", "signature": "def testExternalRepoCheckout(self)" }, { "docstring": "Test we detect internal checkouts properly.", "name": "testInternalRepoCheckout", "signature": "def testInternalRepoCheck...
2
null
Implement the Python class `RepositoryTests` described below. Class description: Test cases related to repository checkout methods. Method signatures and docstrings: - def testExternalRepoCheckout(self): Test we detect external checkouts properly. - def testInternalRepoCheckout(self): Test we detect internal checkout...
Implement the Python class `RepositoryTests` described below. Class description: Test cases related to repository checkout methods. Method signatures and docstrings: - def testExternalRepoCheckout(self): Test we detect external checkouts properly. - def testInternalRepoCheckout(self): Test we detect internal checkout...
72a05af97787001756bae2511b7985e61498c965
<|skeleton|> class RepositoryTests: """Test cases related to repository checkout methods.""" def testExternalRepoCheckout(self): """Test we detect external checkouts properly.""" <|body_0|> def testInternalRepoCheckout(self): """Test we detect internal checkouts properly.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RepositoryTests: """Test cases related to repository checkout methods.""" def testExternalRepoCheckout(self): """Test we detect external checkouts properly.""" tests = ['https://chromium.googlesource.com/chromiumos/manifest.git', 'test@abcdef.bla.com:39291/bla/manifest.git', 'test@abcdef....
the_stack_v2_python_sparse
third_party/chromite/cbuildbot/repository_unittest.py
metux/chromium-suckless
train
5
6702ed69e8b8b657f69824e879d632a9ef624975
[ "super(ObstacleForce, self).__init__()\nself.depthImWid = imWid\nself.depthImHgt = imHgt\nself.startCol = startCol\nself.sampleWidth = sampWid\nposPercent = (self.startCol + self.sampleWidth / 2.0) / self.depthImWid\nself.speedMult = speedMult\nself.angle = (posPercent - 0.5) * 60\nif self.startCol + self.sampleWid...
<|body_start_0|> super(ObstacleForce, self).__init__() self.depthImWid = imWid self.depthImHgt = imHgt self.startCol = startCol self.sampleWidth = sampWid posPercent = (self.startCol + self.sampleWidth / 2.0) / self.depthImWid self.speedMult = speedMult se...
Defines a Potential Field behavior for depth image-based obstacle reactions.
ObstacleForce
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ObstacleForce: """Defines a Potential Field behavior for depth image-based obstacle reactions.""" def __init__(self, startCol, sampWid, speedMult, imWid=640, imHgt=480): """Takes in starting column and section botWidth in the depth image to look at, a speed multiplier, and optionally...
stack_v2_sparse_classes_36k_train_007241
8,374
no_license
[ { "docstring": "Takes in starting column and section botWidth in the depth image to look at, a speed multiplier, and optionally a setting for the size of the depth image, botWidth and botHeight. Sets up the section of the depth image to use.", "name": "__init__", "signature": "def __init__(self, startCo...
2
stack_v2_sparse_classes_30k_train_000755
Implement the Python class `ObstacleForce` described below. Class description: Defines a Potential Field behavior for depth image-based obstacle reactions. Method signatures and docstrings: - def __init__(self, startCol, sampWid, speedMult, imWid=640, imHgt=480): Takes in starting column and section botWidth in the d...
Implement the Python class `ObstacleForce` described below. Class description: Defines a Potential Field behavior for depth image-based obstacle reactions. Method signatures and docstrings: - def __init__(self, startCol, sampWid, speedMult, imWid=640, imHgt=480): Takes in starting column and section botWidth in the d...
97bb378a325b1639110de06b88d6e237dffc7330
<|skeleton|> class ObstacleForce: """Defines a Potential Field behavior for depth image-based obstacle reactions.""" def __init__(self, startCol, sampWid, speedMult, imWid=640, imHgt=480): """Takes in starting column and section botWidth in the depth image to look at, a speed multiplier, and optionally...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ObstacleForce: """Defines a Potential Field behavior for depth image-based obstacle reactions.""" def __init__(self, startCol, sampWid, speedMult, imWid=640, imHgt=480): """Takes in starting column and section botWidth in the depth image to look at, a speed multiplier, and optionally a setting fo...
the_stack_v2_python_sparse
src/match_seeker/scripts/FieldBehaviors.py
FoxRobotLab/catkin_ws
train
6
35072eb5bf18dd7add7fe198d30600ada8ff1ebc
[ "if np.isscalar(radius):\n r = np.asarray([radius])\nelse:\n r = np.asarray(radius)\nif np.isscalar(data):\n d = data * np.ones((r.size,))\nelse:\n d = np.asarray(data)\nreturn (d, r)", "if len(data.shape) != 1:\n raise EquationException('{}: Invalid number of dimensions in prescribed initial data....
<|body_start_0|> if np.isscalar(radius): r = np.asarray([radius]) else: r = np.asarray(radius) if np.isscalar(data): d = data * np.ones((r.size,)) else: d = np.asarray(data) return (d, r) <|end_body_0|> <|body_start_1|> if ...
PrescribedInitialParameter
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PrescribedInitialParameter: def _setInitialData(self, data, radius=0): """Set prescribed initial data appropriately.""" <|body_0|> def _verifySettingsPrescribedInitialData(self, name, data, radius): """Verify the structure of the prescribed data.""" <|body_1|...
stack_v2_sparse_classes_36k_train_007242
1,272
permissive
[ { "docstring": "Set prescribed initial data appropriately.", "name": "_setInitialData", "signature": "def _setInitialData(self, data, radius=0)" }, { "docstring": "Verify the structure of the prescribed data.", "name": "_verifySettingsPrescribedInitialData", "signature": "def _verifySett...
2
null
Implement the Python class `PrescribedInitialParameter` described below. Class description: Implement the PrescribedInitialParameter class. Method signatures and docstrings: - def _setInitialData(self, data, radius=0): Set prescribed initial data appropriately. - def _verifySettingsPrescribedInitialData(self, name, d...
Implement the Python class `PrescribedInitialParameter` described below. Class description: Implement the PrescribedInitialParameter class. Method signatures and docstrings: - def _setInitialData(self, data, radius=0): Set prescribed initial data appropriately. - def _verifySettingsPrescribedInitialData(self, name, d...
eba9fabddfa4ef439737807ef30978a52ab55afb
<|skeleton|> class PrescribedInitialParameter: def _setInitialData(self, data, radius=0): """Set prescribed initial data appropriately.""" <|body_0|> def _verifySettingsPrescribedInitialData(self, name, data, radius): """Verify the structure of the prescribed data.""" <|body_1|...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PrescribedInitialParameter: def _setInitialData(self, data, radius=0): """Set prescribed initial data appropriately.""" if np.isscalar(radius): r = np.asarray([radius]) else: r = np.asarray(radius) if np.isscalar(data): d = data * np.ones((r....
the_stack_v2_python_sparse
py/DREAM/Settings/Equations/PrescribedInitialParameter.py
anymodel/DREAM-1
train
0
f15caaa4b00e272889713c8a34a576fc1ddcbd62
[ "scraper = request.user.scraper\nparams = GetScrapesRequestSerializer(data=request.data)\nif not params.is_valid():\n return Response(HttpBadRequestSerializer(get_error_desc(params)), status=HTTP_400_BAD_REQUEST)\nlimit = params.data['limit']\nscrapes = list(scraper.get_scrapes().order_by('-upload_date')[:limit]...
<|body_start_0|> scraper = request.user.scraper params = GetScrapesRequestSerializer(data=request.data) if not params.is_valid(): return Response(HttpBadRequestSerializer(get_error_desc(params)), status=HTTP_400_BAD_REQUEST) limit = params.data['limit'] scrapes = list...
ScrapesView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ScrapesView: def get(self, request): """API call to get recents scrapes""" <|body_0|> def delete(self, request): """API call to delete all scrapes""" <|body_1|> <|end_skeleton|> <|body_start_0|> scraper = request.user.scraper params = GetScr...
stack_v2_sparse_classes_36k_train_007243
2,115
no_license
[ { "docstring": "API call to get recents scrapes", "name": "get", "signature": "def get(self, request)" }, { "docstring": "API call to delete all scrapes", "name": "delete", "signature": "def delete(self, request)" } ]
2
stack_v2_sparse_classes_30k_train_021623
Implement the Python class `ScrapesView` described below. Class description: Implement the ScrapesView class. Method signatures and docstrings: - def get(self, request): API call to get recents scrapes - def delete(self, request): API call to delete all scrapes
Implement the Python class `ScrapesView` described below. Class description: Implement the ScrapesView class. Method signatures and docstrings: - def get(self, request): API call to get recents scrapes - def delete(self, request): API call to delete all scrapes <|skeleton|> class ScrapesView: def get(self, requ...
d5171c5b3b54265cecbc3dfab2731729b66e6e70
<|skeleton|> class ScrapesView: def get(self, request): """API call to get recents scrapes""" <|body_0|> def delete(self, request): """API call to delete all scrapes""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ScrapesView: def get(self, request): """API call to get recents scrapes""" scraper = request.user.scraper params = GetScrapesRequestSerializer(data=request.data) if not params.is_valid(): return Response(HttpBadRequestSerializer(get_error_desc(params)), status=HTTP_...
the_stack_v2_python_sparse
api/views/ScrapesView.py
Scraper-Club/Server
train
1
9f2f7bdbe644fc84c68066666508221cd7e6e9bc
[ "super().__init__(**kwargs)\nself.fc1 = keras.layers.Dense(128, activation='relu')\nself.reshape = keras.layers.Reshape((4, 4, 8))\nself.conv1 = keras.layers.Conv2D(8, (3, 3), padding='same', activation='relu')\nself.up1 = keras.layers.UpSampling2D(size=(2, 2))\nself.conv2 = keras.layers.Conv2D(8, (3, 3), padding='...
<|body_start_0|> super().__init__(**kwargs) self.fc1 = keras.layers.Dense(128, activation='relu') self.reshape = keras.layers.Reshape((4, 4, 8)) self.conv1 = keras.layers.Conv2D(8, (3, 3), padding='same', activation='relu') self.up1 = keras.layers.UpSampling2D(size=(2, 2)) ...
MNIST decoder used in the Counterfactual with Reinforcement Learning experiments. The model consists of a fully connected layer of 128 units with ReLU activation followed by a convolutional block. The convolutional block consists fo 4 convolutional layers having 8, 8, 8 and 1 channels and a kernel size of 3. Each convo...
MNISTDecoder
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MNISTDecoder: """MNIST decoder used in the Counterfactual with Reinforcement Learning experiments. The model consists of a fully connected layer of 128 units with ReLU activation followed by a convolutional block. The convolutional block consists fo 4 convolutional layers having 8, 8, 8 and 1 cha...
stack_v2_sparse_classes_36k_train_007244
8,692
permissive
[ { "docstring": "Constructor.", "name": "__init__", "signature": "def __init__(self, **kwargs) -> None" }, { "docstring": "Forward pass. Parameters ---------- x Input tensor **kwargs Other arguments. Not used. Returns ------- Decoded input having each component in the interval [0, 1].", "name...
2
null
Implement the Python class `MNISTDecoder` described below. Class description: MNIST decoder used in the Counterfactual with Reinforcement Learning experiments. The model consists of a fully connected layer of 128 units with ReLU activation followed by a convolutional block. The convolutional block consists fo 4 convol...
Implement the Python class `MNISTDecoder` described below. Class description: MNIST decoder used in the Counterfactual with Reinforcement Learning experiments. The model consists of a fully connected layer of 128 units with ReLU activation followed by a convolutional block. The convolutional block consists fo 4 convol...
54d0c957fb01c7ebba4e2a0d28fcbde52d9c6718
<|skeleton|> class MNISTDecoder: """MNIST decoder used in the Counterfactual with Reinforcement Learning experiments. The model consists of a fully connected layer of 128 units with ReLU activation followed by a convolutional block. The convolutional block consists fo 4 convolutional layers having 8, 8, 8 and 1 cha...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MNISTDecoder: """MNIST decoder used in the Counterfactual with Reinforcement Learning experiments. The model consists of a fully connected layer of 128 units with ReLU activation followed by a convolutional block. The convolutional block consists fo 4 convolutional layers having 8, 8, 8 and 1 channels and a k...
the_stack_v2_python_sparse
alibi/models/tensorflow/cfrl_models.py
SeldonIO/alibi
train
2,143
54b3e82178d6d185c5df7325c906c948b1d10ad5
[ "words.sort()\nwords += ['z']\nstack = []\nret = ''\nlength_ret = 0\nfor i in range(len(words)):\n s = words[i]\n length_s = len(s)\n if length_s == 1:\n if stack and len(stack[-1]) > length_ret:\n ret = stack[-1]\n length_ret = len(ret)\n stack = [words[i]]\n else:\n...
<|body_start_0|> words.sort() words += ['z'] stack = [] ret = '' length_ret = 0 for i in range(len(words)): s = words[i] length_s = len(s) if length_s == 1: if stack and len(stack[-1]) > length_ret: r...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def longestWord(self, words): """:type words: List[str] :rtype: str""" <|body_0|> def longestWord2(self, words): """:type words: List[str] :rtype: str""" <|body_1|> def longestWord1(self, words): """:type words: List[str] :rtype: str"""...
stack_v2_sparse_classes_36k_train_007245
2,692
no_license
[ { "docstring": ":type words: List[str] :rtype: str", "name": "longestWord", "signature": "def longestWord(self, words)" }, { "docstring": ":type words: List[str] :rtype: str", "name": "longestWord2", "signature": "def longestWord2(self, words)" }, { "docstring": ":type words: Lis...
3
stack_v2_sparse_classes_30k_train_012248
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def longestWord(self, words): :type words: List[str] :rtype: str - def longestWord2(self, words): :type words: List[str] :rtype: str - def longestWord1(self, words): :type words:...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def longestWord(self, words): :type words: List[str] :rtype: str - def longestWord2(self, words): :type words: List[str] :rtype: str - def longestWord1(self, words): :type words:...
70bdd75b6af2e1811c1beab22050c01d28d7373e
<|skeleton|> class Solution: def longestWord(self, words): """:type words: List[str] :rtype: str""" <|body_0|> def longestWord2(self, words): """:type words: List[str] :rtype: str""" <|body_1|> def longestWord1(self, words): """:type words: List[str] :rtype: str"""...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def longestWord(self, words): """:type words: List[str] :rtype: str""" words.sort() words += ['z'] stack = [] ret = '' length_ret = 0 for i in range(len(words)): s = words[i] length_s = len(s) if length_s == ...
the_stack_v2_python_sparse
python/leetcode_bak/720_Longest_Word_in_Dictionary.py
bobcaoge/my-code
train
0
64be6f85f05543216ef7af63a1584f6809fac468
[ "import math\nresult = [nums]\nnext = nums\nfor a in xrange(math.factorial(len(nums)) - 1):\n next = self.nextPermutation(next)\n result.append(next)\nreturn result", "new = [x for x in nums]\ni = len(new) - 1\nlargest = new[i]\nfor index in range(len(new) - 2, -1, -1):\n if new[index] < largest:\n ...
<|body_start_0|> import math result = [nums] next = nums for a in xrange(math.factorial(len(nums)) - 1): next = self.nextPermutation(next) result.append(next) return result <|end_body_0|> <|body_start_1|> new = [x for x in nums] i = len(ne...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def permute(self, nums): """:type nums: List[int] :rtype: List[List[int]]""" <|body_0|> def nextPermutation(self, nums): """from leetcode problem 31. :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.""" <|body_...
stack_v2_sparse_classes_36k_train_007246
2,895
no_license
[ { "docstring": ":type nums: List[int] :rtype: List[List[int]]", "name": "permute", "signature": "def permute(self, nums)" }, { "docstring": "from leetcode problem 31. :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.", "name": "nextPermutation", "si...
2
stack_v2_sparse_classes_30k_train_016018
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def permute(self, nums): :type nums: List[int] :rtype: List[List[int]] - def nextPermutation(self, nums): from leetcode problem 31. :type nums: List[int] :rtype: void Do not retu...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def permute(self, nums): :type nums: List[int] :rtype: List[List[int]] - def nextPermutation(self, nums): from leetcode problem 31. :type nums: List[int] :rtype: void Do not retu...
2157d194db12f6ea808c1f5f069ae52c1018dee1
<|skeleton|> class Solution: def permute(self, nums): """:type nums: List[int] :rtype: List[List[int]]""" <|body_0|> def nextPermutation(self, nums): """from leetcode problem 31. :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.""" <|body_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def permute(self, nums): """:type nums: List[int] :rtype: List[List[int]]""" import math result = [nums] next = nums for a in xrange(math.factorial(len(nums)) - 1): next = self.nextPermutation(next) result.append(next) return re...
the_stack_v2_python_sparse
leetcode/46.py
bbung24/codingStudy
train
1
4a4ee718579e280e14779c98faaa0831270e34dd
[ "self.file = file\nself.num_cards = num_cards\nself.a, self.b = self.parse(self.read_shuffle())", "instructions = []\nwith open(self.file) as f:\n for line in f.readlines():\n if 'deal with increment ' in line:\n instructions.append(('I', int(line[20:])))\n elif 'deal into new stack' i...
<|body_start_0|> self.file = file self.num_cards = num_cards self.a, self.b = self.parse(self.read_shuffle()) <|end_body_0|> <|body_start_1|> instructions = [] with open(self.file) as f: for line in f.readlines(): if 'deal with increment ' in line: ...
Class sorting the cards in the deck
Deck
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Deck: """Class sorting the cards in the deck""" def __init__(self, file, num_cards): """Initialize number of cards and parse instructions""" <|body_0|> def read_shuffle(self): """Go through instructions list to shuffle""" <|body_1|> def parse(self, i...
stack_v2_sparse_classes_36k_train_007247
1,211
permissive
[ { "docstring": "Initialize number of cards and parse instructions", "name": "__init__", "signature": "def __init__(self, file, num_cards)" }, { "docstring": "Go through instructions list to shuffle", "name": "read_shuffle", "signature": "def read_shuffle(self)" }, { "docstring": ...
3
stack_v2_sparse_classes_30k_train_013884
Implement the Python class `Deck` described below. Class description: Class sorting the cards in the deck Method signatures and docstrings: - def __init__(self, file, num_cards): Initialize number of cards and parse instructions - def read_shuffle(self): Go through instructions list to shuffle - def parse(self, instr...
Implement the Python class `Deck` described below. Class description: Class sorting the cards in the deck Method signatures and docstrings: - def __init__(self, file, num_cards): Initialize number of cards and parse instructions - def read_shuffle(self): Go through instructions list to shuffle - def parse(self, instr...
9e4ef53bb1f99b5d9bab2371cb0578c7b3538a01
<|skeleton|> class Deck: """Class sorting the cards in the deck""" def __init__(self, file, num_cards): """Initialize number of cards and parse instructions""" <|body_0|> def read_shuffle(self): """Go through instructions list to shuffle""" <|body_1|> def parse(self, i...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Deck: """Class sorting the cards in the deck""" def __init__(self, file, num_cards): """Initialize number of cards and parse instructions""" self.file = file self.num_cards = num_cards self.a, self.b = self.parse(self.read_shuffle()) def read_shuffle(self): ""...
the_stack_v2_python_sparse
2019/day22/python/deck.py
realquizm/advent-of-code
train
0
841fffeb371dae4280d4352224697c487acec0a8
[ "statements = re.compile(';[ \\\\t]*$', re.M)\nsql_list = []\nusing = options.get('database', DEFAULT_DB_ALIAS)\nconnection = connections[using]\nfor statement in statements.split(sql.decode(settings.FILE_CHARSET)):\n statement = re.sub('--.*([\\\\n\\\\Z]|$)', '', statement)\n if statement.strip():\n s...
<|body_start_0|> statements = re.compile(';[ \\t]*$', re.M) sql_list = [] using = options.get('database', DEFAULT_DB_ALIAS) connection = connections[using] for statement in statements.split(sql.decode(settings.FILE_CHARSET)): statement = re.sub('--.*([\\n\\Z]|$)', '',...
Example: python manage.py drop corporate_memberships memberships
Command
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Command: """Example: python manage.py drop corporate_memberships memberships""" def run_sql(self, sql, **options): """Parse through sql statements. Execute each sql statement. Commit in one transaction.""" <|body_0|> def drop_tables(self, app_name, **options): ""...
stack_v2_sparse_classes_36k_train_007248
2,888
no_license
[ { "docstring": "Parse through sql statements. Execute each sql statement. Commit in one transaction.", "name": "run_sql", "signature": "def run_sql(self, sql, **options)" }, { "docstring": "Drop application tables", "name": "drop_tables", "signature": "def drop_tables(self, app_name, **o...
3
null
Implement the Python class `Command` described below. Class description: Example: python manage.py drop corporate_memberships memberships Method signatures and docstrings: - def run_sql(self, sql, **options): Parse through sql statements. Execute each sql statement. Commit in one transaction. - def drop_tables(self, ...
Implement the Python class `Command` described below. Class description: Example: python manage.py drop corporate_memberships memberships Method signatures and docstrings: - def run_sql(self, sql, **options): Parse through sql statements. Execute each sql statement. Commit in one transaction. - def drop_tables(self, ...
f2ac4ecc076b223c262f2cde4fa3b35b4a5cd54e
<|skeleton|> class Command: """Example: python manage.py drop corporate_memberships memberships""" def run_sql(self, sql, **options): """Parse through sql statements. Execute each sql statement. Commit in one transaction.""" <|body_0|> def drop_tables(self, app_name, **options): ""...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Command: """Example: python manage.py drop corporate_memberships memberships""" def run_sql(self, sql, **options): """Parse through sql statements. Execute each sql statement. Commit in one transaction.""" statements = re.compile(';[ \\t]*$', re.M) sql_list = [] using = op...
the_stack_v2_python_sparse
tendenci/apps/base/management/commands/drop.py
chendong0444/ams
train
0
a7aa6c0124bb908d0690314e3613596f802bd61a
[ "Calibration.__init__(self, ecal_train, hcal_train, true_train, lim)\nif weights == 'gaussian':\n self.weights = lambda x: np.exp(-x ** 2 / sigma ** 2 / 2)\nelse:\n self.weights = weights\nself.n_neighbors_ecal_eq_0 = n_neighbors_ecal_eq_0\nself.n_neighbors_ecal_neq_0 = n_neighbors_ecal_neq_0\nself.algorithm ...
<|body_start_0|> Calibration.__init__(self, ecal_train, hcal_train, true_train, lim) if weights == 'gaussian': self.weights = lambda x: np.exp(-x ** 2 / sigma ** 2 / 2) else: self.weights = weights self.n_neighbors_ecal_eq_0 = n_neighbors_ecal_eq_0 self.n_...
Inherit from Calibration. Class to calibrate the true energy of a particle thanks to training datas. We use the a k neareast neighbours method. We do the pondered mean of the true energies of k neareast neighbours. Attributs --------- ecal_train : array ecal value to train the calibration hcal_train : array ecal value ...
KNN
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class KNN: """Inherit from Calibration. Class to calibrate the true energy of a particle thanks to training datas. We use the a k neareast neighbours method. We do the pondered mean of the true energies of k neareast neighbours. Attributs --------- ecal_train : array ecal value to train the calibration...
stack_v2_sparse_classes_36k_train_007249
8,091
no_license
[ { "docstring": "Parameters ---------- ecal_train : array-like ecal value to train the calibration hcal_train : array-like hcal value to train the calibration true_train : array-like true value to train the calibration n_neighbors_ecal_eq_0: int Number of neighbors to use by default for k_neighbors queries. for ...
4
stack_v2_sparse_classes_30k_train_017137
Implement the Python class `KNN` described below. Class description: Inherit from Calibration. Class to calibrate the true energy of a particle thanks to training datas. We use the a k neareast neighbours method. We do the pondered mean of the true energies of k neareast neighbours. Attributs --------- ecal_train : ar...
Implement the Python class `KNN` described below. Class description: Inherit from Calibration. Class to calibrate the true energy of a particle thanks to training datas. We use the a k neareast neighbours method. We do the pondered mean of the true energies of k neareast neighbours. Attributs --------- ecal_train : ar...
53dbbd2e68986602c29008338d6c9cc96edc6d77
<|skeleton|> class KNN: """Inherit from Calibration. Class to calibrate the true energy of a particle thanks to training datas. We use the a k neareast neighbours method. We do the pondered mean of the true energies of k neareast neighbours. Attributs --------- ecal_train : array ecal value to train the calibration...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class KNN: """Inherit from Calibration. Class to calibrate the true energy of a particle thanks to training datas. We use the a k neareast neighbours method. We do the pondered mean of the true energies of k neareast neighbours. Attributs --------- ecal_train : array ecal value to train the calibration hcal_train :...
the_stack_v2_python_sparse
pfcalibration/KNN.py
sniang/particle_flow_calibration
train
3
e2cc276245445d80ffddc4d0b16051f6adcfa0c1
[ "super().__init__(path)\nself.subreddits = get_subreddits(path, self.files)\nself.sentiments = {'normal': [], 'maximum': [], 'minimum': [], 'all': []}\nself.set_sentiments()\nself.save_order()", "for sent in self.subreddits.keys():\n self.order.append(sent)\n normal, maximum, minimum, sentiment_all = self.g...
<|body_start_0|> super().__init__(path) self.subreddits = get_subreddits(path, self.files) self.sentiments = {'normal': [], 'maximum': [], 'minimum': [], 'all': []} self.set_sentiments() self.save_order() <|end_body_0|> <|body_start_1|> for sent in self.subreddits.keys()...
An object containing all raw and processed data in every given subreddit. Attributes: subreddits: dictionary of form: subreddit:word:sentiment, standard derivation sentiments: dictionary of views (normal, min, max, all) containing feature vectors of all subreddits order: list representing the order of the subreddits in...
SubredditData
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SubredditData: """An object containing all raw and processed data in every given subreddit. Attributes: subreddits: dictionary of form: subreddit:word:sentiment, standard derivation sentiments: dictionary of views (normal, min, max, all) containing feature vectors of all subreddits order: list re...
stack_v2_sparse_classes_36k_train_007250
5,052
no_license
[ { "docstring": "Initialize an object containing all raw and processed data Arguments: path: Path to the folder containing the subreddits", "name": "__init__", "signature": "def __init__(self, path)" }, { "docstring": "Process sentiments in all subreddits, thus create feature matrix Arguments: wo...
5
stack_v2_sparse_classes_30k_val_000899
Implement the Python class `SubredditData` described below. Class description: An object containing all raw and processed data in every given subreddit. Attributes: subreddits: dictionary of form: subreddit:word:sentiment, standard derivation sentiments: dictionary of views (normal, min, max, all) containing feature v...
Implement the Python class `SubredditData` described below. Class description: An object containing all raw and processed data in every given subreddit. Attributes: subreddits: dictionary of form: subreddit:word:sentiment, standard derivation sentiments: dictionary of views (normal, min, max, all) containing feature v...
8e30b14d811ee345dd7ca12de4e6d26bd6a7a8c8
<|skeleton|> class SubredditData: """An object containing all raw and processed data in every given subreddit. Attributes: subreddits: dictionary of form: subreddit:word:sentiment, standard derivation sentiments: dictionary of views (normal, min, max, all) containing feature vectors of all subreddits order: list re...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SubredditData: """An object containing all raw and processed data in every given subreddit. Attributes: subreddits: dictionary of form: subreddit:word:sentiment, standard derivation sentiments: dictionary of views (normal, min, max, all) containing feature vectors of all subreddits order: list representing th...
the_stack_v2_python_sparse
examinlexica/original/subreddit_data.py
HubReb/examing_socialsent_lexica
train
2
ec8a807bb69129d6f31bf02de255dbca408fbd85
[ "self.uri = uri\nself.schema_file = schema_file\nself.http_method = http_method\nself.params = params\nself.test = test\nself.runner = runner\nself.headers = {k: ACCEPT_HEADER[k] for k in ACCEPT_HEADER.keys()}\nself.full_message = []", "for header_name, header_value in self.runner.headers.items():\n self.heade...
<|body_start_0|> self.uri = uri self.schema_file = schema_file self.http_method = http_method self.params = params self.test = test self.runner = runner self.headers = {k: ACCEPT_HEADER[k] for k in ACCEPT_HEADER.keys()} self.full_message = [] <|end_body_0|...
Executes API request, validates response and sets result to pass/fail The SingleTestExecutor is a generalized model for executing tests against the API. It executes a request, checks for response code, and validates the returned object against a schema. Attributes: uri (str): uri to be requested schema_file (str): JSON...
SingleTestExecutor
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SingleTestExecutor: """Executes API request, validates response and sets result to pass/fail The SingleTestExecutor is a generalized model for executing tests against the API. It executes a request, checks for response code, and validates the returned object against a schema. Attributes: uri (str...
stack_v2_sparse_classes_36k_train_007251
5,877
permissive
[ { "docstring": "instantiates a SingleTestExecutor object Args: uri (str): uri to be requested schema_file (str): JSON schema file to validate response against http_method (int): GET or POST request params (dict): parameters/filters to submit with query test (Test): reference to Test object runner (TestRunner): ...
3
stack_v2_sparse_classes_30k_train_003300
Implement the Python class `SingleTestExecutor` described below. Class description: Executes API request, validates response and sets result to pass/fail The SingleTestExecutor is a generalized model for executing tests against the API. It executes a request, checks for response code, and validates the returned object...
Implement the Python class `SingleTestExecutor` described below. Class description: Executes API request, validates response and sets result to pass/fail The SingleTestExecutor is a generalized model for executing tests against the API. It executes a request, checks for response code, and validates the returned object...
0e764005d476aa3c370eadf890a633d927d2374c
<|skeleton|> class SingleTestExecutor: """Executes API request, validates response and sets result to pass/fail The SingleTestExecutor is a generalized model for executing tests against the API. It executes a request, checks for response code, and validates the returned object against a schema. Attributes: uri (str...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SingleTestExecutor: """Executes API request, validates response and sets result to pass/fail The SingleTestExecutor is a generalized model for executing tests against the API. It executes a request, checks for response code, and validates the returned object against a schema. Attributes: uri (str): uri to be ...
the_stack_v2_python_sparse
compliance_suite/single_test_executor.py
alipski/rnaget-compliance-suite
train
0
f73e4bcf78273940cbba1f31c19d6d28be77824b
[ "for fld in ['LmChallengeResponseFields', 'NtChallengeResponseFields', 'DomainNameFields', 'UserNameFields', 'WorkstationFields', 'EncryptedRandomSessionKeyFields']:\n yield (fld, self[fld])\nreturn", "for _, item in self.enumerate():\n yield item\nreturn", "for item in self.iterate():\n yield item\nre...
<|body_start_0|> for fld in ['LmChallengeResponseFields', 'NtChallengeResponseFields', 'DomainNameFields', 'UserNameFields', 'WorkstationFields', 'EncryptedRandomSessionKeyFields']: yield (fld, self[fld]) return <|end_body_0|> <|body_start_1|> for _, item in self.enumerate(): ...
AUTHENTICATE_MESSAGE
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AUTHENTICATE_MESSAGE: def enumerate(self): """Yield the name and field that compose the message type payload.""" <|body_0|> def iterate(self): """Yield each field that composes the message type payload.""" <|body_1|> def Fields(self): """Yield al...
stack_v2_sparse_classes_36k_train_007252
31,838
permissive
[ { "docstring": "Yield the name and field that compose the message type payload.", "name": "enumerate", "signature": "def enumerate(self)" }, { "docstring": "Yield each field that composes the message type payload.", "name": "iterate", "signature": "def iterate(self)" }, { "docstr...
3
null
Implement the Python class `AUTHENTICATE_MESSAGE` described below. Class description: Implement the AUTHENTICATE_MESSAGE class. Method signatures and docstrings: - def enumerate(self): Yield the name and field that compose the message type payload. - def iterate(self): Yield each field that composes the message type ...
Implement the Python class `AUTHENTICATE_MESSAGE` described below. Class description: Implement the AUTHENTICATE_MESSAGE class. Method signatures and docstrings: - def enumerate(self): Yield the name and field that compose the message type payload. - def iterate(self): Yield each field that composes the message type ...
e02b014dc764ed822288210248c9438a843af8a9
<|skeleton|> class AUTHENTICATE_MESSAGE: def enumerate(self): """Yield the name and field that compose the message type payload.""" <|body_0|> def iterate(self): """Yield each field that composes the message type payload.""" <|body_1|> def Fields(self): """Yield al...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AUTHENTICATE_MESSAGE: def enumerate(self): """Yield the name and field that compose the message type payload.""" for fld in ['LmChallengeResponseFields', 'NtChallengeResponseFields', 'DomainNameFields', 'UserNameFields', 'WorkstationFields', 'EncryptedRandomSessionKeyFields']: yiel...
the_stack_v2_python_sparse
template/protocol/nlmp.py
arizvisa/syringe
train
36
32a1945cb0fa6d32a08f4222b261daed7ff59956
[ "self.cluster_name = cluster_name\nself.cluster_size = cluster_size\nself.encryption_config = encryption_config\nself.ip_preference = ip_preference\nself.metadata_fault_tolerance = metadata_fault_tolerance\nself.network_config = network_config\nself.node_ips = node_ips", "if dictionary is None:\n return None\n...
<|body_start_0|> self.cluster_name = cluster_name self.cluster_size = cluster_size self.encryption_config = encryption_config self.ip_preference = ip_preference self.metadata_fault_tolerance = metadata_fault_tolerance self.network_config = network_config self.node...
Implementation of the 'CreateCloudClusterParameters' model. Specifies the parameters needed for creation of a new Cluster. Attributes: cluster_name (string, required): Specifies the name of the new Cluster. cluster_size (ClusterSizeEnum): Specifies the size of the cluster. It is set as Large by default if the parameter...
CreateCloudClusterParameters
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CreateCloudClusterParameters: """Implementation of the 'CreateCloudClusterParameters' model. Specifies the parameters needed for creation of a new Cluster. Attributes: cluster_name (string, required): Specifies the name of the new Cluster. cluster_size (ClusterSizeEnum): Specifies the size of the...
stack_v2_sparse_classes_36k_train_007253
3,779
permissive
[ { "docstring": "Constructor for the CreateCloudClusterParameters class", "name": "__init__", "signature": "def __init__(self, cluster_name=None, cluster_size=None, encryption_config=None, ip_preference=None, metadata_fault_tolerance=None, network_config=None, node_ips=None)" }, { "docstring": "C...
2
stack_v2_sparse_classes_30k_train_010911
Implement the Python class `CreateCloudClusterParameters` described below. Class description: Implementation of the 'CreateCloudClusterParameters' model. Specifies the parameters needed for creation of a new Cluster. Attributes: cluster_name (string, required): Specifies the name of the new Cluster. cluster_size (Clus...
Implement the Python class `CreateCloudClusterParameters` described below. Class description: Implementation of the 'CreateCloudClusterParameters' model. Specifies the parameters needed for creation of a new Cluster. Attributes: cluster_name (string, required): Specifies the name of the new Cluster. cluster_size (Clus...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class CreateCloudClusterParameters: """Implementation of the 'CreateCloudClusterParameters' model. Specifies the parameters needed for creation of a new Cluster. Attributes: cluster_name (string, required): Specifies the name of the new Cluster. cluster_size (ClusterSizeEnum): Specifies the size of the...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CreateCloudClusterParameters: """Implementation of the 'CreateCloudClusterParameters' model. Specifies the parameters needed for creation of a new Cluster. Attributes: cluster_name (string, required): Specifies the name of the new Cluster. cluster_size (ClusterSizeEnum): Specifies the size of the cluster. It ...
the_stack_v2_python_sparse
cohesity_management_sdk/models/create_cloud_cluster_parameters.py
cohesity/management-sdk-python
train
24
97c3b1dd333d1bdf484b216dd99c4f7975a506a1
[ "self.IndivWord_Dic = IndivWordDict\nself.WordTag_Dic = WordTagDict\nself.TagWord_Dic = TagWordDict\nTemplateDict = collections.defaultdict(list)\nself.Template_Dic = TemplateDict\nself.indivword_path = indivword_path\nself.featureword_path = featureword_path\nself.template_path = template_path\nif indivword_path !...
<|body_start_0|> self.IndivWord_Dic = IndivWordDict self.WordTag_Dic = WordTagDict self.TagWord_Dic = TagWordDict TemplateDict = collections.defaultdict(list) self.Template_Dic = TemplateDict self.indivword_path = indivword_path self.featureword_path = featureword...
Initial_Dict_Load
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Initial_Dict_Load: def __init__(self, IndivWordDict={}, WordTagDict={}, TagWordDict={}, TemplateDict={}, indivword_path='', featureword_path='', template_path=''): """初始化操作 :param IndivWordDict: 个体词-标签词典 :param WordTagDict: 功能词-标签词典 :param TagWordDict: 标签-功能词列表词典 :param TemplateDict: 复述模...
stack_v2_sparse_classes_36k_train_007254
5,984
no_license
[ { "docstring": "初始化操作 :param IndivWordDict: 个体词-标签词典 :param WordTagDict: 功能词-标签词典 :param TagWordDict: 标签-功能词列表词典 :param TemplateDict: 复述模板词典 :param indivword_path: 个体词读取路径 :param featureword_path: 功能词读取路径 :param template_path: 复述模板读取路径", "name": "__init__", "signature": "def __init__(self, IndivWordDict...
4
stack_v2_sparse_classes_30k_train_007696
Implement the Python class `Initial_Dict_Load` described below. Class description: Implement the Initial_Dict_Load class. Method signatures and docstrings: - def __init__(self, IndivWordDict={}, WordTagDict={}, TagWordDict={}, TemplateDict={}, indivword_path='', featureword_path='', template_path=''): 初始化操作 :param In...
Implement the Python class `Initial_Dict_Load` described below. Class description: Implement the Initial_Dict_Load class. Method signatures and docstrings: - def __init__(self, IndivWordDict={}, WordTagDict={}, TagWordDict={}, TemplateDict={}, indivword_path='', featureword_path='', template_path=''): 初始化操作 :param In...
829cb826df2de502ac38ef28cac623d868e66ead
<|skeleton|> class Initial_Dict_Load: def __init__(self, IndivWordDict={}, WordTagDict={}, TagWordDict={}, TemplateDict={}, indivword_path='', featureword_path='', template_path=''): """初始化操作 :param IndivWordDict: 个体词-标签词典 :param WordTagDict: 功能词-标签词典 :param TagWordDict: 标签-功能词列表词典 :param TemplateDict: 复述模...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Initial_Dict_Load: def __init__(self, IndivWordDict={}, WordTagDict={}, TagWordDict={}, TemplateDict={}, indivword_path='', featureword_path='', template_path=''): """初始化操作 :param IndivWordDict: 个体词-标签词典 :param WordTagDict: 功能词-标签词典 :param TagWordDict: 标签-功能词列表词典 :param TemplateDict: 复述模板词典 :param ind...
the_stack_v2_python_sparse
SentenceParaphrase/TemplateMatching/InitializeDict.py
astronstar/LearningJournal-Code
train
0
cb13c00cfb6032383b7dac6070d6bdb64fe02563
[ "import netCDF4\nfrom netcdftime import utime\nself.nc = netCDF4.Dataset(filename)\nself.ncv = self.nc.variables\nself.lon = self.ncv['SCHISM_hgrid_node_x'][:]\nself.lat = self.ncv['SCHISM_hgrid_node_y'][:]\nself.nodeids = np.arange(len(self.lon))\nself.nv = self.ncv['SCHISM_hgrid_face_nodes'][:, :3] - 1\nself.time...
<|body_start_0|> import netCDF4 from netcdftime import utime self.nc = netCDF4.Dataset(filename) self.ncv = self.nc.variables self.lon = self.ncv['SCHISM_hgrid_node_x'][:] self.lat = self.ncv['SCHISM_hgrid_node_y'][:] self.nodeids = np.arange(len(self.lon)) ...
schism_output
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class schism_output: def __init__(self, filename): """read output filename and initialize grid""" <|body_0|> def init_node_tree(self, latlon=True): """build a node tree using cKDTree for a quick search for node coordinates""" <|body_1|> def find_nearest_node(s...
stack_v2_sparse_classes_36k_train_007255
19,398
no_license
[ { "docstring": "read output filename and initialize grid", "name": "__init__", "signature": "def __init__(self, filename)" }, { "docstring": "build a node tree using cKDTree for a quick search for node coordinates", "name": "init_node_tree", "signature": "def init_node_tree(self, latlon=...
3
stack_v2_sparse_classes_30k_train_008371
Implement the Python class `schism_output` described below. Class description: Implement the schism_output class. Method signatures and docstrings: - def __init__(self, filename): read output filename and initialize grid - def init_node_tree(self, latlon=True): build a node tree using cKDTree for a quick search for n...
Implement the Python class `schism_output` described below. Class description: Implement the schism_output class. Method signatures and docstrings: - def __init__(self, filename): read output filename and initialize grid - def init_node_tree(self, latlon=True): build a node tree using cKDTree for a quick search for n...
1828b3be0531d38171e5d16f77c1c422033adb2e
<|skeleton|> class schism_output: def __init__(self, filename): """read output filename and initialize grid""" <|body_0|> def init_node_tree(self, latlon=True): """build a node tree using cKDTree for a quick search for node coordinates""" <|body_1|> def find_nearest_node(s...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class schism_output: def __init__(self, filename): """read output filename and initialize grid""" import netCDF4 from netcdftime import utime self.nc = netCDF4.Dataset(filename) self.ncv = self.nc.variables self.lon = self.ncv['SCHISM_hgrid_node_x'][:] self.la...
the_stack_v2_python_sparse
scripts/schism.py
hofmeist/schism-setups
train
0
a68b9565a97edec62497eafc94f3d89a1e5616cc
[ "Part = self.old_state.apps.get_model('part', 'part')\npart = Part.objects.create(name='PART', description='A purchaseable part', purchaseable=True, level=0, tree_id=0, lft=0, rght=0)\nCompany = self.old_state.apps.get_model('company', 'company')\nsupplier = Company.objects.create(name='Supplier', description='A su...
<|body_start_0|> Part = self.old_state.apps.get_model('part', 'part') part = Part.objects.create(name='PART', description='A purchaseable part', purchaseable=True, level=0, tree_id=0, lft=0, rght=0) Company = self.old_state.apps.get_model('company', 'company') supplier = Company.objects....
Tests for upgrade from basic currency support to django-money.
TestCurrencyMigration
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestCurrencyMigration: """Tests for upgrade from basic currency support to django-money.""" def prepare(self): """Prepare some data: - A part to buy - A supplier to buy from - A supplier part - Multiple currency objects - Multiple supplier price breaks""" <|body_0|> def ...
stack_v2_sparse_classes_36k_train_007256
12,626
permissive
[ { "docstring": "Prepare some data: - A part to buy - A supplier to buy from - A supplier part - Multiple currency objects - Multiple supplier price breaks", "name": "prepare", "signature": "def prepare(self)" }, { "docstring": "Test database state after applying migrations", "name": "test_cu...
2
null
Implement the Python class `TestCurrencyMigration` described below. Class description: Tests for upgrade from basic currency support to django-money. Method signatures and docstrings: - def prepare(self): Prepare some data: - A part to buy - A supplier to buy from - A supplier part - Multiple currency objects - Multi...
Implement the Python class `TestCurrencyMigration` described below. Class description: Tests for upgrade from basic currency support to django-money. Method signatures and docstrings: - def prepare(self): Prepare some data: - A part to buy - A supplier to buy from - A supplier part - Multiple currency objects - Multi...
e88a8e99a5f0b201c67a95cba097c729f090d5e2
<|skeleton|> class TestCurrencyMigration: """Tests for upgrade from basic currency support to django-money.""" def prepare(self): """Prepare some data: - A part to buy - A supplier to buy from - A supplier part - Multiple currency objects - Multiple supplier price breaks""" <|body_0|> def ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestCurrencyMigration: """Tests for upgrade from basic currency support to django-money.""" def prepare(self): """Prepare some data: - A part to buy - A supplier to buy from - A supplier part - Multiple currency objects - Multiple supplier price breaks""" Part = self.old_state.apps.get_mo...
the_stack_v2_python_sparse
InvenTree/company/test_migrations.py
inventree/InvenTree
train
3,077
58761d0776644488d0157582e30e5b119ac1012f
[ "assert isinstance(response, scrapy.http.response.html.HtmlResponse)\nurls = [response.url]\nparts = str(response.url.split('/')[-1])\nparts = parts.split('.', 1)\ncurboard = parts[0]\nposts_per_page = 25\npagination = response.selector.xpath('//div[contains(@class,\"pagination\")]//span[contains(@class, \"page-dot...
<|body_start_0|> assert isinstance(response, scrapy.http.response.html.HtmlResponse) urls = [response.url] parts = str(response.url.split('/')[-1]) parts = parts.split('.', 1) curboard = parts[0] posts_per_page = 25 pagination = response.selector.xpath('//div[cont...
scrape reports from angling addicts forum
AnglingAddictsReportsSpider
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AnglingAddictsReportsSpider: """scrape reports from angling addicts forum""" def parse(self, response): """generate links to pages in a board yields: 'http://www.anglingaddicts.co.uk/forum/north-west-fishing-reports.html', 'http://www.anglingaddicts.co.uk/forum/north-east-sea-fishing...
stack_v2_sparse_classes_36k_train_007257
10,325
no_license
[ { "docstring": "generate links to pages in a board yields: 'http://www.anglingaddicts.co.uk/forum/north-west-fishing-reports.html', 'http://www.anglingaddicts.co.uk/forum/north-east-sea-fishing-reports.html, ...", "name": "parse", "signature": "def parse(self, response)" }, { "docstring": "respo...
3
null
Implement the Python class `AnglingAddictsReportsSpider` described below. Class description: scrape reports from angling addicts forum Method signatures and docstrings: - def parse(self, response): generate links to pages in a board yields: 'http://www.anglingaddicts.co.uk/forum/north-west-fishing-reports.html', 'htt...
Implement the Python class `AnglingAddictsReportsSpider` described below. Class description: scrape reports from angling addicts forum Method signatures and docstrings: - def parse(self, response): generate links to pages in a board yields: 'http://www.anglingaddicts.co.uk/forum/north-west-fishing-reports.html', 'htt...
9123aa6baf538b662143b9098d963d55165e8409
<|skeleton|> class AnglingAddictsReportsSpider: """scrape reports from angling addicts forum""" def parse(self, response): """generate links to pages in a board yields: 'http://www.anglingaddicts.co.uk/forum/north-west-fishing-reports.html', 'http://www.anglingaddicts.co.uk/forum/north-east-sea-fishing...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AnglingAddictsReportsSpider: """scrape reports from angling addicts forum""" def parse(self, response): """generate links to pages in a board yields: 'http://www.anglingaddicts.co.uk/forum/north-west-fishing-reports.html', 'http://www.anglingaddicts.co.uk/forum/north-east-sea-fishing-reports.html...
the_stack_v2_python_sparse
imgscrape/spiders/angingaddicts_reports.py
gmonkman/python
train
0
624313f0e3b33943686400b1e7eb7481d638f085
[ "private_key = hashlib.sha256(password.encode('utf-8')).digest()\nraw = pad(raw)\niv = 'Random.new().read(AES.block_size)'\ncipher = 'AES.new(private_key, AES.MODE_CBC, iv)'\nreturn base64.b64encode(iv + cipher.encrypt(raw))", "private_key = hashlib.sha256(password.encode('utf-8')).digest()\nenc = base64.b64decod...
<|body_start_0|> private_key = hashlib.sha256(password.encode('utf-8')).digest() raw = pad(raw) iv = 'Random.new().read(AES.block_size)' cipher = 'AES.new(private_key, AES.MODE_CBC, iv)' return base64.b64encode(iv + cipher.encrypt(raw)) <|end_body_0|> <|body_start_1|> pr...
A class used to check errors and validations ... Attributes ---------- BLOCK_SIZE : global a formatted string to print out what the animal says pad : global during registration it helps checking the inserted name errors. unpad : global during userName insertion it helps checking the validity with defined charecters in ...
Security
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Security: """A class used to check errors and validations ... Attributes ---------- BLOCK_SIZE : global a formatted string to print out what the animal says pad : global during registration it helps checking the inserted name errors. unpad : global during userName insertion it helps checking the ...
stack_v2_sparse_classes_36k_train_007258
2,298
no_license
[ { "docstring": "Parameters ---------- raw : str raw password typed by the user password : str encrypted password.", "name": "encrypt", "signature": "def encrypt(self, raw, password)" }, { "docstring": "Parameters ---------- enc : str Encrypted password from the database table password : str Decy...
2
stack_v2_sparse_classes_30k_train_009345
Implement the Python class `Security` described below. Class description: A class used to check errors and validations ... Attributes ---------- BLOCK_SIZE : global a formatted string to print out what the animal says pad : global during registration it helps checking the inserted name errors. unpad : global during us...
Implement the Python class `Security` described below. Class description: A class used to check errors and validations ... Attributes ---------- BLOCK_SIZE : global a formatted string to print out what the animal says pad : global during registration it helps checking the inserted name errors. unpad : global during us...
18d4a9c63c3b42e18c09157ff65391486ecab5bd
<|skeleton|> class Security: """A class used to check errors and validations ... Attributes ---------- BLOCK_SIZE : global a formatted string to print out what the animal says pad : global during registration it helps checking the inserted name errors. unpad : global during userName insertion it helps checking the ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Security: """A class used to check errors and validations ... Attributes ---------- BLOCK_SIZE : global a formatted string to print out what the animal says pad : global during registration it helps checking the inserted name errors. unpad : global during userName insertion it helps checking the validity with...
the_stack_v2_python_sparse
Documentatio/RPiCode/security.py
s3593810/Sensor-Based-Library-Management-System-
train
0
908861e8041f98219707bae4c109dbd85b9208d8
[ "try:\n logging.info('CRUDModelMonitoring create function')\n project = ModelMonitoring(**kwargs)\n with session() as transaction_session:\n transaction_session.add(project)\n transaction_session.commit()\n transaction_session.refresh(project)\nexcept Exception as error:\n logging.e...
<|body_start_0|> try: logging.info('CRUDModelMonitoring create function') project = ModelMonitoring(**kwargs) with session() as transaction_session: transaction_session.add(project) transaction_session.commit() transaction_sessi...
CRUDModelMonitoring
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CRUDModelMonitoring: def create(self, **kwargs): """[CRUD function to create a new Model Monitoring record] Raises: error: [Error returned from the DB layer]""" <|body_0|> def delete(self, model_uri: str): """[CRUD function to delete a Model Monitoring record] Args: ...
stack_v2_sparse_classes_36k_train_007259
3,214
permissive
[ { "docstring": "[CRUD function to create a new Model Monitoring record] Raises: error: [Error returned from the DB layer]", "name": "create", "signature": "def create(self, **kwargs)" }, { "docstring": "[CRUD function to delete a Model Monitoring record] Args: model_uri (str): [Unique identifier...
4
null
Implement the Python class `CRUDModelMonitoring` described below. Class description: Implement the CRUDModelMonitoring class. Method signatures and docstrings: - def create(self, **kwargs): [CRUD function to create a new Model Monitoring record] Raises: error: [Error returned from the DB layer] - def delete(self, mod...
Implement the Python class `CRUDModelMonitoring` described below. Class description: Implement the CRUDModelMonitoring class. Method signatures and docstrings: - def create(self, **kwargs): [CRUD function to create a new Model Monitoring record] Raises: error: [Error returned from the DB layer] - def delete(self, mod...
c71b1324ed270caa3724c0a8c58c4883b28dc19c
<|skeleton|> class CRUDModelMonitoring: def create(self, **kwargs): """[CRUD function to create a new Model Monitoring record] Raises: error: [Error returned from the DB layer]""" <|body_0|> def delete(self, model_uri: str): """[CRUD function to delete a Model Monitoring record] Args: ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CRUDModelMonitoring: def create(self, **kwargs): """[CRUD function to create a new Model Monitoring record] Raises: error: [Error returned from the DB layer]""" try: logging.info('CRUDModelMonitoring create function') project = ModelMonitoring(**kwargs) with...
the_stack_v2_python_sparse
datahub/sql/crud/model_monitoring_crud.py
Chronicles-of-AI/osAIris
train
4
cd2935ecf55deeca49bbe6a2132dc41f6c01eb25
[ "self.matsize = matsize\nself.kernelsize = kernelsize\nself.channels_in = channels_in\nself.channels_out = channels_out\nself.strides = strides\nself.batchsize = batchsize\nself.padding = padding\nself.use_bias = use_bias\nself.precision = precision\nself.activation_fct = activation_fct\nself.opt = optimizer\nself....
<|body_start_0|> self.matsize = matsize self.kernelsize = kernelsize self.channels_in = channels_in self.channels_out = channels_out self.strides = strides self.batchsize = batchsize self.padding = padding self.use_bias = use_bias self.precision = ...
Class for gerenating the benchmark operations
convolution
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class convolution: """Class for gerenating the benchmark operations""" def __init__(self, batchsize, matsize, kernelsize, channels_in, channels_out, strides, precision, padding, activation_fct, use_bias, optimizer, strategy, iterations_warmup, iterations_benchmark, backprop): """Initialize...
stack_v2_sparse_classes_36k_train_007260
3,798
permissive
[ { "docstring": "Initialize convolution Args: args: Input arguments", "name": "__init__", "signature": "def __init__(self, batchsize, matsize, kernelsize, channels_in, channels_out, strides, precision, padding, activation_fct, use_bias, optimizer, strategy, iterations_warmup, iterations_benchmark, backpr...
2
stack_v2_sparse_classes_30k_train_007971
Implement the Python class `convolution` described below. Class description: Class for gerenating the benchmark operations Method signatures and docstrings: - def __init__(self, batchsize, matsize, kernelsize, channels_in, channels_out, strides, precision, padding, activation_fct, use_bias, optimizer, strategy, itera...
Implement the Python class `convolution` described below. Class description: Class for gerenating the benchmark operations Method signatures and docstrings: - def __init__(self, batchsize, matsize, kernelsize, channels_in, channels_out, strides, precision, padding, activation_fct, use_bias, optimizer, strategy, itera...
c177ed3b01b3849de2d0266a3dd673c47bd754f8
<|skeleton|> class convolution: """Class for gerenating the benchmark operations""" def __init__(self, batchsize, matsize, kernelsize, channels_in, channels_out, strides, precision, padding, activation_fct, use_bias, optimizer, strategy, iterations_warmup, iterations_benchmark, backprop): """Initialize...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class convolution: """Class for gerenating the benchmark operations""" def __init__(self, batchsize, matsize, kernelsize, channels_in, channels_out, strides, precision, padding, activation_fct, use_bias, optimizer, strategy, iterations_warmup, iterations_benchmark, backprop): """Initialize convolution ...
the_stack_v2_python_sparse
prediction_model_tf2/Generate_train_data/benchmark_conv_ms.py
profnote/ml-performance-prediction
train
0
7fd83ee6c3e489d73a224e09e00cd92c0be79640
[ "if Articles.objects.filter(slug=article_slug).exists():\n comment = request.data.get('comment', {})\n article = Articles.objects.filter(slug=article_slug).first()\n comment.update({'article': article})\n serializer = self.serializer_class(data=comment)\n serializer.is_valid(raise_exception=True)\n ...
<|body_start_0|> if Articles.objects.filter(slug=article_slug).exists(): comment = request.data.get('comment', {}) article = Articles.objects.filter(slug=article_slug).first() comment.update({'article': article}) serializer = self.serializer_class(data=comment) ...
Endpoint for creating a comments
CreateCommentView
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CreateCommentView: """Endpoint for creating a comments""" def post(self, request, article_slug): """Handles all post requests to create a comment""" <|body_0|> def get(self, request, article_slug): """Handles all get requests by users to view the comments of a pa...
stack_v2_sparse_classes_36k_train_007261
8,741
permissive
[ { "docstring": "Handles all post requests to create a comment", "name": "post", "signature": "def post(self, request, article_slug)" }, { "docstring": "Handles all get requests by users to view the comments of a particular article", "name": "get", "signature": "def get(self, request, art...
2
stack_v2_sparse_classes_30k_train_002396
Implement the Python class `CreateCommentView` described below. Class description: Endpoint for creating a comments Method signatures and docstrings: - def post(self, request, article_slug): Handles all post requests to create a comment - def get(self, request, article_slug): Handles all get requests by users to view...
Implement the Python class `CreateCommentView` described below. Class description: Endpoint for creating a comments Method signatures and docstrings: - def post(self, request, article_slug): Handles all post requests to create a comment - def get(self, request, article_slug): Handles all get requests by users to view...
ff4f1ba34d074e68e49f7896848f81b729542e1f
<|skeleton|> class CreateCommentView: """Endpoint for creating a comments""" def post(self, request, article_slug): """Handles all post requests to create a comment""" <|body_0|> def get(self, request, article_slug): """Handles all get requests by users to view the comments of a pa...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CreateCommentView: """Endpoint for creating a comments""" def post(self, request, article_slug): """Handles all post requests to create a comment""" if Articles.objects.filter(slug=article_slug).exists(): comment = request.data.get('comment', {}) article = Articles...
the_stack_v2_python_sparse
authors/apps/comments/views.py
rfpremier/ah-django
train
0
f77e4a6a531897333011cdc2b314447b56386524
[ "with tempfile.TemporaryDirectory() as tmp_dir:\n out, err, err_code = utils.execute(['ls', '.'], location=tmp_dir, check_result=False)\n self.assertEqual(err_code, 0)\n self.assertEqual(err, '')\n self.assertEqual(out, '')\n out, err, err_code = utils.execute(['mkdir', 'tmp'], location=tmp_dir, chec...
<|body_start_0|> with tempfile.TemporaryDirectory() as tmp_dir: out, err, err_code = utils.execute(['ls', '.'], location=tmp_dir, check_result=False) self.assertEqual(err_code, 0) self.assertEqual(err, '') self.assertEqual(out, '') out, err, err_code =...
Tests the execute function.
ExecuteTest
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ExecuteTest: """Tests the execute function.""" def test_valid_command(self): """Tests that execute can produce valid output.""" <|body_0|> def test_error_command(self): """Tests that execute can correctly surface errors.""" <|body_1|> <|end_skeleton|> <...
stack_v2_sparse_classes_36k_train_007262
5,775
permissive
[ { "docstring": "Tests that execute can produce valid output.", "name": "test_valid_command", "signature": "def test_valid_command(self)" }, { "docstring": "Tests that execute can correctly surface errors.", "name": "test_error_command", "signature": "def test_error_command(self)" } ]
2
stack_v2_sparse_classes_30k_train_013751
Implement the Python class `ExecuteTest` described below. Class description: Tests the execute function. Method signatures and docstrings: - def test_valid_command(self): Tests that execute can produce valid output. - def test_error_command(self): Tests that execute can correctly surface errors.
Implement the Python class `ExecuteTest` described below. Class description: Tests the execute function. Method signatures and docstrings: - def test_valid_command(self): Tests that execute can produce valid output. - def test_error_command(self): Tests that execute can correctly surface errors. <|skeleton|> class E...
f0275421f84b8f80ee767fb9230134ac97cb687b
<|skeleton|> class ExecuteTest: """Tests the execute function.""" def test_valid_command(self): """Tests that execute can produce valid output.""" <|body_0|> def test_error_command(self): """Tests that execute can correctly surface errors.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ExecuteTest: """Tests the execute function.""" def test_valid_command(self): """Tests that execute can produce valid output.""" with tempfile.TemporaryDirectory() as tmp_dir: out, err, err_code = utils.execute(['ls', '.'], location=tmp_dir, check_result=False) self...
the_stack_v2_python_sparse
infra/utils_test.py
google/oss-fuzz
train
9,438
3b953875149dd9710aca7dac868373a618172a95
[ "self.bounds = (min(x), max(x))\nself.fill_value = fill_value\nsuper(ExtrapolatingUnivariateSpline, self).__init__(x, y, w=w, bbox=bbox, k=k, ext=ext)", "x = np.atleast_1d(x)\nretval = super(ExtrapolatingUnivariateSpline, self).__call__(x, nu=nu, ext=ext)\nidx = ~((x > self.bounds[0]) & (x < self.bounds[1]))\nret...
<|body_start_0|> self.bounds = (min(x), max(x)) self.fill_value = fill_value super(ExtrapolatingUnivariateSpline, self).__init__(x, y, w=w, bbox=bbox, k=k, ext=ext) <|end_body_0|> <|body_start_1|> x = np.atleast_1d(x) retval = super(ExtrapolatingUnivariateSpline, self).__call__(...
Does the same thing as InterpolatedUnivariateSpline, but keeps track of if it is extrapolating. When extrapolating, this will just return the fill value which defaults to NaN.
ExtrapolatingUnivariateSpline
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ExtrapolatingUnivariateSpline: """Does the same thing as InterpolatedUnivariateSpline, but keeps track of if it is extrapolating. When extrapolating, this will just return the fill value which defaults to NaN.""" def __init__(self, x, y, w=None, bbox=[None] * 2, k=3, ext=0, fill_value=np.nan...
stack_v2_sparse_classes_36k_train_007263
47,749
permissive
[ { "docstring": "See docstring for InterpolatedUnivariateSpline.", "name": "__init__", "signature": "def __init__(self, x, y, w=None, bbox=[None] * 2, k=3, ext=0, fill_value=np.nan)" }, { "docstring": "See docstring for InterpolatedUnivariateSpline.__call__", "name": "__call__", "signatur...
2
stack_v2_sparse_classes_30k_train_021114
Implement the Python class `ExtrapolatingUnivariateSpline` described below. Class description: Does the same thing as InterpolatedUnivariateSpline, but keeps track of if it is extrapolating. When extrapolating, this will just return the fill value which defaults to NaN. Method signatures and docstrings: - def __init_...
Implement the Python class `ExtrapolatingUnivariateSpline` described below. Class description: Does the same thing as InterpolatedUnivariateSpline, but keeps track of if it is extrapolating. When extrapolating, this will just return the fill value which defaults to NaN. Method signatures and docstrings: - def __init_...
8a9f00a6977dad8d4477eef1d664fd62e9ecab75
<|skeleton|> class ExtrapolatingUnivariateSpline: """Does the same thing as InterpolatedUnivariateSpline, but keeps track of if it is extrapolating. When extrapolating, this will just return the fill value which defaults to NaN.""" def __init__(self, x, y, w=None, bbox=[None] * 2, k=3, ext=0, fill_value=np.nan...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ExtrapolatingUnivariateSpline: """Does the same thing as InterpolatedUnivariateSpline, but keeps track of if it is extrapolating. When extrapolating, this will just return the fill value which defaults to NaN.""" def __init__(self, x, y, w=None, bbox=[None] * 2, k=3, ext=0, fill_value=np.nan): ""...
the_stack_v2_python_sparse
kglib/utils/HelperFunctions.py
kgullikson88/gullikson-scripts
train
4
fee9287da7ef73399f37dc6f49a1959111963d34
[ "try:\n with open(model_path, 'rb') as fo:\n self.model = joblib.load(fo)\nexcept:\n raise FileNotFoundError('There is no file in that path')\n warnings.warn('There is no file in that path, So model will be create according to default value')\n self.model = RandomForestClassifier(n_estimators=50,...
<|body_start_0|> try: with open(model_path, 'rb') as fo: self.model = joblib.load(fo) except: raise FileNotFoundError('There is no file in that path') warnings.warn('There is no file in that path, So model will be create according to default value') ...
PaZum
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PaZum: def __init__(self, model_path): """Parameter model_path : Path to saved model Example : 'C:\\Users\\cha45\\PycharmProjects\\AluxandraDrinTheDodge\\module\\Random_Forest_best_run.sav'""" <|body_0|> def predict(self, input, out='prob'): """Parameter input : list...
stack_v2_sparse_classes_36k_train_007264
3,050
no_license
[ { "docstring": "Parameter model_path : Path to saved model Example : 'C:\\\\Users\\\\cha45\\\\PycharmProjects\\\\AluxandraDrinTheDodge\\\\module\\\\Random_Forest_best_run.sav'", "name": "__init__", "signature": "def __init__(self, model_path)" }, { "docstring": "Parameter input : list of imageFe...
2
stack_v2_sparse_classes_30k_train_017505
Implement the Python class `PaZum` described below. Class description: Implement the PaZum class. Method signatures and docstrings: - def __init__(self, model_path): Parameter model_path : Path to saved model Example : 'C:\\Users\\cha45\\PycharmProjects\\AluxandraDrinTheDodge\\module\\Random_Forest_best_run.sav' - de...
Implement the Python class `PaZum` described below. Class description: Implement the PaZum class. Method signatures and docstrings: - def __init__(self, model_path): Parameter model_path : Path to saved model Example : 'C:\\Users\\cha45\\PycharmProjects\\AluxandraDrinTheDodge\\module\\Random_Forest_best_run.sav' - de...
15b1272db5c88be6d39d1d33694c20e75e4863d2
<|skeleton|> class PaZum: def __init__(self, model_path): """Parameter model_path : Path to saved model Example : 'C:\\Users\\cha45\\PycharmProjects\\AluxandraDrinTheDodge\\module\\Random_Forest_best_run.sav'""" <|body_0|> def predict(self, input, out='prob'): """Parameter input : list...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PaZum: def __init__(self, model_path): """Parameter model_path : Path to saved model Example : 'C:\\Users\\cha45\\PycharmProjects\\AluxandraDrinTheDodge\\module\\Random_Forest_best_run.sav'""" try: with open(model_path, 'rb') as fo: self.model = joblib.load(fo) ...
the_stack_v2_python_sparse
module/PaZum.py
Arthicha/AluxandraDrinTheDodge
train
2
5821076a103befe2a060e9d1e26b59ce44188ccd
[ "log = MissionClockEvent(user=self.user1, team_on_clock=True, team_on_timeout=False)\nlog.save()\nself.assertIsNotNone(log.__unicode__())", "log = MissionClockEvent(user=self.user1, team_on_clock=False, team_on_timeout=False)\nlog.save()\nlog = MissionClockEvent(user=self.user2, team_on_clock=True, team_on_timeou...
<|body_start_0|> log = MissionClockEvent(user=self.user1, team_on_clock=True, team_on_timeout=False) log.save() self.assertIsNotNone(log.__unicode__()) <|end_body_0|> <|body_start_1|> log = MissionClockEvent(user=self.user1, team_on_clock=False, team_on_timeout=False) log.save()...
Tests the MissionClockEvent model.
TestMissionClockEventModel
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestMissionClockEventModel: """Tests the MissionClockEvent model.""" def test_unicode(self): """Tests the unicode method executes.""" <|body_0|> def test_user_on_clock(self): """Tests the user_on_clock method.""" <|body_1|> def test_user_on_timeout(s...
stack_v2_sparse_classes_36k_train_007265
3,380
permissive
[ { "docstring": "Tests the unicode method executes.", "name": "test_unicode", "signature": "def test_unicode(self)" }, { "docstring": "Tests the user_on_clock method.", "name": "test_user_on_clock", "signature": "def test_user_on_clock(self)" }, { "docstring": "Tests the user_on_t...
4
stack_v2_sparse_classes_30k_train_003762
Implement the Python class `TestMissionClockEventModel` described below. Class description: Tests the MissionClockEvent model. Method signatures and docstrings: - def test_unicode(self): Tests the unicode method executes. - def test_user_on_clock(self): Tests the user_on_clock method. - def test_user_on_timeout(self)...
Implement the Python class `TestMissionClockEventModel` described below. Class description: Tests the MissionClockEvent model. Method signatures and docstrings: - def test_unicode(self): Tests the unicode method executes. - def test_user_on_clock(self): Tests the user_on_clock method. - def test_user_on_timeout(self)...
509f36562fc895433fcd01da755a35dd04581025
<|skeleton|> class TestMissionClockEventModel: """Tests the MissionClockEvent model.""" def test_unicode(self): """Tests the unicode method executes.""" <|body_0|> def test_user_on_clock(self): """Tests the user_on_clock method.""" <|body_1|> def test_user_on_timeout(s...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestMissionClockEventModel: """Tests the MissionClockEvent model.""" def test_unicode(self): """Tests the unicode method executes.""" log = MissionClockEvent(user=self.user1, team_on_clock=True, team_on_timeout=False) log.save() self.assertIsNotNone(log.__unicode__()) ...
the_stack_v2_python_sparse
server/auvsi_suas/models/mission_clock_event_test.py
matcheydj/interop
train
1
99ca3583a8826d6aba548d8085265594e7991784
[ "if self.dialog is None:\n self.dialog = MemoryViewerDialog()\nreturn self.dialog.Open(dlgtype=c4d.DLG_TYPE_ASYNC, pluginid=PLUGIN_ID, defaulth=400, defaultw=400)", "if self.dialog is None:\n self.dialog = MemoryViewerDialog()\nreturn self.dialog.Restore(pluginid=PLUGIN_ID, secret=sec_ref)" ]
<|body_start_0|> if self.dialog is None: self.dialog = MemoryViewerDialog() return self.dialog.Open(dlgtype=c4d.DLG_TYPE_ASYNC, pluginid=PLUGIN_ID, defaulth=400, defaultw=400) <|end_body_0|> <|body_start_1|> if self.dialog is None: self.dialog = MemoryViewerDialog() ...
Command Data class that holds the MemoryViewerDialog instance.
MemoryViewerCommandData
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MemoryViewerCommandData: """Command Data class that holds the MemoryViewerDialog instance.""" def Execute(self, doc): """Called when the user Execute the command (CallCommand or a clicks on the Command from the plugin menu). Args: doc (c4d.documents.BaseDocument): the current active ...
stack_v2_sparse_classes_36k_train_007266
8,722
permissive
[ { "docstring": "Called when the user Execute the command (CallCommand or a clicks on the Command from the plugin menu). Args: doc (c4d.documents.BaseDocument): the current active document Returns: True if the command success", "name": "Execute", "signature": "def Execute(self, doc)" }, { "docstr...
2
stack_v2_sparse_classes_30k_train_001357
Implement the Python class `MemoryViewerCommandData` described below. Class description: Command Data class that holds the MemoryViewerDialog instance. Method signatures and docstrings: - def Execute(self, doc): Called when the user Execute the command (CallCommand or a clicks on the Command from the plugin menu). Ar...
Implement the Python class `MemoryViewerCommandData` described below. Class description: Command Data class that holds the MemoryViewerDialog instance. Method signatures and docstrings: - def Execute(self, doc): Called when the user Execute the command (CallCommand or a clicks on the Command from the plugin menu). Ar...
b1ea3fce533df34094bc3d0bd6460dfb84306e53
<|skeleton|> class MemoryViewerCommandData: """Command Data class that holds the MemoryViewerDialog instance.""" def Execute(self, doc): """Called when the user Execute the command (CallCommand or a clicks on the Command from the plugin menu). Args: doc (c4d.documents.BaseDocument): the current active ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MemoryViewerCommandData: """Command Data class that holds the MemoryViewerDialog instance.""" def Execute(self, doc): """Called when the user Execute the command (CallCommand or a clicks on the Command from the plugin menu). Args: doc (c4d.documents.BaseDocument): the current active document Retu...
the_stack_v2_python_sparse
plugins/py-memory_viewer_r12/py-memory_viewer_r12.pyp
PluginCafe/cinema4d_py_sdk_extended
train
112
7de46aae64796e99be5037595473ee1ff78b9851
[ "filter_properties = kwargs.get('filter_properties', {})\nignore_hosts = filter_properties.get('ignore_hosts', [])\nhosts = [host for host in hosts if host not in ignore_hosts]\nreturn hosts", "elevated = context.elevated()\nhosts = self.hosts_up(elevated, topic)\nif not hosts:\n msg = _('Is the appropriate se...
<|body_start_0|> filter_properties = kwargs.get('filter_properties', {}) ignore_hosts = filter_properties.get('ignore_hosts', []) hosts = [host for host in hosts if host not in ignore_hosts] return hosts <|end_body_0|> <|body_start_1|> elevated = context.elevated() hosts...
Implements Scheduler as a random node selector.
ChanceScheduler
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ChanceScheduler: """Implements Scheduler as a random node selector.""" def _filter_hosts(self, request_spec, hosts, **kwargs): """Filter a list of hosts based on request_spec.""" <|body_0|> def _schedule(self, context, topic, request_spec, **kwargs): """Picks a h...
stack_v2_sparse_classes_36k_train_007267
2,669
permissive
[ { "docstring": "Filter a list of hosts based on request_spec.", "name": "_filter_hosts", "signature": "def _filter_hosts(self, request_spec, hosts, **kwargs)" }, { "docstring": "Picks a host that is up at random.", "name": "_schedule", "signature": "def _schedule(self, context, topic, re...
3
null
Implement the Python class `ChanceScheduler` described below. Class description: Implements Scheduler as a random node selector. Method signatures and docstrings: - def _filter_hosts(self, request_spec, hosts, **kwargs): Filter a list of hosts based on request_spec. - def _schedule(self, context, topic, request_spec,...
Implement the Python class `ChanceScheduler` described below. Class description: Implements Scheduler as a random node selector. Method signatures and docstrings: - def _filter_hosts(self, request_spec, hosts, **kwargs): Filter a list of hosts based on request_spec. - def _schedule(self, context, topic, request_spec,...
a93a844398a11a8a85f204782fb9456f7caccdbe
<|skeleton|> class ChanceScheduler: """Implements Scheduler as a random node selector.""" def _filter_hosts(self, request_spec, hosts, **kwargs): """Filter a list of hosts based on request_spec.""" <|body_0|> def _schedule(self, context, topic, request_spec, **kwargs): """Picks a h...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ChanceScheduler: """Implements Scheduler as a random node selector.""" def _filter_hosts(self, request_spec, hosts, **kwargs): """Filter a list of hosts based on request_spec.""" filter_properties = kwargs.get('filter_properties', {}) ignore_hosts = filter_properties.get('ignore_h...
the_stack_v2_python_sparse
manila/scheduler/drivers/chance.py
openstack/manila
train
178
bf80c67801d65eb072bc9a9a283bc117404d692b
[ "super().__init__(index)\nself.serial = communicator\nself.hex_id = Util.int_to_hex_string(index * 7)\nself.next_color = None\nself.next_text = None", "del flashing\ndel flash_mask\ncolors = text.get_colors()\nself.next_text = text\nif colors:\n self._set_color(colors)", "if len(colors) == 1:\n self.next_...
<|body_start_0|> super().__init__(index) self.serial = communicator self.hex_id = Util.int_to_hex_string(index * 7) self.next_color = None self.next_text = None <|end_body_0|> <|body_start_1|> del flashing del flash_mask colors = text.get_colors() ...
FAST segment display.
FASTSegmentDisplay
[ "MIT", "CC-BY-4.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FASTSegmentDisplay: """FAST segment display.""" def __init__(self, index, communicator): """Initialise alpha numeric display.""" <|body_0|> def set_text(self, text: ColoredSegmentDisplayText, flashing: FlashingType, flash_mask: str) -> None: """Set digits to disp...
stack_v2_sparse_classes_36k_train_007268
1,467
permissive
[ { "docstring": "Initialise alpha numeric display.", "name": "__init__", "signature": "def __init__(self, index, communicator)" }, { "docstring": "Set digits to display.", "name": "set_text", "signature": "def set_text(self, text: ColoredSegmentDisplayText, flashing: FlashingType, flash_m...
3
null
Implement the Python class `FASTSegmentDisplay` described below. Class description: FAST segment display. Method signatures and docstrings: - def __init__(self, index, communicator): Initialise alpha numeric display. - def set_text(self, text: ColoredSegmentDisplayText, flashing: FlashingType, flash_mask: str) -> Non...
Implement the Python class `FASTSegmentDisplay` described below. Class description: FAST segment display. Method signatures and docstrings: - def __init__(self, index, communicator): Initialise alpha numeric display. - def set_text(self, text: ColoredSegmentDisplayText, flashing: FlashingType, flash_mask: str) -> Non...
9f90c8b1586363b65340017bfa3af5d56d32c6d9
<|skeleton|> class FASTSegmentDisplay: """FAST segment display.""" def __init__(self, index, communicator): """Initialise alpha numeric display.""" <|body_0|> def set_text(self, text: ColoredSegmentDisplayText, flashing: FlashingType, flash_mask: str) -> None: """Set digits to disp...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FASTSegmentDisplay: """FAST segment display.""" def __init__(self, index, communicator): """Initialise alpha numeric display.""" super().__init__(index) self.serial = communicator self.hex_id = Util.int_to_hex_string(index * 7) self.next_color = None self.n...
the_stack_v2_python_sparse
mpf/platforms/fast/fast_segment_display.py
missionpinball/mpf
train
191
622e1248440d72833923b678b0dfeccec6ec1093
[ "super().__init__(name=name, id=id, classes=classes, disabled=disabled)\nself._start_time = None\nself._percentage = None", "if percentage is not None:\n self.auto_refresh = None\nelse:\n self.auto_refresh = 1 / 15", "if self._percentage is None:\n return self.render_indeterminate()\nelse:\n bar_sty...
<|body_start_0|> super().__init__(name=name, id=id, classes=classes, disabled=disabled) self._start_time = None self._percentage = None <|end_body_0|> <|body_start_1|> if percentage is not None: self.auto_refresh = None else: self.auto_refresh = 1 / 15 <|...
The bar portion of the progress bar.
Bar
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Bar: """The bar portion of the progress bar.""" def __init__(self, name: str | None=None, id: str | None=None, classes: str | None=None, disabled: bool=False): """Create a bar for a [`ProgressBar`][textual.widgets.ProgressBar].""" <|body_0|> def watch__percentage(self, p...
stack_v2_sparse_classes_36k_train_007269
15,215
permissive
[ { "docstring": "Create a bar for a [`ProgressBar`][textual.widgets.ProgressBar].", "name": "__init__", "signature": "def __init__(self, name: str | None=None, id: str | None=None, classes: str | None=None, disabled: bool=False)" }, { "docstring": "Manage the timer that enables the indeterminate ...
5
null
Implement the Python class `Bar` described below. Class description: The bar portion of the progress bar. Method signatures and docstrings: - def __init__(self, name: str | None=None, id: str | None=None, classes: str | None=None, disabled: bool=False): Create a bar for a [`ProgressBar`][textual.widgets.ProgressBar]....
Implement the Python class `Bar` described below. Class description: The bar portion of the progress bar. Method signatures and docstrings: - def __init__(self, name: str | None=None, id: str | None=None, classes: str | None=None, disabled: bool=False): Create a bar for a [`ProgressBar`][textual.widgets.ProgressBar]....
b74ac1e47fdd16133ca567390c99ea19de278c5a
<|skeleton|> class Bar: """The bar portion of the progress bar.""" def __init__(self, name: str | None=None, id: str | None=None, classes: str | None=None, disabled: bool=False): """Create a bar for a [`ProgressBar`][textual.widgets.ProgressBar].""" <|body_0|> def watch__percentage(self, p...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Bar: """The bar portion of the progress bar.""" def __init__(self, name: str | None=None, id: str | None=None, classes: str | None=None, disabled: bool=False): """Create a bar for a [`ProgressBar`][textual.widgets.ProgressBar].""" super().__init__(name=name, id=id, classes=classes, disabl...
the_stack_v2_python_sparse
src/textual/widgets/_progress_bar.py
Textualize/textual
train
14,818
378c845527ed1579e91c7197270a543a223c26a0
[ "data = np.ones((16, 16), dtype=np.float32)\nself.cube = set_up_variable_cube(data, 'precipitation_amount', 'kg m^-2', grid_spacing=1, domain_corner=(49, -8))\nself.cube_360 = set_up_variable_cube(data, 'precipitation_amount', 'kg m^-2', grid_spacing=1, domain_corner=(49, 345))\nself.spot_cube = create_spot_cube(xr...
<|body_start_0|> data = np.ones((16, 16), dtype=np.float32) self.cube = set_up_variable_cube(data, 'precipitation_amount', 'kg m^-2', grid_spacing=1, domain_corner=(49, -8)) self.cube_360 = set_up_variable_cube(data, 'precipitation_amount', 'kg m^-2', grid_spacing=1, domain_corner=(49, 345)) ...
Test string representation
Test__daynight_lat_lon_cube
[ "BSD-3-Clause", "LicenseRef-scancode-proprietary-license" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Test__daynight_lat_lon_cube: """Test string representation""" def setUp(self): """Set up the cube for testing.""" <|body_0|> def test_basic_lat_lon_cube_gridded(self): """Test this create a blank gridded mask cube""" <|body_1|> def test_basic_lat_lon...
stack_v2_sparse_classes_36k_train_007270
18,065
permissive
[ { "docstring": "Set up the cube for testing.", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "Test this create a blank gridded mask cube", "name": "test_basic_lat_lon_cube_gridded", "signature": "def test_basic_lat_lon_cube_gridded(self)" }, { "docstring": "Te...
4
stack_v2_sparse_classes_30k_train_005869
Implement the Python class `Test__daynight_lat_lon_cube` described below. Class description: Test string representation Method signatures and docstrings: - def setUp(self): Set up the cube for testing. - def test_basic_lat_lon_cube_gridded(self): Test this create a blank gridded mask cube - def test_basic_lat_lon_cub...
Implement the Python class `Test__daynight_lat_lon_cube` described below. Class description: Test string representation Method signatures and docstrings: - def setUp(self): Set up the cube for testing. - def test_basic_lat_lon_cube_gridded(self): Test this create a blank gridded mask cube - def test_basic_lat_lon_cub...
cd2c9019944345df1e703bf8f625db537ad9f559
<|skeleton|> class Test__daynight_lat_lon_cube: """Test string representation""" def setUp(self): """Set up the cube for testing.""" <|body_0|> def test_basic_lat_lon_cube_gridded(self): """Test this create a blank gridded mask cube""" <|body_1|> def test_basic_lat_lon...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Test__daynight_lat_lon_cube: """Test string representation""" def setUp(self): """Set up the cube for testing.""" data = np.ones((16, 16), dtype=np.float32) self.cube = set_up_variable_cube(data, 'precipitation_amount', 'kg m^-2', grid_spacing=1, domain_corner=(49, -8)) se...
the_stack_v2_python_sparse
improver_tests/utilities/solar/test_DayNightMask.py
metoppv/improver
train
101
00d9d2e9530a85fe985c60606acdd07f09fbd299
[ "self._feature_importances = np.zeros(n_features)\nself._n_trees = 0\nsuper().__init__(probabilities, n_features, alpha)", "self._feature_importances += new_tree.feature_importances()\nself._n_trees += 1\nself._probabilities = self._probabilities * (1 - self._feature_importances / self._n_trees * self._alpha * ra...
<|body_start_0|> self._feature_importances = np.zeros(n_features) self._n_trees = 0 super().__init__(probabilities, n_features, alpha) <|end_body_0|> <|body_start_1|> self._feature_importances += new_tree.feature_importances() self._n_trees += 1 self._probabilities = sel...
FIProbabilityLedger
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FIProbabilityLedger: def __init__(self, probabilities, n_features, alpha=0.1): """Creates a probabilities ledger which updates the probabilities according to the feature importances. param probabilities: <list> Feature probabilities :param n_features: <int> Amount of features :param alph...
stack_v2_sparse_classes_36k_train_007271
2,893
no_license
[ { "docstring": "Creates a probabilities ledger which updates the probabilities according to the feature importances. param probabilities: <list> Feature probabilities :param n_features: <int> Amount of features :param alpha: <float> Diversity rate", "name": "__init__", "signature": "def __init__(self, p...
2
stack_v2_sparse_classes_30k_train_012734
Implement the Python class `FIProbabilityLedger` described below. Class description: Implement the FIProbabilityLedger class. Method signatures and docstrings: - def __init__(self, probabilities, n_features, alpha=0.1): Creates a probabilities ledger which updates the probabilities according to the feature importance...
Implement the Python class `FIProbabilityLedger` described below. Class description: Implement the FIProbabilityLedger class. Method signatures and docstrings: - def __init__(self, probabilities, n_features, alpha=0.1): Creates a probabilities ledger which updates the probabilities according to the feature importance...
711e5b4c2e68a023bc965b0ee12feab330de3f32
<|skeleton|> class FIProbabilityLedger: def __init__(self, probabilities, n_features, alpha=0.1): """Creates a probabilities ledger which updates the probabilities according to the feature importances. param probabilities: <list> Feature probabilities :param n_features: <int> Amount of features :param alph...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FIProbabilityLedger: def __init__(self, probabilities, n_features, alpha=0.1): """Creates a probabilities ledger which updates the probabilities according to the feature importances. param probabilities: <list> Feature probabilities :param n_features: <int> Amount of features :param alpha: <float> Div...
the_stack_v2_python_sparse
proactive_forest/probabilites.py
ladm2110/proactive_forest
train
3
d8ae635b592b801dc732021b6ed135a52222c194
[ "self.blob_detector = BlobDetector(min_area, max_area)\nself.connected_components_detector = ConnectedComponentsDetector()\nself.color_converter = ColorConverter()", "grayscale_image = self.color_converter.convert_to_grayscale(image, color_encoding)\nbinary_image = self.color_converter.convert_to_binary(grayscale...
<|body_start_0|> self.blob_detector = BlobDetector(min_area, max_area) self.connected_components_detector = ConnectedComponentsDetector() self.color_converter = ColorConverter() <|end_body_0|> <|body_start_1|> grayscale_image = self.color_converter.convert_to_grayscale(image, color_enco...
Class responsible for detecting diodes locations. Intended for internal usage.
DiodeDetector
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DiodeDetector: """Class responsible for detecting diodes locations. Intended for internal usage.""" def __init__(self, min_area=1, max_area=None): """Parameters ---------- min_area : int, optional Smallest area of blob to count as diode. Default = 1. max_area : int, optional Biggest ...
stack_v2_sparse_classes_36k_train_007272
2,495
permissive
[ { "docstring": "Parameters ---------- min_area : int, optional Smallest area of blob to count as diode. Default = 1. max_area : int, optional Biggest area of blob to count as diode. Default is None.", "name": "__init__", "signature": "def __init__(self, min_area=1, max_area=None)" }, { "docstrin...
2
stack_v2_sparse_classes_30k_train_012237
Implement the Python class `DiodeDetector` described below. Class description: Class responsible for detecting diodes locations. Intended for internal usage. Method signatures and docstrings: - def __init__(self, min_area=1, max_area=None): Parameters ---------- min_area : int, optional Smallest area of blob to count...
Implement the Python class `DiodeDetector` described below. Class description: Class responsible for detecting diodes locations. Intended for internal usage. Method signatures and docstrings: - def __init__(self, min_area=1, max_area=None): Parameters ---------- min_area : int, optional Smallest area of blob to count...
81820b35dab10b14f58d66079b0a8f82ef819bee
<|skeleton|> class DiodeDetector: """Class responsible for detecting diodes locations. Intended for internal usage.""" def __init__(self, min_area=1, max_area=None): """Parameters ---------- min_area : int, optional Smallest area of blob to count as diode. Default = 1. max_area : int, optional Biggest ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DiodeDetector: """Class responsible for detecting diodes locations. Intended for internal usage.""" def __init__(self, min_area=1, max_area=None): """Parameters ---------- min_area : int, optional Smallest area of blob to count as diode. Default = 1. max_area : int, optional Biggest area of blob ...
the_stack_v2_python_sparse
mrc/localization/camera/utils/diode_detector.py
Lukasz1928/mobile-robots-control
train
2
121adaea153c0a10c632459cf8954f201794ceac
[ "self._signal = signal\nself._obj = obj\nself._obj_class = obj_class\nself._connected_slots = []", "try:\n kwargs.pop('sender')\nexcept KeyError:\n pass\nfor slot in self._connected_slots:\n if 'sender' in inspect.signature(slot).parameters:\n slot(*args, sender=self._obj, **kwargs)\n else:\n ...
<|body_start_0|> self._signal = signal self._obj = obj self._obj_class = obj_class self._connected_slots = [] <|end_body_0|> <|body_start_1|> try: kwargs.pop('sender') except KeyError: pass for slot in self._connected_slots: if...
SignalDispatcher
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SignalDispatcher: def __init__(self, signal, obj, obj_class): """Initialises the Signal Dispatcher. Signal calls this.""" <|body_0|> def emit(self, *args, **kwargs): """Notifies all registered targets by calling them with the passed arguments. Args: *args: any **kwar...
stack_v2_sparse_classes_36k_train_007273
2,710
no_license
[ { "docstring": "Initialises the Signal Dispatcher. Signal calls this.", "name": "__init__", "signature": "def __init__(self, signal, obj, obj_class)" }, { "docstring": "Notifies all registered targets by calling them with the passed arguments. Args: *args: any **kwargs: any Passed to the targets...
4
stack_v2_sparse_classes_30k_train_009223
Implement the Python class `SignalDispatcher` described below. Class description: Implement the SignalDispatcher class. Method signatures and docstrings: - def __init__(self, signal, obj, obj_class): Initialises the Signal Dispatcher. Signal calls this. - def emit(self, *args, **kwargs): Notifies all registered targe...
Implement the Python class `SignalDispatcher` described below. Class description: Implement the SignalDispatcher class. Method signatures and docstrings: - def __init__(self, signal, obj, obj_class): Initialises the Signal Dispatcher. Signal calls this. - def emit(self, *args, **kwargs): Notifies all registered targe...
5b8d5a3d61769b4522f40854eaa5f5b9de6cf112
<|skeleton|> class SignalDispatcher: def __init__(self, signal, obj, obj_class): """Initialises the Signal Dispatcher. Signal calls this.""" <|body_0|> def emit(self, *args, **kwargs): """Notifies all registered targets by calling them with the passed arguments. Args: *args: any **kwar...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SignalDispatcher: def __init__(self, signal, obj, obj_class): """Initialises the Signal Dispatcher. Signal calls this.""" self._signal = signal self._obj = obj self._obj_class = obj_class self._connected_slots = [] def emit(self, *args, **kwargs): """Notifi...
the_stack_v2_python_sparse
vaitk/core/signal.py
stefanoborini/vaitk
train
3
143c8b8581b31f024b472ad9bb6ae7f3d8cf07bf
[ "evaluator = SemanticSimilarity(2, 'FREQ')\noutput = evaluator.dist_to_string(self.test_word_pairs)\nself.assertCountEqual(output.strip().split('\\n'), self.expected_similarities)", "evaluator = SemanticSimilarity(2, 'PMI')\noutput = evaluator.dist_to_string(self.test_word_pairs)\nself.assertCountEqual(output.str...
<|body_start_0|> evaluator = SemanticSimilarity(2, 'FREQ') output = evaluator.dist_to_string(self.test_word_pairs) self.assertCountEqual(output.strip().split('\n'), self.expected_similarities) <|end_body_0|> <|body_start_1|> evaluator = SemanticSimilarity(2, 'PMI') output = eval...
This class contains tests for the SemanticSimilarity class
TestSemanticSimilarity
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestSemanticSimilarity: """This class contains tests for the SemanticSimilarity class""" def test_freq(self): """Test frequency distribution :return: void""" <|body_0|> def test_pmi(self): """Test point-wise mutual information distribution :return: void""" ...
stack_v2_sparse_classes_36k_train_007274
7,621
no_license
[ { "docstring": "Test frequency distribution :return: void", "name": "test_freq", "signature": "def test_freq(self)" }, { "docstring": "Test point-wise mutual information distribution :return: void", "name": "test_pmi", "signature": "def test_pmi(self)" }, { "docstring": "Test con...
3
stack_v2_sparse_classes_30k_train_016013
Implement the Python class `TestSemanticSimilarity` described below. Class description: This class contains tests for the SemanticSimilarity class Method signatures and docstrings: - def test_freq(self): Test frequency distribution :return: void - def test_pmi(self): Test point-wise mutual information distribution :r...
Implement the Python class `TestSemanticSimilarity` described below. Class description: This class contains tests for the SemanticSimilarity class Method signatures and docstrings: - def test_freq(self): Test frequency distribution :return: void - def test_pmi(self): Test point-wise mutual information distribution :r...
7af7b357347ed526de7a3d6f16652843d214dcbf
<|skeleton|> class TestSemanticSimilarity: """This class contains tests for the SemanticSimilarity class""" def test_freq(self): """Test frequency distribution :return: void""" <|body_0|> def test_pmi(self): """Test point-wise mutual information distribution :return: void""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestSemanticSimilarity: """This class contains tests for the SemanticSimilarity class""" def test_freq(self): """Test frequency distribution :return: void""" evaluator = SemanticSimilarity(2, 'FREQ') output = evaluator.dist_to_string(self.test_word_pairs) self.assertCountE...
the_stack_v2_python_sparse
SemanticSimilarity/sem_sim.py
zoew2/Projects
train
0
4b1ac1560133c78ccae5532558ef4d05a7850c5c
[ "try:\n return int(option) in range(1, 5)\nexcept ValueError:\n return False", "option = input('Option: ')\nwhile not InputHandler.validOption(option):\n ClientScreenPrinter.invalidOption()\n ClientScreenPrinter.menu()\n option = input()\nreturn option", "if option == '3':\n exit()\nmessageObj...
<|body_start_0|> try: return int(option) in range(1, 5) except ValueError: return False <|end_body_0|> <|body_start_1|> option = input('Option: ') while not InputHandler.validOption(option): ClientScreenPrinter.invalidOption() ClientScreen...
This class handles user input on the client side It's important to note that it does not make any processing besides getting an option and validating it. The processing is done at server side, with the payload received from the message object sent by the client.
InputHandler
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class InputHandler: """This class handles user input on the client side It's important to note that it does not make any processing besides getting an option and validating it. The processing is done at server side, with the payload received from the message object sent by the client.""" def valid...
stack_v2_sparse_classes_36k_train_007275
1,841
no_license
[ { "docstring": "Cheks if an option received from the user is valid", "name": "validOption", "signature": "def validOption(cls, option)" }, { "docstring": "Handles logic to get user option", "name": "getOption", "signature": "def getOption(cls)" }, { "docstring": "Handles option c...
3
stack_v2_sparse_classes_30k_train_005266
Implement the Python class `InputHandler` described below. Class description: This class handles user input on the client side It's important to note that it does not make any processing besides getting an option and validating it. The processing is done at server side, with the payload received from the message objec...
Implement the Python class `InputHandler` described below. Class description: This class handles user input on the client side It's important to note that it does not make any processing besides getting an option and validating it. The processing is done at server side, with the payload received from the message objec...
705ef0c0cb562a9a8506e4de6efd8cb483698c81
<|skeleton|> class InputHandler: """This class handles user input on the client side It's important to note that it does not make any processing besides getting an option and validating it. The processing is done at server side, with the payload received from the message object sent by the client.""" def valid...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class InputHandler: """This class handles user input on the client side It's important to note that it does not make any processing besides getting an option and validating it. The processing is done at server side, with the payload received from the message object sent by the client.""" def validOption(cls, o...
the_stack_v2_python_sparse
src/distributed_word_counter/client/InputHandler.py
ruanramos/distributed-systems
train
0
73309d260a18bc14d6796bcd33a22d92ceb748fe
[ "self.bins = bins\nself.range = range\nself.eps = eps\nself.interpolation = interpolation\nself.variable_width = variable_width", "T = column_or_1d(T)\nt0 = T[y == 0]\nt1 = T[y == 1]\nbins = self.bins\nif self.bins == 'auto':\n bins = 10 + int(len(t0) ** (1.0 / 3.0))\nrange = self.range\nif self.range is None:...
<|body_start_0|> self.bins = bins self.range = range self.eps = eps self.interpolation = interpolation self.variable_width = variable_width <|end_body_0|> <|body_start_1|> T = column_or_1d(T) t0 = T[y == 0] t1 = T[y == 1] bins = self.bins ...
Probability calibration through density estimation with histograms.
HistogramCalibrator
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HistogramCalibrator: """Probability calibration through density estimation with histograms.""" def __init__(self, bins='auto', range=None, eps=0.1, interpolation=None, variable_width=False): """Constructor. Parameters ---------- * `bins` [string or integer]: The number of bins, or `"...
stack_v2_sparse_classes_36k_train_007276
5,898
permissive
[ { "docstring": "Constructor. Parameters ---------- * `bins` [string or integer]: The number of bins, or `\"auto\"` to automatically determine the number of bins depending on the number of samples. * `range` [(lower, upper), optional]: The lower and upper bounds. If `None`, bounds are automatically inferred from...
3
stack_v2_sparse_classes_30k_train_006036
Implement the Python class `HistogramCalibrator` described below. Class description: Probability calibration through density estimation with histograms. Method signatures and docstrings: - def __init__(self, bins='auto', range=None, eps=0.1, interpolation=None, variable_width=False): Constructor. Parameters ---------...
Implement the Python class `HistogramCalibrator` described below. Class description: Probability calibration through density estimation with histograms. Method signatures and docstrings: - def __init__(self, bins='auto', range=None, eps=0.1, interpolation=None, variable_width=False): Constructor. Parameters ---------...
383ef84c449d654d783b4e8bdbb847ee8cbf24b9
<|skeleton|> class HistogramCalibrator: """Probability calibration through density estimation with histograms.""" def __init__(self, bins='auto', range=None, eps=0.1, interpolation=None, variable_width=False): """Constructor. Parameters ---------- * `bins` [string or integer]: The number of bins, or `"...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class HistogramCalibrator: """Probability calibration through density estimation with histograms.""" def __init__(self, bins='auto', range=None, eps=0.1, interpolation=None, variable_width=False): """Constructor. Parameters ---------- * `bins` [string or integer]: The number of bins, or `"auto"` to aut...
the_stack_v2_python_sparse
ml/calibration.py
leonoravesterbacka/carl-torch
train
10
6edeef047bdc2422a9c33b0da6a6dd9974bffc70
[ "if 'deposit_name' not in kwargs:\n kwargs['deposit_name'] = vein.name\nif 'material' not in kwargs:\n kwargs['material'] = vein.material_ore\nsuper().__init__(**kwargs)\nself.diameter = diameter\nself.height = height\nself.vein = vein", "result = super().as_json()\nresult['generator'].update({'block': self...
<|body_start_0|> if 'deposit_name' not in kwargs: kwargs['deposit_name'] = vein.name if 'material' not in kwargs: kwargs['material'] = vein.material_ore super().__init__(**kwargs) self.diameter = diameter self.height = height self.vein = vein <|end...
GravelDeposit create s a deposit as a large cylinder of the given material.
GravelDeposit
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GravelDeposit: """GravelDeposit create s a deposit as a large cylinder of the given material.""" def __init__(self, vein: Vein, height: int=2, diameter: int=16, **kwargs): """Create a new plate deposit.""" <|body_0|> def as_json(self): """Create a dict representa...
stack_v2_sparse_classes_36k_train_007277
1,306
no_license
[ { "docstring": "Create a new plate deposit.", "name": "__init__", "signature": "def __init__(self, vein: Vein, height: int=2, diameter: int=16, **kwargs)" }, { "docstring": "Create a dict representation of this deposit suitable for being converted to JSON.", "name": "as_json", "signature...
2
stack_v2_sparse_classes_30k_train_020742
Implement the Python class `GravelDeposit` described below. Class description: GravelDeposit create s a deposit as a large cylinder of the given material. Method signatures and docstrings: - def __init__(self, vein: Vein, height: int=2, diameter: int=16, **kwargs): Create a new plate deposit. - def as_json(self): Cre...
Implement the Python class `GravelDeposit` described below. Class description: GravelDeposit create s a deposit as a large cylinder of the given material. Method signatures and docstrings: - def __init__(self, vein: Vein, height: int=2, diameter: int=16, **kwargs): Create a new plate deposit. - def as_json(self): Cre...
9bd6e74cb3817eec76119978ea31cf5b04e0ed51
<|skeleton|> class GravelDeposit: """GravelDeposit create s a deposit as a large cylinder of the given material.""" def __init__(self, vein: Vein, height: int=2, diameter: int=16, **kwargs): """Create a new plate deposit.""" <|body_0|> def as_json(self): """Create a dict representa...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GravelDeposit: """GravelDeposit create s a deposit as a large cylinder of the given material.""" def __init__(self, vein: Vein, height: int=2, diameter: int=16, **kwargs): """Create a new plate deposit.""" if 'deposit_name' not in kwargs: kwargs['deposit_name'] = vein.name ...
the_stack_v2_python_sparse
src/packconfig/oregen/deposits/gravel_deposit.py
tungstonminer/packconfig
train
0
18b238101321757398c88053606e09c1b0546cab
[ "company = self.env.company\nbranch_ids = self.env.user.branch_ids\nbranch = branch_ids.filtered(lambda branch: branch.company_id == company)\nreturn [('id', 'in', branch.ids)]", "self.default_account_id = False\nself.suspense_account_id = False\nself.profit_account_id = False\nself.loss_account_id = False" ]
<|body_start_0|> company = self.env.company branch_ids = self.env.user.branch_ids branch = branch_ids.filtered(lambda branch: branch.company_id == company) return [('id', 'in', branch.ids)] <|end_body_0|> <|body_start_1|> self.default_account_id = False self.suspense_acc...
inherited account journal
AccountJournal
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AccountJournal: """inherited account journal""" def _get_branch_domain(self): """methode to get branch domain""" <|body_0|> def onchange_branch_id(self): """onchange methode""" <|body_1|> <|end_skeleton|> <|body_start_0|> company = self.env.comp...
stack_v2_sparse_classes_36k_train_007278
4,321
no_license
[ { "docstring": "methode to get branch domain", "name": "_get_branch_domain", "signature": "def _get_branch_domain(self)" }, { "docstring": "onchange methode", "name": "onchange_branch_id", "signature": "def onchange_branch_id(self)" } ]
2
stack_v2_sparse_classes_30k_val_000674
Implement the Python class `AccountJournal` described below. Class description: inherited account journal Method signatures and docstrings: - def _get_branch_domain(self): methode to get branch domain - def onchange_branch_id(self): onchange methode
Implement the Python class `AccountJournal` described below. Class description: inherited account journal Method signatures and docstrings: - def _get_branch_domain(self): methode to get branch domain - def onchange_branch_id(self): onchange methode <|skeleton|> class AccountJournal: """inherited account journal...
4b1bcb8f17aad44fe9c80a8180eb0128e6bb2c14
<|skeleton|> class AccountJournal: """inherited account journal""" def _get_branch_domain(self): """methode to get branch domain""" <|body_0|> def onchange_branch_id(self): """onchange methode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AccountJournal: """inherited account journal""" def _get_branch_domain(self): """methode to get branch domain""" company = self.env.company branch_ids = self.env.user.branch_ids branch = branch_ids.filtered(lambda branch: branch.company_id == company) return [('id'...
the_stack_v2_python_sparse
multi_branch_base/models/branch_account_journal.py
CybroOdoo/CybroAddons
train
209
3254a2bdf6c8ea51a9ddf7d6191e065af6c5d4bf
[ "self._currencyPair = currencyPair\nif year_month is None:\n now = datetime.datetime.now()\n self._dbname = '../../data/{2}_{0}{1:02d}.db'.format(now.year, now.month, self._currencyPair)\nelse:\n self._dbname = '../../data/{1}_{0}.db'.format(year_month, self._currencyPair)\nsuper().__init__(self._dbname, r...
<|body_start_0|> self._currencyPair = currencyPair if year_month is None: now = datetime.datetime.now() self._dbname = '../../data/{2}_{0}{1:02d}.db'.format(now.year, now.month, self._currencyPair) else: self._dbname = '../../data/{1}_{0}.db'.format(year_month...
The base class of SQLDB for FX. This class mainly has methods processing the "main" table, which has the structure (datetime, dateval, ask, bid).
SQLBaseforFX
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SQLBaseforFX: """The base class of SQLDB for FX. This class mainly has methods processing the "main" table, which has the structure (datetime, dateval, ask, bid).""" def __init__(self, year_month=None, currencyPair='usdjpy', recreate=False): """Initialization If a database named `sef...
stack_v2_sparse_classes_36k_train_007279
3,742
no_license
[ { "docstring": "Initialization If a database named `sef._dbname` doesn't exist, then it will be created first. If `recreate` is true, then the database will be dropped and recreated.", "name": "__init__", "signature": "def __init__(self, year_month=None, currencyPair='usdjpy', recreate=False)" }, { ...
4
stack_v2_sparse_classes_30k_train_015763
Implement the Python class `SQLBaseforFX` described below. Class description: The base class of SQLDB for FX. This class mainly has methods processing the "main" table, which has the structure (datetime, dateval, ask, bid). Method signatures and docstrings: - def __init__(self, year_month=None, currencyPair='usdjpy',...
Implement the Python class `SQLBaseforFX` described below. Class description: The base class of SQLDB for FX. This class mainly has methods processing the "main" table, which has the structure (datetime, dateval, ask, bid). Method signatures and docstrings: - def __init__(self, year_month=None, currencyPair='usdjpy',...
43b60051987abd06c1d817e7d3172cf2bf7b200a
<|skeleton|> class SQLBaseforFX: """The base class of SQLDB for FX. This class mainly has methods processing the "main" table, which has the structure (datetime, dateval, ask, bid).""" def __init__(self, year_month=None, currencyPair='usdjpy', recreate=False): """Initialization If a database named `sef...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SQLBaseforFX: """The base class of SQLDB for FX. This class mainly has methods processing the "main" table, which has the structure (datetime, dateval, ask, bid).""" def __init__(self, year_month=None, currencyPair='usdjpy', recreate=False): """Initialization If a database named `sef._dbname` doe...
the_stack_v2_python_sparse
FX/SQLDBclass/SQLBaseforFX.py
Surpris/FXTF
train
0
d5e0ad2b04f52079120098b0c4c579c87fcaf199
[ "status, state = keyword.run_key('Read Properties ' + var.SYSTEM_STATE_URI + 'enumerate')\nbmc_state = state[var.SYSTEM_STATE_URI + 'bmc0']['CurrentBMCState']\nchassis_state = state[var.SYSTEM_STATE_URI + 'chassis0']['CurrentPowerState']\nhost_state = state[var.SYSTEM_STATE_URI + 'host0']['CurrentHostState']\nif p...
<|body_start_0|> status, state = keyword.run_key('Read Properties ' + var.SYSTEM_STATE_URI + 'enumerate') bmc_state = state[var.SYSTEM_STATE_URI + 'bmc0']['CurrentBMCState'] chassis_state = state[var.SYSTEM_STATE_URI + 'chassis0']['CurrentPowerState'] host_state = state[var.SYSTEM_STATE...
state_map
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class state_map: def get_boot_state(self): """Return the system state as a tuple of bmc, chassis, host state, BootProgress and OperatingSystemState.""" <|body_0|> def valid_boot_state(self, boot_type, state_set): """Validate a given set of states is valid. Description of a...
stack_v2_sparse_classes_36k_train_007280
7,706
permissive
[ { "docstring": "Return the system state as a tuple of bmc, chassis, host state, BootProgress and OperatingSystemState.", "name": "get_boot_state", "signature": "def get_boot_state(self)" }, { "docstring": "Validate a given set of states is valid. Description of argument(s): boot_type Boot type (...
3
null
Implement the Python class `state_map` described below. Class description: Implement the state_map class. Method signatures and docstrings: - def get_boot_state(self): Return the system state as a tuple of bmc, chassis, host state, BootProgress and OperatingSystemState. - def valid_boot_state(self, boot_type, state_s...
Implement the Python class `state_map` described below. Class description: Implement the state_map class. Method signatures and docstrings: - def get_boot_state(self): Return the system state as a tuple of bmc, chassis, host state, BootProgress and OperatingSystemState. - def valid_boot_state(self, boot_type, state_s...
7eab8897f12fa56bed3625f95ebc5e148695febf
<|skeleton|> class state_map: def get_boot_state(self): """Return the system state as a tuple of bmc, chassis, host state, BootProgress and OperatingSystemState.""" <|body_0|> def valid_boot_state(self, boot_type, state_set): """Validate a given set of states is valid. Description of a...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class state_map: def get_boot_state(self): """Return the system state as a tuple of bmc, chassis, host state, BootProgress and OperatingSystemState.""" status, state = keyword.run_key('Read Properties ' + var.SYSTEM_STATE_URI + 'enumerate') bmc_state = state[var.SYSTEM_STATE_URI + 'bmc0']['...
the_stack_v2_python_sparse
lib/state_map.py
Nuvoton-Israel/openbmc-test-automation
train
0
a96da83e3b448666f0c79cdc4f777ff0bfde63fa
[ "dummy = pre = ListNode(0)\nwhile head:\n if head.val != val:\n pre.next = ListNode(head.val)\n pre = pre.next\n head = head.next\nreturn dummy.next", "dummy = pre = ListNode(0)\ndummy.next = head\nwhile head:\n if head.val == val:\n pre.next = head.next\n else:\n pre = pre...
<|body_start_0|> dummy = pre = ListNode(0) while head: if head.val != val: pre.next = ListNode(head.val) pre = pre.next head = head.next return dummy.next <|end_body_0|> <|body_start_1|> dummy = pre = ListNode(0) dummy.next...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def removeElements(self, head, val): """:type head: ListNode :type val: int :rtype: ListNode""" <|body_0|> def removeElements_1(self, head, val): """:type head: ListNode :type val: int :rtype: ListNode""" <|body_1|> <|end_skeleton|> <|body_start_0...
stack_v2_sparse_classes_36k_train_007281
2,259
no_license
[ { "docstring": ":type head: ListNode :type val: int :rtype: ListNode", "name": "removeElements", "signature": "def removeElements(self, head, val)" }, { "docstring": ":type head: ListNode :type val: int :rtype: ListNode", "name": "removeElements_1", "signature": "def removeElements_1(sel...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def removeElements(self, head, val): :type head: ListNode :type val: int :rtype: ListNode - def removeElements_1(self, head, val): :type head: ListNode :type val: int :rtype: Lis...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def removeElements(self, head, val): :type head: ListNode :type val: int :rtype: ListNode - def removeElements_1(self, head, val): :type head: ListNode :type val: int :rtype: Lis...
3d9e0ad2f6ed92ec969556f75d97c51ea4854719
<|skeleton|> class Solution: def removeElements(self, head, val): """:type head: ListNode :type val: int :rtype: ListNode""" <|body_0|> def removeElements_1(self, head, val): """:type head: ListNode :type val: int :rtype: ListNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def removeElements(self, head, val): """:type head: ListNode :type val: int :rtype: ListNode""" dummy = pre = ListNode(0) while head: if head.val != val: pre.next = ListNode(head.val) pre = pre.next head = head.next ...
the_stack_v2_python_sparse
Solutions/0203_removeElements.py
YoupengLi/leetcode-sorting
train
3
719a4891481e35ac7657795aa4799e53adc70495
[ "if gr_pin not in [ARDUINO_GROVE_I2C]:\n raise ValueError('Group number can only be I2C.')\nself.microblaze = Arduino(mb_info, ARDUINO_GROVE_TH02_PROGRAM)\nself.log_interval_ms = 1000\nself.log_running = 0\nself.microblaze.write_blocking_command(CONFIG_IOP_SWITCH)", "self.microblaze.write_blocking_command(READ...
<|body_start_0|> if gr_pin not in [ARDUINO_GROVE_I2C]: raise ValueError('Group number can only be I2C.') self.microblaze = Arduino(mb_info, ARDUINO_GROVE_TH02_PROGRAM) self.log_interval_ms = 1000 self.log_running = 0 self.microblaze.write_blocking_command(CONFIG_IOP_S...
This class controls the Grove I2C Temperature and Humidity sensor. Temperature & humidity sensor (high-accuracy & mini). Hardware version: v1.0. Attributes ---------- microblaze : Arduino Microblaze processor instance used by this module. log_running : int The state of the log (0: stopped, 1: started). log_interval_ms ...
Grove_TH02
[ "BSD-3-Clause", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Grove_TH02: """This class controls the Grove I2C Temperature and Humidity sensor. Temperature & humidity sensor (high-accuracy & mini). Hardware version: v1.0. Attributes ---------- microblaze : Arduino Microblaze processor instance used by this module. log_running : int The state of the log (0: ...
stack_v2_sparse_classes_36k_train_007282
6,103
permissive
[ { "docstring": "Return a new instance of an Grove_TH02 object. Parameters ---------- mb_info : dict A dictionary storing Microblaze information, such as the IP name and the reset name. gr_pin: list A group of pins on arduino-grove shield.", "name": "__init__", "signature": "def __init__(self, mb_info, g...
5
stack_v2_sparse_classes_30k_train_016125
Implement the Python class `Grove_TH02` described below. Class description: This class controls the Grove I2C Temperature and Humidity sensor. Temperature & humidity sensor (high-accuracy & mini). Hardware version: v1.0. Attributes ---------- microblaze : Arduino Microblaze processor instance used by this module. log_...
Implement the Python class `Grove_TH02` described below. Class description: This class controls the Grove I2C Temperature and Humidity sensor. Temperature & humidity sensor (high-accuracy & mini). Hardware version: v1.0. Attributes ---------- microblaze : Arduino Microblaze processor instance used by this module. log_...
38e9fcee46f0839e83e123cf22af76b13671a574
<|skeleton|> class Grove_TH02: """This class controls the Grove I2C Temperature and Humidity sensor. Temperature & humidity sensor (high-accuracy & mini). Hardware version: v1.0. Attributes ---------- microblaze : Arduino Microblaze processor instance used by this module. log_running : int The state of the log (0: ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Grove_TH02: """This class controls the Grove I2C Temperature and Humidity sensor. Temperature & humidity sensor (high-accuracy & mini). Hardware version: v1.0. Attributes ---------- microblaze : Arduino Microblaze processor instance used by this module. log_running : int The state of the log (0: stopped, 1: s...
the_stack_v2_python_sparse
pynq/lib/arduino/arduino_grove_th02.py
yunqu/PYNQ
train
8
8d8fa376c97b2db531aae7066d01d5106d678a33
[ "if count == 0:\n self.open().get(product=product).close()\n return 0\nelse:\n obj, _ = self.update_or_create(product=product, closed_at=None, defaults={'count': count})\n obj.full_clean()\n obj.refresh_from_db()\n return obj.count", "obj = self.open().get(product=product)\nobj.comment = comment...
<|body_start_0|> if count == 0: self.open().get(product=product).close() return 0 else: obj, _ = self.update_or_create(product=product, closed_at=None, defaults={'count': count}) obj.full_clean() obj.refresh_from_db() return obj.cou...
Manager for the Reorder model.
ReorderManager
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ReorderManager: """Manager for the Reorder model.""" def set_count(self, product, count): """Set a reorder count for a product. Args: product: inventory.models.product.BaseProduct count: int""" <|body_0|> def set_comment(self, product, comment): """Set a reorder'...
stack_v2_sparse_classes_36k_train_007283
2,584
no_license
[ { "docstring": "Set a reorder count for a product. Args: product: inventory.models.product.BaseProduct count: int", "name": "set_count", "signature": "def set_count(self, product, count)" }, { "docstring": "Set a reorder's comment field.", "name": "set_comment", "signature": "def set_com...
3
stack_v2_sparse_classes_30k_train_020810
Implement the Python class `ReorderManager` described below. Class description: Manager for the Reorder model. Method signatures and docstrings: - def set_count(self, product, count): Set a reorder count for a product. Args: product: inventory.models.product.BaseProduct count: int - def set_comment(self, product, com...
Implement the Python class `ReorderManager` described below. Class description: Manager for the Reorder model. Method signatures and docstrings: - def set_count(self, product, count): Set a reorder count for a product. Args: product: inventory.models.product.BaseProduct count: int - def set_comment(self, product, com...
ba51d4e304b1aeb296fa2fe16611c892fcdbd471
<|skeleton|> class ReorderManager: """Manager for the Reorder model.""" def set_count(self, product, count): """Set a reorder count for a product. Args: product: inventory.models.product.BaseProduct count: int""" <|body_0|> def set_comment(self, product, comment): """Set a reorder'...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ReorderManager: """Manager for the Reorder model.""" def set_count(self, product, count): """Set a reorder count for a product. Args: product: inventory.models.product.BaseProduct count: int""" if count == 0: self.open().get(product=product).close() return 0 ...
the_stack_v2_python_sparse
restock/models.py
stcstores/stcadmin
train
0
c6e00b1d7380f2e8ce71fa3ab97973e5f7708d16
[ "if not head or not head.next:\n return False\nid_set = set()\nwhile head:\n if id(head) in id_set:\n return True\n else:\n id_set.add(id(head))\n head = head.next\nreturn False", "if not head or not head.next:\n return False\nslow = fast = head\nwhile fast and fast.next:\n fast = ...
<|body_start_0|> if not head or not head.next: return False id_set = set() while head: if id(head) in id_set: return True else: id_set.add(id(head)) head = head.next return False <|end_body_0|> <|body_start_...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def hasCycle_v1(self, head: ListNode) -> bool: """使用哈希表存储已经访问过的结点地址""" <|body_0|> def hasCycle_v2(self, head: ListNode) -> bool: """快慢指针法""" <|body_1|> <|end_skeleton|> <|body_start_0|> if not head or not head.next: return Fals...
stack_v2_sparse_classes_36k_train_007284
1,263
no_license
[ { "docstring": "使用哈希表存储已经访问过的结点地址", "name": "hasCycle_v1", "signature": "def hasCycle_v1(self, head: ListNode) -> bool" }, { "docstring": "快慢指针法", "name": "hasCycle_v2", "signature": "def hasCycle_v2(self, head: ListNode) -> bool" } ]
2
stack_v2_sparse_classes_30k_train_001303
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def hasCycle_v1(self, head: ListNode) -> bool: 使用哈希表存储已经访问过的结点地址 - def hasCycle_v2(self, head: ListNode) -> bool: 快慢指针法
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def hasCycle_v1(self, head: ListNode) -> bool: 使用哈希表存储已经访问过的结点地址 - def hasCycle_v2(self, head: ListNode) -> bool: 快慢指针法 <|skeleton|> class Solution: def hasCycle_v1(self, h...
7bf9b992acb5c3db22b52f1ee70816296a41af9d
<|skeleton|> class Solution: def hasCycle_v1(self, head: ListNode) -> bool: """使用哈希表存储已经访问过的结点地址""" <|body_0|> def hasCycle_v2(self, head: ListNode) -> bool: """快慢指针法""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def hasCycle_v1(self, head: ListNode) -> bool: """使用哈希表存储已经访问过的结点地址""" if not head or not head.next: return False id_set = set() while head: if id(head) in id_set: return True else: id_set.add(id(head...
the_stack_v2_python_sparse
141cycleLinkedList.py
slsefe/leetcode
train
0
f4e3e81298062e977f3702293edda933eec20842
[ "from elasticsearch_dsl.query import Q\nsearch = super(LogData, cls).search()\nreturn search.query(~Q('term', loglevel__raw='AUDIT'))", "search = cls.bounded_search(start, end)\nif len(hosts) != 0:\n search = search.query(query.Terms(host__raw=hosts))\nreturn search", "assert isinstance(interval, basestring)...
<|body_start_0|> from elasticsearch_dsl.query import Q search = super(LogData, cls).search() return search.query(~Q('term', loglevel__raw='AUDIT')) <|end_body_0|> <|body_start_1|> search = cls.bounded_search(start, end) if len(hosts) != 0: search = search.query(query...
Logstash log entry model (intended to be read-only).
LogData
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LogData: """Logstash log entry model (intended to be read-only).""" def search(cls): """Gets a generic Log search object. See elasticsearch-dsl for parameter information.""" <|body_0|> def ranged_log_search(cls, start=None, end=None, hosts=[]): """Returns a searc...
stack_v2_sparse_classes_36k_train_007285
6,496
permissive
[ { "docstring": "Gets a generic Log search object. See elasticsearch-dsl for parameter information.", "name": "search", "signature": "def search(cls)" }, { "docstring": "Returns a search with time range and hosts list terms", "name": "ranged_log_search", "signature": "def ranged_log_searc...
3
stack_v2_sparse_classes_30k_train_015219
Implement the Python class `LogData` described below. Class description: Logstash log entry model (intended to be read-only). Method signatures and docstrings: - def search(cls): Gets a generic Log search object. See elasticsearch-dsl for parameter information. - def ranged_log_search(cls, start=None, end=None, hosts...
Implement the Python class `LogData` described below. Class description: Logstash log entry model (intended to be read-only). Method signatures and docstrings: - def search(cls): Gets a generic Log search object. See elasticsearch-dsl for parameter information. - def ranged_log_search(cls, start=None, end=None, hosts...
d7f1f1f1ff926148d2aa541d0bd4758173aa76d5
<|skeleton|> class LogData: """Logstash log entry model (intended to be read-only).""" def search(cls): """Gets a generic Log search object. See elasticsearch-dsl for parameter information.""" <|body_0|> def ranged_log_search(cls, start=None, end=None, hosts=[]): """Returns a searc...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LogData: """Logstash log entry model (intended to be read-only).""" def search(cls): """Gets a generic Log search object. See elasticsearch-dsl for parameter information.""" from elasticsearch_dsl.query import Q search = super(LogData, cls).search() return search.query(~Q(...
the_stack_v2_python_sparse
goldstone/glogging/models.py
leftees/goldstone-server
train
0
48ee02535f5c029e6935e7eba17857c2e681858c
[ "@wraps(func)\ndef inner(*args):\n \"\"\"Service function\"\"\"\n if not isinstance(args[1], Matrix):\n raise TypeError(f'Cannot execute action to type {type(args[1])}')\n return func(*args)\nreturn inner", "@wraps(func)\ndef inner(*args):\n \"\"\"Service function\"\"\"\n if not isinstance(a...
<|body_start_0|> @wraps(func) def inner(*args): """Service function""" if not isinstance(args[1], Matrix): raise TypeError(f'Cannot execute action to type {type(args[1])}') return func(*args) return inner <|end_body_0|> <|body_start_1|> ...
Class of decorators for functions in Matrix.
Decorators
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Decorators: """Class of decorators for functions in Matrix.""" def matrix_cheker(cls, func): """Decorator to verify argument for basic math operations. :param func: function of math operation. :param func: function. :returns: function -- decorated function. :raises: TypeError.""" ...
stack_v2_sparse_classes_36k_train_007286
9,470
no_license
[ { "docstring": "Decorator to verify argument for basic math operations. :param func: function of math operation. :param func: function. :returns: function -- decorated function. :raises: TypeError.", "name": "matrix_cheker", "signature": "def matrix_cheker(cls, func)" }, { "docstring": "Decorato...
3
stack_v2_sparse_classes_30k_train_011269
Implement the Python class `Decorators` described below. Class description: Class of decorators for functions in Matrix. Method signatures and docstrings: - def matrix_cheker(cls, func): Decorator to verify argument for basic math operations. :param func: function of math operation. :param func: function. :returns: f...
Implement the Python class `Decorators` described below. Class description: Class of decorators for functions in Matrix. Method signatures and docstrings: - def matrix_cheker(cls, func): Decorator to verify argument for basic math operations. :param func: function of math operation. :param func: function. :returns: f...
a370c7e7fd8c55ec5f745918ea0bd27d93bc2959
<|skeleton|> class Decorators: """Class of decorators for functions in Matrix.""" def matrix_cheker(cls, func): """Decorator to verify argument for basic math operations. :param func: function of math operation. :param func: function. :returns: function -- decorated function. :raises: TypeError.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Decorators: """Class of decorators for functions in Matrix.""" def matrix_cheker(cls, func): """Decorator to verify argument for basic math operations. :param func: function of math operation. :param func: function. :returns: function -- decorated function. :raises: TypeError.""" @wraps(f...
the_stack_v2_python_sparse
homework_5._/matrix.py
klimente/homework
train
3
dd861d776d14bf9bddb38906d327d4a8ee46ae1b
[ "logger.info('GENERATE FINGERPRINTS')\nlogger.info(f'Number of input structures: {len(structure_klifs_ids)}')\nstart_time = datetime.datetime.now()\nlogger.info(f'Fingerprint generation started at: {start_time}')\nif klifs_session is None:\n klifs_session = setup_remote()\nn_cores = set_n_cores(n_cores)\nfingerp...
<|body_start_0|> logger.info('GENERATE FINGERPRINTS') logger.info(f'Number of input structures: {len(structure_klifs_ids)}') start_time = datetime.datetime.now() logger.info(f'Fingerprint generation started at: {start_time}') if klifs_session is None: klifs_session = ...
FingerprintGenerator
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FingerprintGenerator: def from_structure_klifs_ids(cls, structure_klifs_ids, klifs_session=None, n_cores=1): """Calculate fingerprints for one or more KLIFS structures (by structure KLIFS IDs). Parameters ---------- structure_klifs_id : int Input structure KLIFS ID (output fingerprints m...
stack_v2_sparse_classes_36k_train_007287
3,626
permissive
[ { "docstring": "Calculate fingerprints for one or more KLIFS structures (by structure KLIFS IDs). Parameters ---------- structure_klifs_id : int Input structure KLIFS ID (output fingerprints may contain less IDs because some structures could not be encoded). klifs_session : opencadd.databases.klifs.session.Sess...
3
stack_v2_sparse_classes_30k_train_000868
Implement the Python class `FingerprintGenerator` described below. Class description: Implement the FingerprintGenerator class. Method signatures and docstrings: - def from_structure_klifs_ids(cls, structure_klifs_ids, klifs_session=None, n_cores=1): Calculate fingerprints for one or more KLIFS structures (by structu...
Implement the Python class `FingerprintGenerator` described below. Class description: Implement the FingerprintGenerator class. Method signatures and docstrings: - def from_structure_klifs_ids(cls, structure_klifs_ids, klifs_session=None, n_cores=1): Calculate fingerprints for one or more KLIFS structures (by structu...
8433bb64062ed785503b96b52f39bbdb02f66381
<|skeleton|> class FingerprintGenerator: def from_structure_klifs_ids(cls, structure_klifs_ids, klifs_session=None, n_cores=1): """Calculate fingerprints for one or more KLIFS structures (by structure KLIFS IDs). Parameters ---------- structure_klifs_id : int Input structure KLIFS ID (output fingerprints m...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FingerprintGenerator: def from_structure_klifs_ids(cls, structure_klifs_ids, klifs_session=None, n_cores=1): """Calculate fingerprints for one or more KLIFS structures (by structure KLIFS IDs). Parameters ---------- structure_klifs_id : int Input structure KLIFS ID (output fingerprints may contain les...
the_stack_v2_python_sparse
kissim/encoding/fingerprint_generator.py
volkamerlab/kissim
train
26
2bac48f158df5f8d072e4a6b378cc160569ff0b7
[ "super(FileObjectOutputWriter, self).__init__(encoding=encoding)\nself._errors = 'strict'\nself._file_object = file_object", "try:\n encoded_string = codecs.encode(string, self._encoding, self._errors)\nexcept UnicodeEncodeError:\n if self._errors == 'strict':\n logger.error('Unable to properly write...
<|body_start_0|> super(FileObjectOutputWriter, self).__init__(encoding=encoding) self._errors = 'strict' self._file_object = file_object <|end_body_0|> <|body_start_1|> try: encoded_string = codecs.encode(string, self._encoding, self._errors) except UnicodeEncodeErro...
File object command line interface output writer. This output writer relies on the file-like object having a write method.
FileObjectOutputWriter
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FileObjectOutputWriter: """File object command line interface output writer. This output writer relies on the file-like object having a write method.""" def __init__(self, file_object, encoding='utf-8'): """Initializes a file object command line interface output writer. Args: file_ob...
stack_v2_sparse_classes_36k_train_007288
19,023
permissive
[ { "docstring": "Initializes a file object command line interface output writer. Args: file_object (file): file-like object to read from. encoding (Optional[str]): output encoding.", "name": "__init__", "signature": "def __init__(self, file_object, encoding='utf-8')" }, { "docstring": "Writes a s...
2
null
Implement the Python class `FileObjectOutputWriter` described below. Class description: File object command line interface output writer. This output writer relies on the file-like object having a write method. Method signatures and docstrings: - def __init__(self, file_object, encoding='utf-8'): Initializes a file o...
Implement the Python class `FileObjectOutputWriter` described below. Class description: File object command line interface output writer. This output writer relies on the file-like object having a write method. Method signatures and docstrings: - def __init__(self, file_object, encoding='utf-8'): Initializes a file o...
d6022f8cfebfddf2d08ab2d300a41b61f3349933
<|skeleton|> class FileObjectOutputWriter: """File object command line interface output writer. This output writer relies on the file-like object having a write method.""" def __init__(self, file_object, encoding='utf-8'): """Initializes a file object command line interface output writer. Args: file_ob...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FileObjectOutputWriter: """File object command line interface output writer. This output writer relies on the file-like object having a write method.""" def __init__(self, file_object, encoding='utf-8'): """Initializes a file object command line interface output writer. Args: file_object (file): ...
the_stack_v2_python_sparse
plaso/cli/tools.py
log2timeline/plaso
train
1,506
763050d8f94b9409bd29b0aa821787ab0c1e103c
[ "result = []\nif not root:\n return 0\nstackOfNode = [root]\nstackOfString = [root.val]\nwhile stackOfNode:\n currNode = stackOfNode.pop()\n currString = stackOfString.pop()\n if currNode.left:\n stackOfNode.append(currNode.left)\n stackOfString.append(currString * 10 + currNode.left.val)\...
<|body_start_0|> result = [] if not root: return 0 stackOfNode = [root] stackOfString = [root.val] while stackOfNode: currNode = stackOfNode.pop() currString = stackOfString.pop() if currNode.left: stackOfNode.append...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def sumNumbers(self, root): """:type root: TreeNode :rtype: int""" <|body_0|> def sumNumbers_self(self, root): """:type root: TreeNode :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> result = [] if not root: ...
stack_v2_sparse_classes_36k_train_007289
1,662
no_license
[ { "docstring": ":type root: TreeNode :rtype: int", "name": "sumNumbers", "signature": "def sumNumbers(self, root)" }, { "docstring": ":type root: TreeNode :rtype: int", "name": "sumNumbers_self", "signature": "def sumNumbers_self(self, root)" } ]
2
stack_v2_sparse_classes_30k_train_015830
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def sumNumbers(self, root): :type root: TreeNode :rtype: int - def sumNumbers_self(self, root): :type root: TreeNode :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def sumNumbers(self, root): :type root: TreeNode :rtype: int - def sumNumbers_self(self, root): :type root: TreeNode :rtype: int <|skeleton|> class Solution: def sumNumbers...
ea492ec864b50547214ecbbb2cdeeac21e70229b
<|skeleton|> class Solution: def sumNumbers(self, root): """:type root: TreeNode :rtype: int""" <|body_0|> def sumNumbers_self(self, root): """:type root: TreeNode :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def sumNumbers(self, root): """:type root: TreeNode :rtype: int""" result = [] if not root: return 0 stackOfNode = [root] stackOfString = [root.val] while stackOfNode: currNode = stackOfNode.pop() currString = stackO...
the_stack_v2_python_sparse
129_sum_root_to_leaf_numbers/sol.py
lianke123321/leetcode_sol
train
0
86438f7e8f37ab524c52b50d5a8c93cdcd5d502e
[ "test_directory = '/Users/L1n/Desktop/Entertainment/进击的巨人第一季全集'\nfiles_list = get_all_files_path_with_fix(test_directory, ['mp4', 'mp3'])\ntest_file1 = '/Users/L1n/Desktop/Entertainment/进击的巨人第一季全集/[Dymy][Shingeki no Kyojin][17][BIG5][1280X720].mp4'\nself.assertIn(test_file1, files_list)\ntest_file2 = '/Users/L1n/De...
<|body_start_0|> test_directory = '/Users/L1n/Desktop/Entertainment/进击的巨人第一季全集' files_list = get_all_files_path_with_fix(test_directory, ['mp4', 'mp3']) test_file1 = '/Users/L1n/Desktop/Entertainment/进击的巨人第一季全集/[Dymy][Shingeki no Kyojin][17][BIG5][1280X720].mp4' self.assertIn(test_file1,...
TestGetRightFileInfo
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestGetRightFileInfo: def test_get_all_files_path(self): """测试是否能获取到指定路径下的所有指定后缀的文件 :return:""" <|body_0|> def test_open_a_file_with_right_app(self): """测试是否能够正确打开一个文件 :return:""" <|body_1|> def test_random_choice(self): """测试是否能够实现随机选择功能 :return...
stack_v2_sparse_classes_36k_train_007290
2,710
no_license
[ { "docstring": "测试是否能获取到指定路径下的所有指定后缀的文件 :return:", "name": "test_get_all_files_path", "signature": "def test_get_all_files_path(self)" }, { "docstring": "测试是否能够正确打开一个文件 :return:", "name": "test_open_a_file_with_right_app", "signature": "def test_open_a_file_with_right_app(self)" }, {...
3
stack_v2_sparse_classes_30k_train_004213
Implement the Python class `TestGetRightFileInfo` described below. Class description: Implement the TestGetRightFileInfo class. Method signatures and docstrings: - def test_get_all_files_path(self): 测试是否能获取到指定路径下的所有指定后缀的文件 :return: - def test_open_a_file_with_right_app(self): 测试是否能够正确打开一个文件 :return: - def test_random...
Implement the Python class `TestGetRightFileInfo` described below. Class description: Implement the TestGetRightFileInfo class. Method signatures and docstrings: - def test_get_all_files_path(self): 测试是否能获取到指定路径下的所有指定后缀的文件 :return: - def test_open_a_file_with_right_app(self): 测试是否能够正确打开一个文件 :return: - def test_random...
73022b40d26ad09051329ae7ff8aae7201d8de6d
<|skeleton|> class TestGetRightFileInfo: def test_get_all_files_path(self): """测试是否能获取到指定路径下的所有指定后缀的文件 :return:""" <|body_0|> def test_open_a_file_with_right_app(self): """测试是否能够正确打开一个文件 :return:""" <|body_1|> def test_random_choice(self): """测试是否能够实现随机选择功能 :return...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestGetRightFileInfo: def test_get_all_files_path(self): """测试是否能获取到指定路径下的所有指定后缀的文件 :return:""" test_directory = '/Users/L1n/Desktop/Entertainment/进击的巨人第一季全集' files_list = get_all_files_path_with_fix(test_directory, ['mp4', 'mp3']) test_file1 = '/Users/L1n/Desktop/Entertainment...
the_stack_v2_python_sparse
随机选择器/test_my_random_choicer.py
L1nwatch/Mac-Python-3.X
train
10
07ddf16af34a8c0cb4136f3385dd7ccdebfbde2b
[ "if not root:\n return False\nstack = deque()\nprev = None\nwhile root or stack:\n if root:\n stack.append(root)\n root = root.left\n else:\n node = stack.pop()\n if prev and prev.val > node.val:\n return False\n prev = node\n root = node.right\nreturn T...
<|body_start_0|> if not root: return False stack = deque() prev = None while root or stack: if root: stack.append(root) root = root.left else: node = stack.pop() if prev and prev.val > nod...
These are class or static variables. Use self.prev and self.firstnode to access them inside a function.
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: """These are class or static variables. Use self.prev and self.firstnode to access them inside a function.""" def isValidBST(self, root): """similar to inorder traverse. If this is an valide BST, the inorder traverse should be in order. record previous poped up node. Then c...
stack_v2_sparse_classes_36k_train_007291
1,610
no_license
[ { "docstring": "similar to inorder traverse. If this is an valide BST, the inorder traverse should be in order. record previous poped up node. Then compare with the current poped up node. :type root: TreeNode :rtype: bool", "name": "isValidBST", "signature": "def isValidBST(self, root)" }, { "do...
2
stack_v2_sparse_classes_30k_train_005704
Implement the Python class `Solution` described below. Class description: These are class or static variables. Use self.prev and self.firstnode to access them inside a function. Method signatures and docstrings: - def isValidBST(self, root): similar to inorder traverse. If this is an valide BST, the inorder traverse ...
Implement the Python class `Solution` described below. Class description: These are class or static variables. Use self.prev and self.firstnode to access them inside a function. Method signatures and docstrings: - def isValidBST(self, root): similar to inorder traverse. If this is an valide BST, the inorder traverse ...
49d0831387227e69ae4067c1f5b7e828976377b4
<|skeleton|> class Solution: """These are class or static variables. Use self.prev and self.firstnode to access them inside a function.""" def isValidBST(self, root): """similar to inorder traverse. If this is an valide BST, the inorder traverse should be in order. record previous poped up node. Then c...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: """These are class or static variables. Use self.prev and self.firstnode to access them inside a function.""" def isValidBST(self, root): """similar to inorder traverse. If this is an valide BST, the inorder traverse should be in order. record previous poped up node. Then compare with t...
the_stack_v2_python_sparse
binary_tree_divide_conquer/98_Validate Binary Search Tree.py
libinjungle/LeetCode_Python
train
0
037d5658e5e85f09b18e9b0cab84902de5aed6fe
[ "super().__init__()\nassert use_masking != use_weighted_masking or not use_masking\nself.use_masking = use_masking\nself.use_weighted_masking = use_weighted_masking\nreduction = 'none' if self.use_weighted_masking else 'mean'\nself.l1_criterion = nn.L1Loss(reduction=reduction)\nself.mse_criterion = nn.MSELoss(reduc...
<|body_start_0|> super().__init__() assert use_masking != use_weighted_masking or not use_masking self.use_masking = use_masking self.use_weighted_masking = use_weighted_masking reduction = 'none' if self.use_weighted_masking else 'mean' self.l1_criterion = nn.L1Loss(redu...
Loss function module for Tacotron2.
Tacotron2Loss
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Tacotron2Loss: """Loss function module for Tacotron2.""" def __init__(self, use_masking=True, use_weighted_masking=False, bce_pos_weight=20.0): """Initialize Tactoron2 loss module. Args: use_masking (bool): Whether to apply masking for padded part in loss calculation. use_weighted_ma...
stack_v2_sparse_classes_36k_train_007292
46,210
permissive
[ { "docstring": "Initialize Tactoron2 loss module. Args: use_masking (bool): Whether to apply masking for padded part in loss calculation. use_weighted_masking (bool): Whether to apply weighted masking in loss calculation. bce_pos_weight (float): Weight of positive sample of stop token.", "name": "__init__",...
2
stack_v2_sparse_classes_30k_train_016208
Implement the Python class `Tacotron2Loss` described below. Class description: Loss function module for Tacotron2. Method signatures and docstrings: - def __init__(self, use_masking=True, use_weighted_masking=False, bce_pos_weight=20.0): Initialize Tactoron2 loss module. Args: use_masking (bool): Whether to apply mas...
Implement the Python class `Tacotron2Loss` described below. Class description: Loss function module for Tacotron2. Method signatures and docstrings: - def __init__(self, use_masking=True, use_weighted_masking=False, bce_pos_weight=20.0): Initialize Tactoron2 loss module. Args: use_masking (bool): Whether to apply mas...
17854a04d43c231eff66bfed9d6aa55e94a29e79
<|skeleton|> class Tacotron2Loss: """Loss function module for Tacotron2.""" def __init__(self, use_masking=True, use_weighted_masking=False, bce_pos_weight=20.0): """Initialize Tactoron2 loss module. Args: use_masking (bool): Whether to apply masking for padded part in loss calculation. use_weighted_ma...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Tacotron2Loss: """Loss function module for Tacotron2.""" def __init__(self, use_masking=True, use_weighted_masking=False, bce_pos_weight=20.0): """Initialize Tactoron2 loss module. Args: use_masking (bool): Whether to apply masking for padded part in loss calculation. use_weighted_masking (bool):...
the_stack_v2_python_sparse
paddlespeech/t2s/modules/losses.py
anniyanvr/DeepSpeech-1
train
0
c87919dc93fafaa2d8e584a99a9487bedd084d4f
[ "self.length = length\nself.height = height\nself.dpdx = (p_low - p_hi) / length\nself.rho = density\nself.mu = mu\nself.p_hi = p_hi", "dim_mismatch = len(x_vec) != 2\nif cv is not None:\n dim_mismatch = dim_mismatch or cv.dim != 2\nif dim_mismatch:\n raise ValueError('PlanarPoiseuille initializer is 2D onl...
<|body_start_0|> self.length = length self.height = height self.dpdx = (p_low - p_hi) / length self.rho = density self.mu = mu self.p_hi = p_hi <|end_body_0|> <|body_start_1|> dim_mismatch = len(x_vec) != 2 if cv is not None: dim_mismatch = di...
Initializer for the planar Poiseuille case. The 2D planar Poiseuille case is defined as a viscous flow between two stationary parallel sides with a uniform pressure drop prescribed as *p_hi* at the inlet and *p_low* at the outlet. See the figure below: .. figure:: ../figures/poiseuille.png :scale: 50 % :alt: Poiseuille...
PlanarPoiseuille
[ "X11", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PlanarPoiseuille: """Initializer for the planar Poiseuille case. The 2D planar Poiseuille case is defined as a viscous flow between two stationary parallel sides with a uniform pressure drop prescribed as *p_hi* at the inlet and *p_low* at the outlet. See the figure below: .. figure:: ../figures/...
stack_v2_sparse_classes_36k_train_007293
32,800
permissive
[ { "docstring": "Initialize the Poiseuille solution initializer. Parameters ---------- p_hi: float Pressure at the inlet (default=100100) p_low: float Pressure at the outlet (default=100000) mu: float Fluid viscosity, (default = 1.0) height: float Height of the domain, (default = .02) length: float Length of the...
3
stack_v2_sparse_classes_30k_train_015757
Implement the Python class `PlanarPoiseuille` described below. Class description: Initializer for the planar Poiseuille case. The 2D planar Poiseuille case is defined as a viscous flow between two stationary parallel sides with a uniform pressure drop prescribed as *p_hi* at the inlet and *p_low* at the outlet. See th...
Implement the Python class `PlanarPoiseuille` described below. Class description: Initializer for the planar Poiseuille case. The 2D planar Poiseuille case is defined as a viscous flow between two stationary parallel sides with a uniform pressure drop prescribed as *p_hi* at the inlet and *p_low* at the outlet. See th...
47f144782258eae2b1fb39520e96f414ae176ff4
<|skeleton|> class PlanarPoiseuille: """Initializer for the planar Poiseuille case. The 2D planar Poiseuille case is defined as a viscous flow between two stationary parallel sides with a uniform pressure drop prescribed as *p_hi* at the inlet and *p_low* at the outlet. See the figure below: .. figure:: ../figures/...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PlanarPoiseuille: """Initializer for the planar Poiseuille case. The 2D planar Poiseuille case is defined as a viscous flow between two stationary parallel sides with a uniform pressure drop prescribed as *p_hi* at the inlet and *p_low* at the outlet. See the figure below: .. figure:: ../figures/poiseuille.pn...
the_stack_v2_python_sparse
mirgecom/initializers.py
kaushikcfd/mirgecom
train
0
8276ec5dbe9c157bdb75502dcc89dec1cec3e946
[ "_, path = url_prefix.split(':')\npath = path.lstrip('/').rstrip('/')\npath_items = path.split('/')\nself.bucket = path_items.pop(0)\nself.prefix = '/'.join(path_items)\nself.s3 = boto3.client('s3')", "if not os.path.exists(output_dir):\n os.makedirs(output_dir)\nkey = f'{self.prefix}/{file_name}'\noutput_file...
<|body_start_0|> _, path = url_prefix.split(':') path = path.lstrip('/').rstrip('/') path_items = path.split('/') self.bucket = path_items.pop(0) self.prefix = '/'.join(path_items) self.s3 = boto3.client('s3') <|end_body_0|> <|body_start_1|> if not os.path.exists...
Downloader
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Downloader: def __init__(self, url_prefix): """URL includes the bucket name and prefix, without filename, ie: s3://my_bucket/path/to/file/""" <|body_0|> def download(self, file_name, output_dir): """Download file from s3 into given file_path directory file_name: myfi...
stack_v2_sparse_classes_36k_train_007294
1,052
no_license
[ { "docstring": "URL includes the bucket name and prefix, without filename, ie: s3://my_bucket/path/to/file/", "name": "__init__", "signature": "def __init__(self, url_prefix)" }, { "docstring": "Download file from s3 into given file_path directory file_name: myfile.zip output_dir: /tmp/", "n...
2
stack_v2_sparse_classes_30k_train_011311
Implement the Python class `Downloader` described below. Class description: Implement the Downloader class. Method signatures and docstrings: - def __init__(self, url_prefix): URL includes the bucket name and prefix, without filename, ie: s3://my_bucket/path/to/file/ - def download(self, file_name, output_dir): Downl...
Implement the Python class `Downloader` described below. Class description: Implement the Downloader class. Method signatures and docstrings: - def __init__(self, url_prefix): URL includes the bucket name and prefix, without filename, ie: s3://my_bucket/path/to/file/ - def download(self, file_name, output_dir): Downl...
5f673f3238c0d13f2a5401573de0c1dd68e2a53f
<|skeleton|> class Downloader: def __init__(self, url_prefix): """URL includes the bucket name and prefix, without filename, ie: s3://my_bucket/path/to/file/""" <|body_0|> def download(self, file_name, output_dir): """Download file from s3 into given file_path directory file_name: myfi...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Downloader: def __init__(self, url_prefix): """URL includes the bucket name and prefix, without filename, ie: s3://my_bucket/path/to/file/""" _, path = url_prefix.split(':') path = path.lstrip('/').rstrip('/') path_items = path.split('/') self.bucket = path_items.pop(0)...
the_stack_v2_python_sparse
importer/downloaders/s3.py
kflavin/importer
train
0
ab80c9e5d02cfb5a6ad51cac6a49ab411561c637
[ "try:\n user = User.objects.get(email=username)\n if user.check_password(password):\n return user\n return None\nexcept User.DoesNotExist:\n return None", "try:\n return User.objects.get(pk=user_id)\nexcept User.DoesnotExist:\n return None" ]
<|body_start_0|> try: user = User.objects.get(email=username) if user.check_password(password): return user return None except User.DoesNotExist: return None <|end_body_0|> <|body_start_1|> try: return User.objects.get(...
Authenticate using e-mail account
EmailAuthBackend
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EmailAuthBackend: """Authenticate using e-mail account""" def authenticate(self, username=None, password=None): """Takes user credentials as parameters. Return true if the user has been authenticated, or false otherwise""" <|body_0|> def get_user(self, user_id): ...
stack_v2_sparse_classes_36k_train_007295
1,351
no_license
[ { "docstring": "Takes user credentials as parameters. Return true if the user has been authenticated, or false otherwise", "name": "authenticate", "signature": "def authenticate(self, username=None, password=None)" }, { "docstring": "takes a user ID parameter and has to return a User object", ...
2
stack_v2_sparse_classes_30k_train_016321
Implement the Python class `EmailAuthBackend` described below. Class description: Authenticate using e-mail account Method signatures and docstrings: - def authenticate(self, username=None, password=None): Takes user credentials as parameters. Return true if the user has been authenticated, or false otherwise - def g...
Implement the Python class `EmailAuthBackend` described below. Class description: Authenticate using e-mail account Method signatures and docstrings: - def authenticate(self, username=None, password=None): Takes user credentials as parameters. Return true if the user has been authenticated, or false otherwise - def g...
ccdc059c6590aa17115ae7af9ed8aff8cd0e5d1c
<|skeleton|> class EmailAuthBackend: """Authenticate using e-mail account""" def authenticate(self, username=None, password=None): """Takes user credentials as parameters. Return true if the user has been authenticated, or false otherwise""" <|body_0|> def get_user(self, user_id): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EmailAuthBackend: """Authenticate using e-mail account""" def authenticate(self, username=None, password=None): """Takes user credentials as parameters. Return true if the user has been authenticated, or false otherwise""" try: user = User.objects.get(email=username) ...
the_stack_v2_python_sparse
account/authentication.py
extremewaysback/origin
train
0
d10a819c69ab93c29fefaaf9c9639187fc87daf7
[ "if _debug:\n ConfigArgumentParser._debug('__init__')\nArgumentParser.__init__(self, **kwargs)\nself.add_argument('--ini', help='device object configuration file', default=BACPYPES_INI)", "if _debug:\n ConfigArgumentParser._debug('parse_args')\nresult_args = ArgumentParser.parse_args(self, *args, **kwargs)\...
<|body_start_0|> if _debug: ConfigArgumentParser._debug('__init__') ArgumentParser.__init__(self, **kwargs) self.add_argument('--ini', help='device object configuration file', default=BACPYPES_INI) <|end_body_0|> <|body_start_1|> if _debug: ConfigArgumentParser._...
ConfigArgumentParser extends the ArgumentParser with the functionality to read in a configuration file. --ini INI provide a separate INI file
ConfigArgumentParser
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ConfigArgumentParser: """ConfigArgumentParser extends the ArgumentParser with the functionality to read in a configuration file. --ini INI provide a separate INI file""" def __init__(self, **kwargs): """Follow normal initialization and add BACpypes arguments.""" <|body_0|> ...
stack_v2_sparse_classes_36k_train_007296
7,777
permissive
[ { "docstring": "Follow normal initialization and add BACpypes arguments.", "name": "__init__", "signature": "def __init__(self, **kwargs)" }, { "docstring": "Parse the arguments as usual, then add default processing.", "name": "parse_args", "signature": "def parse_args(self, *args, **kwa...
2
stack_v2_sparse_classes_30k_train_008299
Implement the Python class `ConfigArgumentParser` described below. Class description: ConfigArgumentParser extends the ArgumentParser with the functionality to read in a configuration file. --ini INI provide a separate INI file Method signatures and docstrings: - def __init__(self, **kwargs): Follow normal initializa...
Implement the Python class `ConfigArgumentParser` described below. Class description: ConfigArgumentParser extends the ArgumentParser with the functionality to read in a configuration file. --ini INI provide a separate INI file Method signatures and docstrings: - def __init__(self, **kwargs): Follow normal initializa...
a5be2ad5ac69821c12299716b167dd52041b5342
<|skeleton|> class ConfigArgumentParser: """ConfigArgumentParser extends the ArgumentParser with the functionality to read in a configuration file. --ini INI provide a separate INI file""" def __init__(self, **kwargs): """Follow normal initialization and add BACpypes arguments.""" <|body_0|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ConfigArgumentParser: """ConfigArgumentParser extends the ArgumentParser with the functionality to read in a configuration file. --ini INI provide a separate INI file""" def __init__(self, **kwargs): """Follow normal initialization and add BACpypes arguments.""" if _debug: Con...
the_stack_v2_python_sparse
py25/bacpypes/consolelogging.py
JoelBender/bacpypes
train
284
7847af750b4040f9e79375a5d642abef487a1534
[ "self.pblstm = layer.PBLSTMLayer(int(conf['listener_numunits']))\nself.blstm = layer.BLSTMLayer(int(conf['listener_numunits']))\nsuper(Listener, self).__init__(conf, name)", "outputs = inputs\noutput_seq_lengths = sequence_lengths\nfor l in range(int(self.conf['listener_numlayers'])):\n outputs, output_seq_len...
<|body_start_0|> self.pblstm = layer.PBLSTMLayer(int(conf['listener_numunits'])) self.blstm = layer.BLSTMLayer(int(conf['listener_numunits'])) super(Listener, self).__init__(conf, name) <|end_body_0|> <|body_start_1|> outputs = inputs output_seq_lengths = sequence_lengths ...
a listener object transforms input features into a high level representation
Listener
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Listener: """a listener object transforms input features into a high level representation""" def __init__(self, conf, name=None): """Listener constructor Args: numlayers: the number of PBLSTM layers numunits: the number of units in each layer dropout: the dropout rate name: the name ...
stack_v2_sparse_classes_36k_train_007297
2,095
permissive
[ { "docstring": "Listener constructor Args: numlayers: the number of PBLSTM layers numunits: the number of units in each layer dropout: the dropout rate name: the name of the Listener", "name": "__init__", "signature": "def __init__(self, conf, name=None)" }, { "docstring": "get the high level fe...
2
stack_v2_sparse_classes_30k_train_021375
Implement the Python class `Listener` described below. Class description: a listener object transforms input features into a high level representation Method signatures and docstrings: - def __init__(self, conf, name=None): Listener constructor Args: numlayers: the number of PBLSTM layers numunits: the number of unit...
Implement the Python class `Listener` described below. Class description: a listener object transforms input features into a high level representation Method signatures and docstrings: - def __init__(self, conf, name=None): Listener constructor Args: numlayers: the number of PBLSTM layers numunits: the number of unit...
fb530cf617ff86fe8a249d4582dfe90a303da295
<|skeleton|> class Listener: """a listener object transforms input features into a high level representation""" def __init__(self, conf, name=None): """Listener constructor Args: numlayers: the number of PBLSTM layers numunits: the number of units in each layer dropout: the dropout rate name: the name ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Listener: """a listener object transforms input features into a high level representation""" def __init__(self, conf, name=None): """Listener constructor Args: numlayers: the number of PBLSTM layers numunits: the number of units in each layer dropout: the dropout rate name: the name of the Listen...
the_stack_v2_python_sparse
nabu/neuralnetworks/classifiers/asr/encoders/listener.py
DavidKarlas/nabu
train
1
466b8c6fc8c57b410a4b00396c8ab34cf561a927
[ "visited = []\nresult = []\nfor i in range(0, len(nums)):\n curr = nums[len(nums) - i - 1]\n count = bisect.bisect(visited, curr)\n while count > 0 and visited[count - 1] == curr:\n count = count - 1\n bisect.insort(visited, curr)\n result.append(count)\nresult.reverse()\nreturn result", "ra...
<|body_start_0|> visited = [] result = [] for i in range(0, len(nums)): curr = nums[len(nums) - i - 1] count = bisect.bisect(visited, curr) while count > 0 and visited[count - 1] == curr: count = count - 1 bisect.insort(visited, cur...
Solution_1
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution_1: def countSmaller(self, nums): """:type nums: List[int] :rtype: List[int] 208ms""" <|body_0|> def countSmaller_1(self, nums): """165ms :param nums: :return:""" <|body_1|> <|end_skeleton|> <|body_start_0|> visited = [] result = [] ...
stack_v2_sparse_classes_36k_train_007298
2,655
no_license
[ { "docstring": ":type nums: List[int] :rtype: List[int] 208ms", "name": "countSmaller", "signature": "def countSmaller(self, nums)" }, { "docstring": "165ms :param nums: :return:", "name": "countSmaller_1", "signature": "def countSmaller_1(self, nums)" } ]
2
null
Implement the Python class `Solution_1` described below. Class description: Implement the Solution_1 class. Method signatures and docstrings: - def countSmaller(self, nums): :type nums: List[int] :rtype: List[int] 208ms - def countSmaller_1(self, nums): 165ms :param nums: :return:
Implement the Python class `Solution_1` described below. Class description: Implement the Solution_1 class. Method signatures and docstrings: - def countSmaller(self, nums): :type nums: List[int] :rtype: List[int] 208ms - def countSmaller_1(self, nums): 165ms :param nums: :return: <|skeleton|> class Solution_1: ...
679a2b246b8b6bb7fc55ed1c8096d3047d6d4461
<|skeleton|> class Solution_1: def countSmaller(self, nums): """:type nums: List[int] :rtype: List[int] 208ms""" <|body_0|> def countSmaller_1(self, nums): """165ms :param nums: :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution_1: def countSmaller(self, nums): """:type nums: List[int] :rtype: List[int] 208ms""" visited = [] result = [] for i in range(0, len(nums)): curr = nums[len(nums) - i - 1] count = bisect.bisect(visited, curr) while count > 0 and visit...
the_stack_v2_python_sparse
CountOfSmallerNumbersAfterSelf_HARD_315.py
953250587/leetcode-python
train
2
a626a9a56a02f87d97b7dc242bbcc957c99f69ad
[ "DenseVectorPrf.__init__(self)\nself.encoder = encoder\nself.sparse_searcher = sparse_searcher", "passage_texts = [query]\nfor item in prf_candidates:\n raw_text = json.loads(self.sparse_searcher.doc(item.docid).raw())\n passage_texts.append(raw_text['contents'])\nfull_text = f'{self.encoder.tokenizer.cls_t...
<|body_start_0|> DenseVectorPrf.__init__(self) self.encoder = encoder self.sparse_searcher = sparse_searcher <|end_body_0|> <|body_start_1|> passage_texts = [query] for item in prf_candidates: raw_text = json.loads(self.sparse_searcher.doc(item.docid).raw()) ...
DenseVectorAncePrf
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DenseVectorAncePrf: def __init__(self, encoder: AnceQueryEncoder, sparse_searcher: LuceneSearcher): """Parameters ---------- encoder : AnceQueryEncoder The new ANCE query encoder for ANCE-PRF. sparse_searcher : LuceneSearcher The sparse searcher using lucene index, for retrieving doc con...
stack_v2_sparse_classes_36k_train_007299
7,539
permissive
[ { "docstring": "Parameters ---------- encoder : AnceQueryEncoder The new ANCE query encoder for ANCE-PRF. sparse_searcher : LuceneSearcher The sparse searcher using lucene index, for retrieving doc contents.", "name": "__init__", "signature": "def __init__(self, encoder: AnceQueryEncoder, sparse_searche...
3
stack_v2_sparse_classes_30k_train_018147
Implement the Python class `DenseVectorAncePrf` described below. Class description: Implement the DenseVectorAncePrf class. Method signatures and docstrings: - def __init__(self, encoder: AnceQueryEncoder, sparse_searcher: LuceneSearcher): Parameters ---------- encoder : AnceQueryEncoder The new ANCE query encoder fo...
Implement the Python class `DenseVectorAncePrf` described below. Class description: Implement the DenseVectorAncePrf class. Method signatures and docstrings: - def __init__(self, encoder: AnceQueryEncoder, sparse_searcher: LuceneSearcher): Parameters ---------- encoder : AnceQueryEncoder The new ANCE query encoder fo...
42b354914b230880c91b2e4e70605b472441a9a1
<|skeleton|> class DenseVectorAncePrf: def __init__(self, encoder: AnceQueryEncoder, sparse_searcher: LuceneSearcher): """Parameters ---------- encoder : AnceQueryEncoder The new ANCE query encoder for ANCE-PRF. sparse_searcher : LuceneSearcher The sparse searcher using lucene index, for retrieving doc con...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DenseVectorAncePrf: def __init__(self, encoder: AnceQueryEncoder, sparse_searcher: LuceneSearcher): """Parameters ---------- encoder : AnceQueryEncoder The new ANCE query encoder for ANCE-PRF. sparse_searcher : LuceneSearcher The sparse searcher using lucene index, for retrieving doc contents.""" ...
the_stack_v2_python_sparse
pyserini/search/faiss/_prf.py
castorini/pyserini
train
1,070