blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 467 8.64k | id stringlengths 40 40 | length_bytes int64 515 49.7k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 160 3.93k | prompted_full_text stringlengths 681 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.09k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 331 8.3k | source stringclasses 1
value | source_path stringlengths 5 177 | source_repo stringlengths 6 88 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3ee7a1bdc06202aa5754ffa2ad3dbf7763d4db3d | [
"self._get_current_time_fn = get_current_time_fn\nself._archive_data_source = archive_data_source\nself._trigger_pvs = [config.trigger_pv for config in configs]\nself._time_last_active = time_last_active\nsearch_for_change_from, self._last_sample_id_for_time = time_last_active.get()\ninitial_data_values = archive_d... | <|body_start_0|>
self._get_current_time_fn = get_current_time_fn
self._archive_data_source = archive_data_source
self._trigger_pvs = [config.trigger_pv for config in configs]
self._time_last_active = time_last_active
search_for_change_from, self._last_sample_id_for_time = time_la... | Initiate the writing of a log file based on the change of a PV. | LogFileInitiatorOnPVChange | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogFileInitiatorOnPVChange:
"""Initiate the writing of a log file based on the change of a PV."""
def __init__(self, configs, archive_data_source, time_last_active, get_current_time_fn=utc_time_now, data_file_creator_factory=DataFileCreatorFactory()):
"""Args: configs(list[ArchiverAc... | stack_v2_sparse_classes_10k_train_006700 | 11,537 | permissive | [
{
"docstring": "Args: configs(list[ArchiverAccess.archive_access_configuration.ArchiveAccessConfig]): list of configs archive_data_source(ArchiverAccess.archiver_data_source.ArchiverDataSource): data source time_last_active(ArchiverAccess.time_last_active.TimeLastActive): provider for the time from which to sea... | 3 | null | Implement the Python class `LogFileInitiatorOnPVChange` described below.
Class description:
Initiate the writing of a log file based on the change of a PV.
Method signatures and docstrings:
- def __init__(self, configs, archive_data_source, time_last_active, get_current_time_fn=utc_time_now, data_file_creator_factory... | Implement the Python class `LogFileInitiatorOnPVChange` described below.
Class description:
Initiate the writing of a log file based on the change of a PV.
Method signatures and docstrings:
- def __init__(self, configs, archive_data_source, time_last_active, get_current_time_fn=utc_time_now, data_file_creator_factory... | 2e605cbff1cfe071571a64bed61708d8c92dc204 | <|skeleton|>
class LogFileInitiatorOnPVChange:
"""Initiate the writing of a log file based on the change of a PV."""
def __init__(self, configs, archive_data_source, time_last_active, get_current_time_fn=utc_time_now, data_file_creator_factory=DataFileCreatorFactory()):
"""Args: configs(list[ArchiverAc... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LogFileInitiatorOnPVChange:
"""Initiate the writing of a log file based on the change of a PV."""
def __init__(self, configs, archive_data_source, time_last_active, get_current_time_fn=utc_time_now, data_file_creator_factory=DataFileCreatorFactory()):
"""Args: configs(list[ArchiverAccess.archive_... | the_stack_v2_python_sparse | ArchiverAccess/log_file_initiator.py | ISISComputingGroup/EPICS-inst_servers | train | 1 |
4a0521e733d7580ef3eba6519f3e26a369b68637 | [
"super().__init__()\nself.spherical_cheb_bn_pool = SphericalChebBNPool(in_channels, out_channels, lap, pooling, kernel_size)\nself.spherical_cheb_bn = SphericalChebBN(in_channels + out_channels, out_channels, lap, kernel_size)",
"x = self.spherical_cheb_bn_pool(x)\nx = torch.cat((x, concat_data), dim=2)\nx = self... | <|body_start_0|>
super().__init__()
self.spherical_cheb_bn_pool = SphericalChebBNPool(in_channels, out_channels, lap, pooling, kernel_size)
self.spherical_cheb_bn = SphericalChebBN(in_channels + out_channels, out_channels, lap, kernel_size)
<|end_body_0|>
<|body_start_1|>
x = self.spher... | Building Block calling a SphericalChebBNPool Block then concatenating the output with another tensor and calling a SphericalChebBN block. | SphericalChebBNPoolConcat | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SphericalChebBNPoolConcat:
"""Building Block calling a SphericalChebBNPool Block then concatenating the output with another tensor and calling a SphericalChebBN block."""
def __init__(self, in_channels, out_channels, lap, pooling, kernel_size):
"""Initialization. Args: in_channels (i... | stack_v2_sparse_classes_10k_train_006701 | 41,403 | no_license | [
{
"docstring": "Initialization. Args: in_channels (int): initial number of channels. out_channels (int): output number of channels. lap (:obj:`torch.sparse.FloatTensor`): laplacian. pooling (:obj:`torch.nn.Module`): pooling/unpooling module. kernel_size (int, optional): polynomial degree. Defaults to 3.",
"... | 2 | null | Implement the Python class `SphericalChebBNPoolConcat` described below.
Class description:
Building Block calling a SphericalChebBNPool Block then concatenating the output with another tensor and calling a SphericalChebBN block.
Method signatures and docstrings:
- def __init__(self, in_channels, out_channels, lap, po... | Implement the Python class `SphericalChebBNPoolConcat` described below.
Class description:
Building Block calling a SphericalChebBNPool Block then concatenating the output with another tensor and calling a SphericalChebBN block.
Method signatures and docstrings:
- def __init__(self, in_channels, out_channels, lap, po... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class SphericalChebBNPoolConcat:
"""Building Block calling a SphericalChebBNPool Block then concatenating the output with another tensor and calling a SphericalChebBN block."""
def __init__(self, in_channels, out_channels, lap, pooling, kernel_size):
"""Initialization. Args: in_channels (i... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SphericalChebBNPoolConcat:
"""Building Block calling a SphericalChebBNPool Block then concatenating the output with another tensor and calling a SphericalChebBN block."""
def __init__(self, in_channels, out_channels, lap, pooling, kernel_size):
"""Initialization. Args: in_channels (int): initial ... | the_stack_v2_python_sparse | generated/test_deepsphere_deepsphere_pytorch.py | jansel/pytorch-jit-paritybench | train | 35 |
0618702a8cf656c2469e54df5f42e60ee222b728 | [
"sn = len(s)\ntn = len(t)\nlists = []\nlistt = []\nif sn != tn:\n return False\nfor i in range(0, sn):\n lists.append(s[i])\nfor j in range(0, tn):\n listt.append(t[j])\nlistt.sort()\nlists.sort()\nif lists == listt:\n return True\nelse:\n return False",
"\"\"\"\n 思路:定义一个26长度的列表,每个元素都是0,在s中进... | <|body_start_0|>
sn = len(s)
tn = len(t)
lists = []
listt = []
if sn != tn:
return False
for i in range(0, sn):
lists.append(s[i])
for j in range(0, tn):
listt.append(t[j])
listt.sort()
lists.sort()
if li... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isAnagram(self, s, t):
""":type s: str :type t: str :rtype: bool"""
<|body_0|>
def isAnagram2(self, s, t):
""":type s: str :type t: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
sn = len(s)
tn = len(t)
... | stack_v2_sparse_classes_10k_train_006702 | 1,833 | no_license | [
{
"docstring": ":type s: str :type t: str :rtype: bool",
"name": "isAnagram",
"signature": "def isAnagram(self, s, t)"
},
{
"docstring": ":type s: str :type t: str :rtype: bool",
"name": "isAnagram2",
"signature": "def isAnagram2(self, s, t)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004523 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isAnagram(self, s, t): :type s: str :type t: str :rtype: bool
- def isAnagram2(self, s, t): :type s: str :type t: str :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isAnagram(self, s, t): :type s: str :type t: str :rtype: bool
- def isAnagram2(self, s, t): :type s: str :type t: str :rtype: bool
<|skeleton|>
class Solution:
def isAn... | c2250f2c7365976a6767e3c12760474f7a6618eb | <|skeleton|>
class Solution:
def isAnagram(self, s, t):
""":type s: str :type t: str :rtype: bool"""
<|body_0|>
def isAnagram2(self, s, t):
""":type s: str :type t: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def isAnagram(self, s, t):
""":type s: str :type t: str :rtype: bool"""
sn = len(s)
tn = len(t)
lists = []
listt = []
if sn != tn:
return False
for i in range(0, sn):
lists.append(s[i])
for j in range(0, tn):
... | the_stack_v2_python_sparse | 242. Valid Anagram/242. Valid Anagram.py | yaolinxia/leetcode_study | train | 0 | |
b39c2636ecc0a419bab3a42117f8392ed86c90ea | [
"nph = NumpyHist.getFromRoot(h)\nif np.isnan(nph.w).any():\n logging.warning('Warning : nan found in hist %s' % h.GetName())\n return None\nif not hasattr(self, 'ne'):\n raise RuntimeError('New bin edges have not been computed, is the rebin_method() not implemented ?')\nreturn nph.rebin(self.ne).fillHistog... | <|body_start_0|>
nph = NumpyHist.getFromRoot(h)
if np.isnan(nph.w).any():
logging.warning('Warning : nan found in hist %s' % h.GetName())
return None
if not hasattr(self, 'ne'):
raise RuntimeError('New bin edges have not been computed, is the rebin_method() no... | Base rebin method includes common methods to rebin, extract and fill histograms | Rebin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Rebin:
"""Base rebin method includes common methods to rebin, extract and fill histograms"""
def __call__(self, h):
"""input : initial histogram TH1 return : rebinned TH1"""
<|body_0|>
def _processHist(h):
"""Input : h, can be - ROOT.TH1X - NumpyHist already - li... | stack_v2_sparse_classes_10k_train_006703 | 35,100 | no_license | [
{
"docstring": "input : initial histogram TH1 return : rebinned TH1",
"name": "__call__",
"signature": "def __call__(self, h)"
},
{
"docstring": "Input : h, can be - ROOT.TH1X - NumpyHist already - list of ROOT.TH1X or NumpyHist return : NumpyHist object",
"name": "_processHist",
"signat... | 2 | stack_v2_sparse_classes_30k_train_007086 | Implement the Python class `Rebin` described below.
Class description:
Base rebin method includes common methods to rebin, extract and fill histograms
Method signatures and docstrings:
- def __call__(self, h): input : initial histogram TH1 return : rebinned TH1
- def _processHist(h): Input : h, can be - ROOT.TH1X - N... | Implement the Python class `Rebin` described below.
Class description:
Base rebin method includes common methods to rebin, extract and fill histograms
Method signatures and docstrings:
- def __call__(self, h): input : initial histogram TH1 return : rebinned TH1
- def _processHist(h): Input : h, can be - ROOT.TH1X - N... | 30df434202df51017309b5bf88a1d9b94041b6ef | <|skeleton|>
class Rebin:
"""Base rebin method includes common methods to rebin, extract and fill histograms"""
def __call__(self, h):
"""input : initial histogram TH1 return : rebinned TH1"""
<|body_0|>
def _processHist(h):
"""Input : h, can be - ROOT.TH1X - NumpyHist already - li... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Rebin:
"""Base rebin method includes common methods to rebin, extract and fill histograms"""
def __call__(self, h):
"""input : initial histogram TH1 return : rebinned TH1"""
nph = NumpyHist.getFromRoot(h)
if np.isnan(nph.w).any():
logging.warning('Warning : nan found i... | the_stack_v2_python_sparse | ZAStatAnalysis/Rebinning.py | kjaffel/ZA_FullAnalysis | train | 11 |
e7cf8eb9189aaba3a0bcd92ba39c3af2b0c95e7b | [
"ret = [0]\nfor i in range(1, len(pattern)):\n print('剛入range後i', i)\n j = ret[i - 1]\n print('j', j)\n while j > 0 and pattern[j] != pattern[i]:\n print('j', j)\n j = ret[j - 1]\n print('while j > 0 and pattern[j] != pattern[i]:時j ', j)\n print('i', 'j', i, j)\n ret.append(j ... | <|body_start_0|>
ret = [0]
for i in range(1, len(pattern)):
print('剛入range後i', i)
j = ret[i - 1]
print('j', j)
while j > 0 and pattern[j] != pattern[i]:
print('j', j)
j = ret[j - 1]
print('while j > 0 and pat... | KMP | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KMP:
def partial(self, pattern):
"""Calculate partial match table: String -> [Int]"""
<|body_0|>
def search(self, T, P):
"""KMP search main algorithm: String -> String -> [Int] Return all the matching position of pattern string P in T"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_10k_train_006704 | 1,672 | no_license | [
{
"docstring": "Calculate partial match table: String -> [Int]",
"name": "partial",
"signature": "def partial(self, pattern)"
},
{
"docstring": "KMP search main algorithm: String -> String -> [Int] Return all the matching position of pattern string P in T",
"name": "search",
"signature":... | 2 | stack_v2_sparse_classes_30k_train_005612 | Implement the Python class `KMP` described below.
Class description:
Implement the KMP class.
Method signatures and docstrings:
- def partial(self, pattern): Calculate partial match table: String -> [Int]
- def search(self, T, P): KMP search main algorithm: String -> String -> [Int] Return all the matching position o... | Implement the Python class `KMP` described below.
Class description:
Implement the KMP class.
Method signatures and docstrings:
- def partial(self, pattern): Calculate partial match table: String -> [Int]
- def search(self, T, P): KMP search main algorithm: String -> String -> [Int] Return all the matching position o... | a54bd09f4b28f106196a6cd8a0f9c056bcd237e6 | <|skeleton|>
class KMP:
def partial(self, pattern):
"""Calculate partial match table: String -> [Int]"""
<|body_0|>
def search(self, T, P):
"""KMP search main algorithm: String -> String -> [Int] Return all the matching position of pattern string P in T"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class KMP:
def partial(self, pattern):
"""Calculate partial match table: String -> [Int]"""
ret = [0]
for i in range(1, len(pattern)):
print('剛入range後i', i)
j = ret[i - 1]
print('j', j)
while j > 0 and pattern[j] != pattern[i]:
... | the_stack_v2_python_sparse | algorithm/KMP/KMP_github.py | luyihsien/leetcodepy | train | 0 | |
737d9a4e631096ec48bf477f265f3869d285174c | [
"super().__init__(machine, name)\nself.shows_queue = deque()\nself._current_show = None",
"self.shows_queue.append((show_config, start_step))\nif not self._current_show:\n self._play_next_show()",
"if not self.shows_queue:\n self._current_show = None\n return\nshow_config, start_step = self.shows_queue... | <|body_start_0|>
super().__init__(machine, name)
self.shows_queue = deque()
self._current_show = None
<|end_body_0|>
<|body_start_1|>
self.shows_queue.append((show_config, start_step))
if not self._current_show:
self._play_next_show()
<|end_body_1|>
<|body_start_2|>... | Represents a show queue. | ShowQueue | [
"MIT",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShowQueue:
"""Represents a show queue."""
def __init__(self, machine, name):
"""Initialise show queue."""
<|body_0|>
def enqueue_show(self, show_config: ShowConfig, start_step: int):
"""Add a show to the end of the queue."""
<|body_1|>
def _play_next... | stack_v2_sparse_classes_10k_train_006705 | 1,602 | permissive | [
{
"docstring": "Initialise show queue.",
"name": "__init__",
"signature": "def __init__(self, machine, name)"
},
{
"docstring": "Add a show to the end of the queue.",
"name": "enqueue_show",
"signature": "def enqueue_show(self, show_config: ShowConfig, start_step: int)"
},
{
"doc... | 3 | null | Implement the Python class `ShowQueue` described below.
Class description:
Represents a show queue.
Method signatures and docstrings:
- def __init__(self, machine, name): Initialise show queue.
- def enqueue_show(self, show_config: ShowConfig, start_step: int): Add a show to the end of the queue.
- def _play_next_sho... | Implement the Python class `ShowQueue` described below.
Class description:
Represents a show queue.
Method signatures and docstrings:
- def __init__(self, machine, name): Initialise show queue.
- def enqueue_show(self, show_config: ShowConfig, start_step: int): Add a show to the end of the queue.
- def _play_next_sho... | 9f90c8b1586363b65340017bfa3af5d56d32c6d9 | <|skeleton|>
class ShowQueue:
"""Represents a show queue."""
def __init__(self, machine, name):
"""Initialise show queue."""
<|body_0|>
def enqueue_show(self, show_config: ShowConfig, start_step: int):
"""Add a show to the end of the queue."""
<|body_1|>
def _play_next... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ShowQueue:
"""Represents a show queue."""
def __init__(self, machine, name):
"""Initialise show queue."""
super().__init__(machine, name)
self.shows_queue = deque()
self._current_show = None
def enqueue_show(self, show_config: ShowConfig, start_step: int):
"""... | the_stack_v2_python_sparse | mpf/devices/show_queue.py | missionpinball/mpf | train | 191 |
075fdae4ade922f2048baa054a77b1d7704c184b | [
"hook_event = request.META.get('HTTP_X_GITHUB_EVENT')\nif hook_event == 'ping':\n return HttpResponse()\nelif hook_event != 'push':\n return HttpResponseBadRequest('Only \"ping\" and \"push\" events are supported.')\nrepository = get_repository_for_hook(repository_id, hosting_service_id, local_site_name)\nm =... | <|body_start_0|>
hook_event = request.META.get('HTTP_X_GITHUB_EVENT')
if hook_event == 'ping':
return HttpResponse()
elif hook_event != 'push':
return HttpResponseBadRequest('Only "ping" and "push" events are supported.')
repository = get_repository_for_hook(repos... | Container class for hook views. | GitHubHookViews | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GitHubHookViews:
"""Container class for hook views."""
def post_receive_hook_close_submitted(request, local_site_name=None, repository_id=None, hosting_service_id=None):
"""Close review requests as submitted automatically after a push. Args: request (django.http.HttpRequest): The req... | stack_v2_sparse_classes_10k_train_006706 | 42,594 | permissive | [
{
"docstring": "Close review requests as submitted automatically after a push. Args: request (django.http.HttpRequest): The request from the Bitbucket webhook. local_site_name (unicode): The local site name, if available. repository_id (int): The pk of the repository, if available. hosting_service_id (unicode):... | 2 | stack_v2_sparse_classes_30k_train_003412 | Implement the Python class `GitHubHookViews` described below.
Class description:
Container class for hook views.
Method signatures and docstrings:
- def post_receive_hook_close_submitted(request, local_site_name=None, repository_id=None, hosting_service_id=None): Close review requests as submitted automatically after... | Implement the Python class `GitHubHookViews` described below.
Class description:
Container class for hook views.
Method signatures and docstrings:
- def post_receive_hook_close_submitted(request, local_site_name=None, repository_id=None, hosting_service_id=None): Close review requests as submitted automatically after... | c3a991f1e9d7682239a1ab0e8661cee6da01d537 | <|skeleton|>
class GitHubHookViews:
"""Container class for hook views."""
def post_receive_hook_close_submitted(request, local_site_name=None, repository_id=None, hosting_service_id=None):
"""Close review requests as submitted automatically after a push. Args: request (django.http.HttpRequest): The req... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GitHubHookViews:
"""Container class for hook views."""
def post_receive_hook_close_submitted(request, local_site_name=None, repository_id=None, hosting_service_id=None):
"""Close review requests as submitted automatically after a push. Args: request (django.http.HttpRequest): The request from the... | the_stack_v2_python_sparse | reviewboard/hostingsvcs/github.py | reviewboard/reviewboard | train | 1,141 |
e5077a26d041cc9bbed47296fc66fa74cea5ead3 | [
"input_size = common.tuplify2d(input_size)\nsuper().__init__(input_tensor_spec=TensorSpec((input_channels,) + input_size), name=name)\nassert isinstance(conv_layer_params, tuple)\nassert len(conv_layer_params) > 0\nif kernel_initializer is None:\n kernel_initializer = functools.partial(variance_scaling_init, mod... | <|body_start_0|>
input_size = common.tuplify2d(input_size)
super().__init__(input_tensor_spec=TensorSpec((input_channels,) + input_size), name=name)
assert isinstance(conv_layer_params, tuple)
assert len(conv_layer_params) > 0
if kernel_initializer is None:
kernel_ini... | ParamConvNet | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParamConvNet:
def __init__(self, input_channels, input_size, conv_layer_params, same_padding=False, activation=torch.relu_, use_bias=False, use_ln=False, n_groups=None, kernel_initializer=None, flatten_output=False, name='ParamConvNet'):
"""A fully 2D conv network that does not maintain ... | stack_v2_sparse_classes_10k_train_006707 | 14,523 | permissive | [
{
"docstring": "A fully 2D conv network that does not maintain its own network parameters, but accepts them from users. If the given parameter tensor has an extra batch dimension (first dimension), it performs parallel operations. Args: input_channels (int): number of channels in the input image input_size (int... | 4 | null | Implement the Python class `ParamConvNet` described below.
Class description:
Implement the ParamConvNet class.
Method signatures and docstrings:
- def __init__(self, input_channels, input_size, conv_layer_params, same_padding=False, activation=torch.relu_, use_bias=False, use_ln=False, n_groups=None, kernel_initiali... | Implement the Python class `ParamConvNet` described below.
Class description:
Implement the ParamConvNet class.
Method signatures and docstrings:
- def __init__(self, input_channels, input_size, conv_layer_params, same_padding=False, activation=torch.relu_, use_bias=False, use_ln=False, n_groups=None, kernel_initiali... | b00ff2fa5e660de31020338ba340263183fbeaa4 | <|skeleton|>
class ParamConvNet:
def __init__(self, input_channels, input_size, conv_layer_params, same_padding=False, activation=torch.relu_, use_bias=False, use_ln=False, n_groups=None, kernel_initializer=None, flatten_output=False, name='ParamConvNet'):
"""A fully 2D conv network that does not maintain ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ParamConvNet:
def __init__(self, input_channels, input_size, conv_layer_params, same_padding=False, activation=torch.relu_, use_bias=False, use_ln=False, n_groups=None, kernel_initializer=None, flatten_output=False, name='ParamConvNet'):
"""A fully 2D conv network that does not maintain its own networ... | the_stack_v2_python_sparse | alf/networks/param_networks.py | HorizonRobotics/alf | train | 288 | |
864e4628421c89ff3cbddebaefdd7b201b3f85b5 | [
"parser = ParlaiParser(True, True, 'Index Dense Embs')\nparser.add_argument('--embeddings-dir', type=str, help='directory of embeddings')\nparser.add_argument('--embeddings-name', type=str, default='', help='name of emb part')\nparser.add_argument('--partition-index', type='bool', default=False, help='specify True ... | <|body_start_0|>
parser = ParlaiParser(True, True, 'Index Dense Embs')
parser.add_argument('--embeddings-dir', type=str, help='directory of embeddings')
parser.add_argument('--embeddings-name', type=str, default='', help='name of emb part')
parser.add_argument('--partition-index', type='... | Index Dense Embeddings. | Indexer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Indexer:
"""Index Dense Embeddings."""
def setup_args(cls):
"""Setup args."""
<|body_0|>
def run(self):
"""Load dense embeddings and index with FAISS."""
<|body_1|>
def index_data(self, input_files: List[str], add_only: bool=False):
"""Index ... | stack_v2_sparse_classes_10k_train_006708 | 4,832 | permissive | [
{
"docstring": "Setup args.",
"name": "setup_args",
"signature": "def setup_args(cls)"
},
{
"docstring": "Load dense embeddings and index with FAISS.",
"name": "run",
"signature": "def run(self)"
},
{
"docstring": "Index data. :param input_files: files to load.",
"name": "ind... | 4 | null | Implement the Python class `Indexer` described below.
Class description:
Index Dense Embeddings.
Method signatures and docstrings:
- def setup_args(cls): Setup args.
- def run(self): Load dense embeddings and index with FAISS.
- def index_data(self, input_files: List[str], add_only: bool=False): Index data. :param in... | Implement the Python class `Indexer` described below.
Class description:
Index Dense Embeddings.
Method signatures and docstrings:
- def setup_args(cls): Setup args.
- def run(self): Load dense embeddings and index with FAISS.
- def index_data(self, input_files: List[str], add_only: bool=False): Index data. :param in... | e1d899edfb92471552bae153f59ad30aa7fca468 | <|skeleton|>
class Indexer:
"""Index Dense Embeddings."""
def setup_args(cls):
"""Setup args."""
<|body_0|>
def run(self):
"""Load dense embeddings and index with FAISS."""
<|body_1|>
def index_data(self, input_files: List[str], add_only: bool=False):
"""Index ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Indexer:
"""Index Dense Embeddings."""
def setup_args(cls):
"""Setup args."""
parser = ParlaiParser(True, True, 'Index Dense Embs')
parser.add_argument('--embeddings-dir', type=str, help='directory of embeddings')
parser.add_argument('--embeddings-name', type=str, default=... | the_stack_v2_python_sparse | parlai/agents/rag/scripts/index_dense_embeddings.py | facebookresearch/ParlAI | train | 10,943 |
12a28e1512f472e02f759f89186f17763f6ecca8 | [
"super(_IterationPhaseInferCommon, self).__init__(nIters=nIters)\nself._model = model\nself._inferenceArgs = inferenceArgs\nreturn",
"super(_IterationPhaseInferCommon, self).enterPhase()\nself._model.enableInference(inferenceArgs=self._inferenceArgs)\nreturn"
] | <|body_start_0|>
super(_IterationPhaseInferCommon, self).__init__(nIters=nIters)
self._model = model
self._inferenceArgs = inferenceArgs
return
<|end_body_0|>
<|body_start_1|>
super(_IterationPhaseInferCommon, self).enterPhase()
self._model.enableInference(inferenceArgs=... | Basic class providing common implementation for _IterationPhaseInferOnly and _IterationPhaseLearnAndInfer classes | _IterationPhaseInferCommon | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _IterationPhaseInferCommon:
"""Basic class providing common implementation for _IterationPhaseInferOnly and _IterationPhaseLearnAndInfer classes"""
def __init__(self, model, nIters, inferenceArgs):
"""model: Model instance nIters: Number of iterations; MUST be greater than 0 inferenc... | stack_v2_sparse_classes_10k_train_006709 | 16,958 | no_license | [
{
"docstring": "model: Model instance nIters: Number of iterations; MUST be greater than 0 inferenceArgs: A dictionary of arguments required for inference. These depend on the InferenceType of the current model",
"name": "__init__",
"signature": "def __init__(self, model, nIters, inferenceArgs)"
},
... | 2 | stack_v2_sparse_classes_30k_train_000384 | Implement the Python class `_IterationPhaseInferCommon` described below.
Class description:
Basic class providing common implementation for _IterationPhaseInferOnly and _IterationPhaseLearnAndInfer classes
Method signatures and docstrings:
- def __init__(self, model, nIters, inferenceArgs): model: Model instance nIte... | Implement the Python class `_IterationPhaseInferCommon` described below.
Class description:
Basic class providing common implementation for _IterationPhaseInferOnly and _IterationPhaseLearnAndInfer classes
Method signatures and docstrings:
- def __init__(self, model, nIters, inferenceArgs): model: Model instance nIte... | d494b3041069d377d6a7a9c296a14334f2fa5acc | <|skeleton|>
class _IterationPhaseInferCommon:
"""Basic class providing common implementation for _IterationPhaseInferOnly and _IterationPhaseLearnAndInfer classes"""
def __init__(self, model, nIters, inferenceArgs):
"""model: Model instance nIters: Number of iterations; MUST be greater than 0 inferenc... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class _IterationPhaseInferCommon:
"""Basic class providing common implementation for _IterationPhaseInferOnly and _IterationPhaseLearnAndInfer classes"""
def __init__(self, model, nIters, inferenceArgs):
"""model: Model instance nIters: Number of iterations; MUST be greater than 0 inferenceArgs: A dict... | the_stack_v2_python_sparse | python/numenta_nupic/nupic-master/src/nupic/frameworks/opf/opftaskdriver.py | LiuFang816/SALSTM_py_data | train | 10 |
2cf39ae831a923e80197608352057a8860df9d28 | [
"s, stack = ('', deque([root]))\nif root:\n while stack:\n node = stack.popleft()\n if node:\n s += str(node.val) + ','\n stack.append(node.left)\n stack.append(node.right)\n else:\n s += ' ,'\nreturn s[:-1]",
"x = deque(data.split(','))\nv = x.p... | <|body_start_0|>
s, stack = ('', deque([root]))
if root:
while stack:
node = stack.popleft()
if node:
s += str(node.val) + ','
stack.append(node.left)
stack.append(node.right)
else:
... | Q0297, check out listToTreeNode in @/src/config/treenode.py, which is exactly how deserialize work. | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
"""Q0297, check out listToTreeNode in @/src/config/treenode.py, which is exactly how deserialize work."""
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decod... | stack_v2_sparse_classes_10k_train_006710 | 2,340 | no_license | [
{
"docstring": "Encodes a tree to a single string.",
"name": "serialize",
"signature": "def serialize(self, root: TreeNode) -> str"
},
{
"docstring": "Decodes your encoded data to tree.",
"name": "deserialize",
"signature": "def deserialize(self, data: str) -> TreeNode"
}
] | 2 | null | Implement the Python class `Codec` described below.
Class description:
Q0297, check out listToTreeNode in @/src/config/treenode.py, which is exactly how deserialize work.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: st... | Implement the Python class `Codec` described below.
Class description:
Q0297, check out listToTreeNode in @/src/config/treenode.py, which is exactly how deserialize work.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: st... | 6043134736452a6f4704b62857d0aed2e9571164 | <|skeleton|>
class Codec:
"""Q0297, check out listToTreeNode in @/src/config/treenode.py, which is exactly how deserialize work."""
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decod... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Codec:
"""Q0297, check out listToTreeNode in @/src/config/treenode.py, which is exactly how deserialize work."""
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
s, stack = ('', deque([root]))
if root:
while stack:
no... | the_stack_v2_python_sparse | src/0400-0499/0449.serialize.deserialize.bst.py | gyang274/leetcode | train | 1 |
cfcea6e812f6ca96691730b7ce3c9e5bb034f6bb | [
"self.ip_address = ip_address\nself.port = port\nself.application_name = application_name",
"try:\n connection_url = 'tcp://' + self.ip_address + ':' + str(self.port)\n app = qi.Application([self.application_name, '--qi-url=' + connection_url])\nexcept RuntimeError:\n print('Can\\'t connect to Naoqi at i... | <|body_start_0|>
self.ip_address = ip_address
self.port = port
self.application_name = application_name
<|end_body_0|>
<|body_start_1|>
try:
connection_url = 'tcp://' + self.ip_address + ':' + str(self.port)
app = qi.Application([self.application_name, '--qi-url=... | QiApplication | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QiApplication:
def __init__(self, application_name, ip_address, port):
"""Initialise variables for connection"""
<|body_0|>
def connect(self):
"""Establish a Qi-application and connect to robot"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.ip... | stack_v2_sparse_classes_10k_train_006711 | 947 | no_license | [
{
"docstring": "Initialise variables for connection",
"name": "__init__",
"signature": "def __init__(self, application_name, ip_address, port)"
},
{
"docstring": "Establish a Qi-application and connect to robot",
"name": "connect",
"signature": "def connect(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005676 | Implement the Python class `QiApplication` described below.
Class description:
Implement the QiApplication class.
Method signatures and docstrings:
- def __init__(self, application_name, ip_address, port): Initialise variables for connection
- def connect(self): Establish a Qi-application and connect to robot | Implement the Python class `QiApplication` described below.
Class description:
Implement the QiApplication class.
Method signatures and docstrings:
- def __init__(self, application_name, ip_address, port): Initialise variables for connection
- def connect(self): Establish a Qi-application and connect to robot
<|skel... | ed3008d4ac864ec9c5b9384144c6a80c98c8c871 | <|skeleton|>
class QiApplication:
def __init__(self, application_name, ip_address, port):
"""Initialise variables for connection"""
<|body_0|>
def connect(self):
"""Establish a Qi-application and connect to robot"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class QiApplication:
def __init__(self, application_name, ip_address, port):
"""Initialise variables for connection"""
self.ip_address = ip_address
self.port = port
self.application_name = application_name
def connect(self):
"""Establish a Qi-application and connect to r... | the_stack_v2_python_sparse | mgribb3n-pepper-5bababb73a86/RobotServices/qiApplication.py | GustavSB/pepper-code | train | 0 | |
5ca7ea81e1e2fab1dae5cc8643c73c23e15e94cf | [
"super().__init__()\nself.conv = Conv2dHeadModel(image_shape=image_shape, channels=channels or [16, 32], kernel_sizes=kernel_sizes or [8, 4], strides=strides or [4, 2], paddings=paddings or [0, 1], use_maxpool=use_maxpool, hidden_sizes=fc_sizes)\nself.pi = torch.nn.Linear(self.conv.output_size, output_size)\nself.v... | <|body_start_0|>
super().__init__()
self.conv = Conv2dHeadModel(image_shape=image_shape, channels=channels or [16, 32], kernel_sizes=kernel_sizes or [8, 4], strides=strides or [4, 2], paddings=paddings or [0, 1], use_maxpool=use_maxpool, hidden_sizes=fc_sizes)
self.pi = torch.nn.Linear(self.conv... | Feedforward model for Atari agents: a convolutional network feeding an MLP with outputs for action probabilities and state-value estimate. | AtariFfModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AtariFfModel:
"""Feedforward model for Atari agents: a convolutional network feeding an MLP with outputs for action probabilities and state-value estimate."""
def __init__(self, image_shape, output_size, fc_sizes=512, use_maxpool=False, channels=None, kernel_sizes=None, strides=None, padding... | stack_v2_sparse_classes_10k_train_006712 | 2,373 | permissive | [
{
"docstring": "Instantiate neural net module according to inputs.",
"name": "__init__",
"signature": "def __init__(self, image_shape, output_size, fc_sizes=512, use_maxpool=False, channels=None, kernel_sizes=None, strides=None, paddings=None)"
},
{
"docstring": "Compute action probabilities and... | 2 | stack_v2_sparse_classes_30k_train_002356 | Implement the Python class `AtariFfModel` described below.
Class description:
Feedforward model for Atari agents: a convolutional network feeding an MLP with outputs for action probabilities and state-value estimate.
Method signatures and docstrings:
- def __init__(self, image_shape, output_size, fc_sizes=512, use_ma... | Implement the Python class `AtariFfModel` described below.
Class description:
Feedforward model for Atari agents: a convolutional network feeding an MLP with outputs for action probabilities and state-value estimate.
Method signatures and docstrings:
- def __init__(self, image_shape, output_size, fc_sizes=512, use_ma... | 98681a23bae9e8e5e9fbf68a0316ca2a22a27593 | <|skeleton|>
class AtariFfModel:
"""Feedforward model for Atari agents: a convolutional network feeding an MLP with outputs for action probabilities and state-value estimate."""
def __init__(self, image_shape, output_size, fc_sizes=512, use_maxpool=False, channels=None, kernel_sizes=None, strides=None, padding... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AtariFfModel:
"""Feedforward model for Atari agents: a convolutional network feeding an MLP with outputs for action probabilities and state-value estimate."""
def __init__(self, image_shape, output_size, fc_sizes=512, use_maxpool=False, channels=None, kernel_sizes=None, strides=None, paddings=None):
... | the_stack_v2_python_sparse | dependencies/rlpyt/rlpyt/models/pg/atari_ff_model.py | keirp/glamor | train | 5 |
2a4ce08fa1df750db7bae3280b585a4edea41da7 | [
"_id = request.form.get('id', request.args.get('id', None))\nif _id is None:\n return ({'success': False, 'message': 'missing parameter: id'}, 400)\njob_spec = mozart_es.get_by_id(index=JOB_SPECS_INDEX, id=_id, ignore=404)\napp.logger.info(job_spec)\nif job_spec['found'] is False:\n app.logger.error('job_spec... | <|body_start_0|>
_id = request.form.get('id', request.args.get('id', None))
if _id is None:
return ({'success': False, 'message': 'missing parameter: id'}, 400)
job_spec = mozart_es.get_by_id(index=JOB_SPECS_INDEX, id=_id, ignore=404)
app.logger.info(job_spec)
if job_... | Rest APIs for all job_specs (GET, POST, DELETE) | JobSpecs | [
"LicenseRef-scancode-proprietary-license",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JobSpecs:
"""Rest APIs for all job_specs (GET, POST, DELETE)"""
def get(self):
"""Gets a Job Type specification object for the given ID."""
<|body_0|>
def post(self):
"""Add a Job Type specification JSON object."""
<|body_1|>
def delete(self):
... | stack_v2_sparse_classes_10k_train_006713 | 13,931 | permissive | [
{
"docstring": "Gets a Job Type specification object for the given ID.",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Add a Job Type specification JSON object.",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "Remove Job Spec for the given ID",
... | 3 | stack_v2_sparse_classes_30k_train_005702 | Implement the Python class `JobSpecs` described below.
Class description:
Rest APIs for all job_specs (GET, POST, DELETE)
Method signatures and docstrings:
- def get(self): Gets a Job Type specification object for the given ID.
- def post(self): Add a Job Type specification JSON object.
- def delete(self): Remove Job... | Implement the Python class `JobSpecs` described below.
Class description:
Rest APIs for all job_specs (GET, POST, DELETE)
Method signatures and docstrings:
- def get(self): Gets a Job Type specification object for the given ID.
- def post(self): Add a Job Type specification JSON object.
- def delete(self): Remove Job... | c238340fafd96a9b92d92e544d0892a354c1ca32 | <|skeleton|>
class JobSpecs:
"""Rest APIs for all job_specs (GET, POST, DELETE)"""
def get(self):
"""Gets a Job Type specification object for the given ID."""
<|body_0|>
def post(self):
"""Add a Job Type specification JSON object."""
<|body_1|>
def delete(self):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class JobSpecs:
"""Rest APIs for all job_specs (GET, POST, DELETE)"""
def get(self):
"""Gets a Job Type specification object for the given ID."""
_id = request.form.get('id', request.args.get('id', None))
if _id is None:
return ({'success': False, 'message': 'missing paramet... | the_stack_v2_python_sparse | mozart/services/api_v02/specs.py | hysds/mozart | train | 1 |
f94bdabda09a1dc0c9fee1917f6dafeccbed6270 | [
"def sort_rule(x, y):\n a, b = (x + y, y + x)\n if a > b:\n return 1\n elif a < b:\n return -1\n else:\n return 0\nstrs = [str(num) for num in nums]\nstrs.sort(key=functools.cmp_to_key(sort_rule))\nreturn ''.join(strs)",
"def fast_sort(l, r):\n if l >= r:\n return\n i... | <|body_start_0|>
def sort_rule(x, y):
a, b = (x + y, y + x)
if a > b:
return 1
elif a < b:
return -1
else:
return 0
strs = [str(num) for num in nums]
strs.sort(key=functools.cmp_to_key(sort_rule))
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minNumber_1(self, nums: List[int]) -> str:
"""自定义排序 使用python内置排序函数 时间复杂度 O(NlogN) 空间复杂度 O(N) :param nums: :return:"""
<|body_0|>
def minNumber_2(self, nums: List[int]) -> str:
"""自定义排序 使用快速排序 时间复杂度 O(NlogN) 空间复杂度 O(N) :param nums: :return:"""
<|... | stack_v2_sparse_classes_10k_train_006714 | 2,068 | no_license | [
{
"docstring": "自定义排序 使用python内置排序函数 时间复杂度 O(NlogN) 空间复杂度 O(N) :param nums: :return:",
"name": "minNumber_1",
"signature": "def minNumber_1(self, nums: List[int]) -> str"
},
{
"docstring": "自定义排序 使用快速排序 时间复杂度 O(NlogN) 空间复杂度 O(N) :param nums: :return:",
"name": "minNumber_2",
"signature":... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minNumber_1(self, nums: List[int]) -> str: 自定义排序 使用python内置排序函数 时间复杂度 O(NlogN) 空间复杂度 O(N) :param nums: :return:
- def minNumber_2(self, nums: List[int]) -> str: 自定义排序 使用快速排序 ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minNumber_1(self, nums: List[int]) -> str: 自定义排序 使用python内置排序函数 时间复杂度 O(NlogN) 空间复杂度 O(N) :param nums: :return:
- def minNumber_2(self, nums: List[int]) -> str: 自定义排序 使用快速排序 ... | 62419b49000e79962bcdc99cd98afd2fb82ea345 | <|skeleton|>
class Solution:
def minNumber_1(self, nums: List[int]) -> str:
"""自定义排序 使用python内置排序函数 时间复杂度 O(NlogN) 空间复杂度 O(N) :param nums: :return:"""
<|body_0|>
def minNumber_2(self, nums: List[int]) -> str:
"""自定义排序 使用快速排序 时间复杂度 O(NlogN) 空间复杂度 O(N) :param nums: :return:"""
<|... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def minNumber_1(self, nums: List[int]) -> str:
"""自定义排序 使用python内置排序函数 时间复杂度 O(NlogN) 空间复杂度 O(N) :param nums: :return:"""
def sort_rule(x, y):
a, b = (x + y, y + x)
if a > b:
return 1
elif a < b:
return -1
... | the_stack_v2_python_sparse | 剑指 Offer(第 2 版)/minNumber.py | MaoningGuan/LeetCode | train | 3 | |
ea92aca8b46c3388f67c9d72671ba2e698f2ebcf | [
"self.force_admin = kwargs.pop('force_admin', None)\nsuper(NewUserForm, self).__init__(*args, **kwargs)\nself.fields['username'].widget.attrs['class'] = 'form-control'\nself.fields['password1'].widget.attrs['class'] = 'form-control'\nself.fields['password2'].widget.attrs['class'] = 'form-control'\nfor fieldname in ... | <|body_start_0|>
self.force_admin = kwargs.pop('force_admin', None)
super(NewUserForm, self).__init__(*args, **kwargs)
self.fields['username'].widget.attrs['class'] = 'form-control'
self.fields['password1'].widget.attrs['class'] = 'form-control'
self.fields['password2'].widget.at... | Class for creating a new user | NewUserForm | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NewUserForm:
"""Class for creating a new user"""
def __init__(self, *args, **kwargs):
"""Override init to customise the UserCreationForm widget class appearance"""
<|body_0|>
def save(self, commit=True):
"""Override save to make user a superuser"""
<|body... | stack_v2_sparse_classes_10k_train_006715 | 30,652 | permissive | [
{
"docstring": "Override init to customise the UserCreationForm widget class appearance",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Override save to make user a superuser",
"name": "save",
"signature": "def save(self, commit=True)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006527 | Implement the Python class `NewUserForm` described below.
Class description:
Class for creating a new user
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Override init to customise the UserCreationForm widget class appearance
- def save(self, commit=True): Override save to make user a superu... | Implement the Python class `NewUserForm` described below.
Class description:
Class for creating a new user
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Override init to customise the UserCreationForm widget class appearance
- def save(self, commit=True): Override save to make user a superu... | fdff8b8ddc202c53edda2a509a50c4e83013474d | <|skeleton|>
class NewUserForm:
"""Class for creating a new user"""
def __init__(self, *args, **kwargs):
"""Override init to customise the UserCreationForm widget class appearance"""
<|body_0|>
def save(self, commit=True):
"""Override save to make user a superuser"""
<|body... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NewUserForm:
"""Class for creating a new user"""
def __init__(self, *args, **kwargs):
"""Override init to customise the UserCreationForm widget class appearance"""
self.force_admin = kwargs.pop('force_admin', None)
super(NewUserForm, self).__init__(*args, **kwargs)
self.fi... | the_stack_v2_python_sparse | rse/forms.py | RSE-Sheffield/RSEAdmin | train | 22 |
878c394dd3151d43e1ad4daec379caa83549e92f | [
"self.bg_file = bg_file\nself.ref_file = ref_file\nself.var_file = var_file\nself.region = region\nself.sample = sample\nself.gt_replace = gt_replace\nself.min_insert = min_insert\nself.max_insert = max_insert\nself.annotated_vars = None\nself.name = '%s:%d-%d' % tuple(self.region)",
"vcf_file = vcf.Reader(filena... | <|body_start_0|>
self.bg_file = bg_file
self.ref_file = ref_file
self.var_file = var_file
self.region = region
self.sample = sample
self.gt_replace = gt_replace
self.min_insert = min_insert
self.max_insert = max_insert
self.annotated_vars = None
... | This is one run of the program - I can thread these | PcmpTask | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PcmpTask:
"""This is one run of the program - I can thread these"""
def __init__(self, bg_file, ref_file, var_file, region=None, sample=None, gt_replace=False, min_insert=200, max_insert=1000):
"""Main runner On a BioGraph file and a Reference genotype the variants in var_file"""
... | stack_v2_sparse_classes_10k_train_006716 | 21,838 | permissive | [
{
"docstring": "Main runner On a BioGraph file and a Reference genotype the variants in var_file",
"name": "__init__",
"signature": "def __init__(self, bg_file, ref_file, var_file, region=None, sample=None, gt_replace=False, min_insert=200, max_insert=1000)"
},
{
"docstring": "Given a traced var... | 3 | stack_v2_sparse_classes_30k_train_006737 | Implement the Python class `PcmpTask` described below.
Class description:
This is one run of the program - I can thread these
Method signatures and docstrings:
- def __init__(self, bg_file, ref_file, var_file, region=None, sample=None, gt_replace=False, min_insert=200, max_insert=1000): Main runner On a BioGraph file... | Implement the Python class `PcmpTask` described below.
Class description:
This is one run of the program - I can thread these
Method signatures and docstrings:
- def __init__(self, bg_file, ref_file, var_file, region=None, sample=None, gt_replace=False, min_insert=200, max_insert=1000): Main runner On a BioGraph file... | 5f40198e95b0626ae143e021ec97884de634e61d | <|skeleton|>
class PcmpTask:
"""This is one run of the program - I can thread these"""
def __init__(self, bg_file, ref_file, var_file, region=None, sample=None, gt_replace=False, min_insert=200, max_insert=1000):
"""Main runner On a BioGraph file and a Reference genotype the variants in var_file"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PcmpTask:
"""This is one run of the program - I can thread these"""
def __init__(self, bg_file, ref_file, var_file, region=None, sample=None, gt_replace=False, min_insert=200, max_insert=1000):
"""Main runner On a BioGraph file and a Reference genotype the variants in var_file"""
self.bg_... | the_stack_v2_python_sparse | python/biograph/internal/vPCMP.py | spiralgenetics/biograph | train | 21 |
94788a97470b928d0db3e8ffc39a2819c4989d11 | [
"ret = []\nfor x in self.get_range(max_size, **kwargs):\n ret.append(callback())\nreturn ret",
"exclude = kwargs.pop('exclude', None)\nexclude = set(exclude) if exclude else set()\nvals = make_list(args)\nif exclude:\n vals = list(set(vals).difference(exclude))\n if not vals:\n raise ValueError('N... | <|body_start_0|>
ret = []
for x in self.get_range(max_size, **kwargs):
ret.append(callback())
return ret
<|end_body_0|>
<|body_start_1|>
exclude = kwargs.pop('exclude', None)
exclude = set(exclude) if exclude else set()
vals = make_list(args)
if exclu... | SequenceData | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SequenceData:
def get_list(self, callback, max_size=100, **kwargs):
"""Create a list filled with values returned from callback https://github.com/Jaymon/testdata/issues/73 :param callback: callable, each item in the list will be populated by calling this :param max_size: int, the maximum... | stack_v2_sparse_classes_10k_train_006717 | 2,708 | permissive | [
{
"docstring": "Create a list filled with values returned from callback https://github.com/Jaymon/testdata/issues/73 :param callback: callable, each item in the list will be populated by calling this :param max_size: int, the maximum size of the list :returns: list, the randomly generated list",
"name": "ge... | 3 | stack_v2_sparse_classes_30k_train_004185 | Implement the Python class `SequenceData` described below.
Class description:
Implement the SequenceData class.
Method signatures and docstrings:
- def get_list(self, callback, max_size=100, **kwargs): Create a list filled with values returned from callback https://github.com/Jaymon/testdata/issues/73 :param callback... | Implement the Python class `SequenceData` described below.
Class description:
Implement the SequenceData class.
Method signatures and docstrings:
- def get_list(self, callback, max_size=100, **kwargs): Create a list filled with values returned from callback https://github.com/Jaymon/testdata/issues/73 :param callback... | 41ca4bbbff595c2bb50403c5353f19670ec9e2ef | <|skeleton|>
class SequenceData:
def get_list(self, callback, max_size=100, **kwargs):
"""Create a list filled with values returned from callback https://github.com/Jaymon/testdata/issues/73 :param callback: callable, each item in the list will be populated by calling this :param max_size: int, the maximum... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SequenceData:
def get_list(self, callback, max_size=100, **kwargs):
"""Create a list filled with values returned from callback https://github.com/Jaymon/testdata/issues/73 :param callback: callable, each item in the list will be populated by calling this :param max_size: int, the maximum size of the l... | the_stack_v2_python_sparse | testdata/types/sequence.py | Jaymon/testdata | train | 10 | |
2ee774699548099d520a436fbd62c4d5632dbc17 | [
"self.is_group_site = is_group_site\nself.is_private_channel_site = is_private_channel_site\nself.is_team_site = is_team_site",
"if dictionary is None:\n return None\nis_group_site = dictionary.get('isGroupSite')\nis_private_channel_site = dictionary.get('isPrivateChannelSite')\nis_team_site = dictionary.get('... | <|body_start_0|>
self.is_group_site = is_group_site
self.is_private_channel_site = is_private_channel_site
self.is_team_site = is_team_site
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
is_group_site = dictionary.get('isGroupSite')
is_pri... | Implementation of the 'Office365SiteInfo' model. Specifies information about an Office365 sharepoint Site. Attributes: is_group_site (bool): Specifies if the sharepoint site is associated with a group. is_private_channel_site (bool): Specifies if the sharepoint site is associated with a private channel of some team. is... | Office365SiteInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Office365SiteInfo:
"""Implementation of the 'Office365SiteInfo' model. Specifies information about an Office365 sharepoint Site. Attributes: is_group_site (bool): Specifies if the sharepoint site is associated with a group. is_private_channel_site (bool): Specifies if the sharepoint site is assoc... | stack_v2_sparse_classes_10k_train_006718 | 2,121 | permissive | [
{
"docstring": "Constructor for the Office365SiteInfo class",
"name": "__init__",
"signature": "def __init__(self, is_group_site=None, is_private_channel_site=None, is_team_site=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A diction... | 2 | stack_v2_sparse_classes_30k_val_000240 | Implement the Python class `Office365SiteInfo` described below.
Class description:
Implementation of the 'Office365SiteInfo' model. Specifies information about an Office365 sharepoint Site. Attributes: is_group_site (bool): Specifies if the sharepoint site is associated with a group. is_private_channel_site (bool): Sp... | Implement the Python class `Office365SiteInfo` described below.
Class description:
Implementation of the 'Office365SiteInfo' model. Specifies information about an Office365 sharepoint Site. Attributes: is_group_site (bool): Specifies if the sharepoint site is associated with a group. is_private_channel_site (bool): Sp... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class Office365SiteInfo:
"""Implementation of the 'Office365SiteInfo' model. Specifies information about an Office365 sharepoint Site. Attributes: is_group_site (bool): Specifies if the sharepoint site is associated with a group. is_private_channel_site (bool): Specifies if the sharepoint site is assoc... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Office365SiteInfo:
"""Implementation of the 'Office365SiteInfo' model. Specifies information about an Office365 sharepoint Site. Attributes: is_group_site (bool): Specifies if the sharepoint site is associated with a group. is_private_channel_site (bool): Specifies if the sharepoint site is associated with a ... | the_stack_v2_python_sparse | cohesity_management_sdk/models/office_365_site_info.py | cohesity/management-sdk-python | train | 24 |
298efcb9bca28839396b1980075a94d298edb1a0 | [
"frame_load = 10 * [['H'], ['T']]\nexpected = math.log(2)\nframe = self.context.frame.create(frame_load, schema=[('data', str)])\ncomputed_entropy = frame.entropy('data')\nself.assertAlmostEqual(computed_entropy, expected, delta=0.001)",
"frame_load = [[0, 1], [1, 2], [2, 4], [4, 8]]\nexpected = 1.640223928941852... | <|body_start_0|>
frame_load = 10 * [['H'], ['T']]
expected = math.log(2)
frame = self.context.frame.create(frame_load, schema=[('data', str)])
computed_entropy = frame.entropy('data')
self.assertAlmostEqual(computed_entropy, expected, delta=0.001)
<|end_body_0|>
<|body_start_1|>... | EntropyTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EntropyTest:
def test_entropy_coin_flip(self):
"""Get entropy on balanced coin flip."""
<|body_0|>
def test_entropy_exponential(self):
"""Get entropy on exponential distribution."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
frame_load = 10 * [['H... | stack_v2_sparse_classes_10k_train_006719 | 2,228 | permissive | [
{
"docstring": "Get entropy on balanced coin flip.",
"name": "test_entropy_coin_flip",
"signature": "def test_entropy_coin_flip(self)"
},
{
"docstring": "Get entropy on exponential distribution.",
"name": "test_entropy_exponential",
"signature": "def test_entropy_exponential(self)"
}
] | 2 | null | Implement the Python class `EntropyTest` described below.
Class description:
Implement the EntropyTest class.
Method signatures and docstrings:
- def test_entropy_coin_flip(self): Get entropy on balanced coin flip.
- def test_entropy_exponential(self): Get entropy on exponential distribution. | Implement the Python class `EntropyTest` described below.
Class description:
Implement the EntropyTest class.
Method signatures and docstrings:
- def test_entropy_coin_flip(self): Get entropy on balanced coin flip.
- def test_entropy_exponential(self): Get entropy on exponential distribution.
<|skeleton|>
class Entr... | 5548fc925b5c278263cbdebbd9e8c7593320c2f4 | <|skeleton|>
class EntropyTest:
def test_entropy_coin_flip(self):
"""Get entropy on balanced coin flip."""
<|body_0|>
def test_entropy_exponential(self):
"""Get entropy on exponential distribution."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EntropyTest:
def test_entropy_coin_flip(self):
"""Get entropy on balanced coin flip."""
frame_load = 10 * [['H'], ['T']]
expected = math.log(2)
frame = self.context.frame.create(frame_load, schema=[('data', str)])
computed_entropy = frame.entropy('data')
self.as... | the_stack_v2_python_sparse | regression-tests/sparktkregtests/testcases/frames/entropy_test.py | trustedanalytics/spark-tk | train | 35 | |
b4ca0346bf3820aaade607c0985853fd1d292705 | [
"zerosRow = []\nzerosCol = []\ni = 0\nwhile i < len(matrix):\n j = 0\n while j < len(matrix[i]):\n if matrix[i][j] == 0:\n zerosRow.append(i)\n zerosCol.append(j)\n j += 1\n i += 1\nprint(zerosCol)\nprint(zerosRow)\ni = 0\nwhile i < len(matrix):\n j = 0\n while j <... | <|body_start_0|>
zerosRow = []
zerosCol = []
i = 0
while i < len(matrix):
j = 0
while j < len(matrix[i]):
if matrix[i][j] == 0:
zerosRow.append(i)
zerosCol.append(j)
j += 1
i += 1
... | Solution | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def setZeroes(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead."""
<|body_0|>
def setZeroes1(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matri... | stack_v2_sparse_classes_10k_train_006720 | 2,036 | permissive | [
{
"docstring": ":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.",
"name": "setZeroes",
"signature": "def setZeroes(self, matrix)"
},
{
"docstring": ":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instea... | 2 | stack_v2_sparse_classes_30k_train_004597 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def setZeroes(self, matrix): :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.
- def setZeroes1(self, matrix): :type matrix: List... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def setZeroes(self, matrix): :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.
- def setZeroes1(self, matrix): :type matrix: List... | 3e2484d19e6845f0f93e78f7b447909bba3efadd | <|skeleton|>
class Solution:
def setZeroes(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead."""
<|body_0|>
def setZeroes1(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matri... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def setZeroes(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead."""
zerosRow = []
zerosCol = []
i = 0
while i < len(matrix):
j = 0
while j < len(matrix[i]):
... | the_stack_v2_python_sparse | explore_medium/array_and_string/SetZeroes.py | niefy/LeetCodeExam | train | 0 | |
9a271f9b08b3c1b6fd0d99f87872cbeb78d93115 | [
"if db_field.name == 'user':\n kwargs['queryset'] = User.objects.filter(id=request.user.id)\n kwargs['initial'] = request.user.id\nelif db_field.name == 'topic' and (not request.user.is_superuser):\n kwargs['queryset'] = Topic.objects.filter(id__in=request.user.profile.topics.all())\nreturn super(ExamAdmin... | <|body_start_0|>
if db_field.name == 'user':
kwargs['queryset'] = User.objects.filter(id=request.user.id)
kwargs['initial'] = request.user.id
elif db_field.name == 'topic' and (not request.user.is_superuser):
kwargs['queryset'] = Topic.objects.filter(id__in=request.us... | ExamAdmin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExamAdmin:
def formfield_for_foreignkey(self, db_field, request, **kwargs):
"""Assigns default value for User field. limits Topics field to user's topics."""
<|body_0|>
def formfield_for_manytomany(self, db_field, request, **kwargs):
"""Limits the choices of professo... | stack_v2_sparse_classes_10k_train_006721 | 9,167 | permissive | [
{
"docstring": "Assigns default value for User field. limits Topics field to user's topics.",
"name": "formfield_for_foreignkey",
"signature": "def formfield_for_foreignkey(self, db_field, request, **kwargs)"
},
{
"docstring": "Limits the choices of professors for the limit of user.",
"name"... | 3 | stack_v2_sparse_classes_30k_train_007074 | Implement the Python class `ExamAdmin` described below.
Class description:
Implement the ExamAdmin class.
Method signatures and docstrings:
- def formfield_for_foreignkey(self, db_field, request, **kwargs): Assigns default value for User field. limits Topics field to user's topics.
- def formfield_for_manytomany(self... | Implement the Python class `ExamAdmin` described below.
Class description:
Implement the ExamAdmin class.
Method signatures and docstrings:
- def formfield_for_foreignkey(self, db_field, request, **kwargs): Assigns default value for User field. limits Topics field to user's topics.
- def formfield_for_manytomany(self... | 70638c121ea85ff0e6a650c5f2641b0b3b04d6d0 | <|skeleton|>
class ExamAdmin:
def formfield_for_foreignkey(self, db_field, request, **kwargs):
"""Assigns default value for User field. limits Topics field to user's topics."""
<|body_0|>
def formfield_for_manytomany(self, db_field, request, **kwargs):
"""Limits the choices of professo... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ExamAdmin:
def formfield_for_foreignkey(self, db_field, request, **kwargs):
"""Assigns default value for User field. limits Topics field to user's topics."""
if db_field.name == 'user':
kwargs['queryset'] = User.objects.filter(id=request.user.id)
kwargs['initial'] = req... | the_stack_v2_python_sparse | cms/admin.py | Ibrahem3amer/bala7 | train | 0 | |
31aa8afe923b6c38c1d1200b3a1d29eb3bb641ba | [
"def dfs(arr, b, e):\n mi = sys.maxint\n ma = -1\n if b == e:\n return (0, arr[b])\n for i in range(b, e):\n left_mi, left_ma = dfs(arr, b, i)\n right_mi, right_ma = dfs(arr, i + 1, e)\n if mi > left_ma * right_ma + left_mi + right_mi:\n mi = left_ma * right_ma + l... | <|body_start_0|>
def dfs(arr, b, e):
mi = sys.maxint
ma = -1
if b == e:
return (0, arr[b])
for i in range(b, e):
left_mi, left_ma = dfs(arr, b, i)
right_mi, right_ma = dfs(arr, i + 1, e)
if mi > left_... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mctFromLeafValues_TLE(self, arr):
""":type arr: List[int] :rtype: int"""
<|body_0|>
def mctFromLeafValues(self, arr):
""":type arr: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def dfs(arr, b, e):
m... | stack_v2_sparse_classes_10k_train_006722 | 1,747 | no_license | [
{
"docstring": ":type arr: List[int] :rtype: int",
"name": "mctFromLeafValues_TLE",
"signature": "def mctFromLeafValues_TLE(self, arr)"
},
{
"docstring": ":type arr: List[int] :rtype: int",
"name": "mctFromLeafValues",
"signature": "def mctFromLeafValues(self, arr)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mctFromLeafValues_TLE(self, arr): :type arr: List[int] :rtype: int
- def mctFromLeafValues(self, arr): :type arr: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mctFromLeafValues_TLE(self, arr): :type arr: List[int] :rtype: int
- def mctFromLeafValues(self, arr): :type arr: List[int] :rtype: int
<|skeleton|>
class Solution:
def... | 2d5fa4cd696d5035ea8859befeadc5cc436959c9 | <|skeleton|>
class Solution:
def mctFromLeafValues_TLE(self, arr):
""":type arr: List[int] :rtype: int"""
<|body_0|>
def mctFromLeafValues(self, arr):
""":type arr: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def mctFromLeafValues_TLE(self, arr):
""":type arr: List[int] :rtype: int"""
def dfs(arr, b, e):
mi = sys.maxint
ma = -1
if b == e:
return (0, arr[b])
for i in range(b, e):
left_mi, left_ma = dfs(arr, b, ... | the_stack_v2_python_sparse | SourceCode/Python/VSCode/1130.minimum-cost-tree-from-leaf-values.py | roger6blog/LeetCode | train | 0 | |
15eea0bc88a571c16d9fd15421b6ed1aed632f03 | [
"print('定义向上滑动方法')\nx1 = width * 0.5\ny1 = height * 0.9\ny2 = height * 0.25\ntime.sleep(3)\nprint('滑动前')\nfor i in range(n):\n print('第%d次滑屏' % i)\n time.sleep(3)\n driver.swipe(x1, y1, x1, y2)",
"print('定义向下滑动方法')\nx1 = width * 0.5\ny1 = height * 0.25\ny2 = height * 0.9\ntime.sleep(3)\nprint('滑动前')\nfor... | <|body_start_0|>
print('定义向上滑动方法')
x1 = width * 0.5
y1 = height * 0.9
y2 = height * 0.25
time.sleep(3)
print('滑动前')
for i in range(n):
print('第%d次滑屏' % i)
time.sleep(3)
driver.swipe(x1, y1, x1, y2)
<|end_body_0|>
<|body_start_1... | swipe | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class swipe:
def swipeUp(driver, n=5):
"""定义向上滑动方法"""
<|body_0|>
def swipeDown(driver, n=5):
"""定义向下滑动方法"""
<|body_1|>
def swipeLeft(driver, n=5):
"""定义向左滑动方法"""
<|body_2|>
def swipeRight(driver, n=5):
"""定义向右滑动方法"""
<|body... | stack_v2_sparse_classes_10k_train_006723 | 2,304 | no_license | [
{
"docstring": "定义向上滑动方法",
"name": "swipeUp",
"signature": "def swipeUp(driver, n=5)"
},
{
"docstring": "定义向下滑动方法",
"name": "swipeDown",
"signature": "def swipeDown(driver, n=5)"
},
{
"docstring": "定义向左滑动方法",
"name": "swipeLeft",
"signature": "def swipeLeft(driver, n=5)"
... | 4 | stack_v2_sparse_classes_30k_train_007211 | Implement the Python class `swipe` described below.
Class description:
Implement the swipe class.
Method signatures and docstrings:
- def swipeUp(driver, n=5): 定义向上滑动方法
- def swipeDown(driver, n=5): 定义向下滑动方法
- def swipeLeft(driver, n=5): 定义向左滑动方法
- def swipeRight(driver, n=5): 定义向右滑动方法 | Implement the Python class `swipe` described below.
Class description:
Implement the swipe class.
Method signatures and docstrings:
- def swipeUp(driver, n=5): 定义向上滑动方法
- def swipeDown(driver, n=5): 定义向下滑动方法
- def swipeLeft(driver, n=5): 定义向左滑动方法
- def swipeRight(driver, n=5): 定义向右滑动方法
<|skeleton|>
class swipe:
... | a184161fdbf4b35dbca8e9b050ad049c05b003ff | <|skeleton|>
class swipe:
def swipeUp(driver, n=5):
"""定义向上滑动方法"""
<|body_0|>
def swipeDown(driver, n=5):
"""定义向下滑动方法"""
<|body_1|>
def swipeLeft(driver, n=5):
"""定义向左滑动方法"""
<|body_2|>
def swipeRight(driver, n=5):
"""定义向右滑动方法"""
<|body... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class swipe:
def swipeUp(driver, n=5):
"""定义向上滑动方法"""
print('定义向上滑动方法')
x1 = width * 0.5
y1 = height * 0.9
y2 = height * 0.25
time.sleep(3)
print('滑动前')
for i in range(n):
print('第%d次滑屏' % i)
time.sleep(3)
driver.swi... | the_stack_v2_python_sparse | Utils/app_common/swipe.py | liuchengxu11/IM | train | 0 | |
5ed5229d66f2a4e7401fb96394fabbc2f3965c93 | [
"super().__init__(env, name, seed)\nself.buffer_processing_matrix = env.job_generator.buffer_processing_matrix\nself.safety_stock = safety_stock",
"_, num_activities = self.constituency_matrix.shape\naction = np.zeros((num_activities, 1))\nfor constituency_s, boundary_constraint_matrix_s in zip(self.constituency_... | <|body_start_0|>
super().__init__(env, name, seed)
self.buffer_processing_matrix = env.job_generator.buffer_processing_matrix
self.safety_stock = safety_stock
<|end_body_0|>
<|body_start_1|>
_, num_activities = self.constituency_matrix.shape
action = np.zeros((num_activities, 1)... | LongestBufferPriorityAgent | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LongestBufferPriorityAgent:
def __init__(self, env: crw.ControlledRandomWalk, safety_stock: Optional[float]=10.0, name: str='LongestBufferPriorityAgent', seed: Optional[int]=None) -> None:
"""Non-idling policy such that every resource works on the buffer with largest amount of customers,... | stack_v2_sparse_classes_10k_train_006724 | 3,606 | permissive | [
{
"docstring": "Non-idling policy such that every resource works on the buffer with largest amount of customers, and that are above the specified safety_stock. If there are multiple buffers with the same largest size and/or multiple activities, each resource chooses among them randomly. :param env: the environm... | 2 | stack_v2_sparse_classes_30k_train_004602 | Implement the Python class `LongestBufferPriorityAgent` described below.
Class description:
Implement the LongestBufferPriorityAgent class.
Method signatures and docstrings:
- def __init__(self, env: crw.ControlledRandomWalk, safety_stock: Optional[float]=10.0, name: str='LongestBufferPriorityAgent', seed: Optional[i... | Implement the Python class `LongestBufferPriorityAgent` described below.
Class description:
Implement the LongestBufferPriorityAgent class.
Method signatures and docstrings:
- def __init__(self, env: crw.ControlledRandomWalk, safety_stock: Optional[float]=10.0, name: str='LongestBufferPriorityAgent', seed: Optional[i... | b067eebaa5b57a96efdaed5796aca9f157d32214 | <|skeleton|>
class LongestBufferPriorityAgent:
def __init__(self, env: crw.ControlledRandomWalk, safety_stock: Optional[float]=10.0, name: str='LongestBufferPriorityAgent', seed: Optional[int]=None) -> None:
"""Non-idling policy such that every resource works on the buffer with largest amount of customers,... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LongestBufferPriorityAgent:
def __init__(self, env: crw.ControlledRandomWalk, safety_stock: Optional[float]=10.0, name: str='LongestBufferPriorityAgent', seed: Optional[int]=None) -> None:
"""Non-idling policy such that every resource works on the buffer with largest amount of customers, and that are ... | the_stack_v2_python_sparse | src/snc/agents/general_heuristics/longest_buffer_priority_agent.py | stochasticnetworkcontrol/snc | train | 9 | |
531ca95260e3eeb6d3fd0a3bef7dcbbe36825420 | [
"super().__init__()\nself.common_tower = nn.Sequential(nn.Conv2d(3, channels, (3, 3), padding=(1, 1), bias=False), nn.BatchNorm2d(channels), nn.ReLU(), *(ResBlock(channels, res, separable, squeeze_size, squeeze_bias) for _ in range(blocks)))\nself.policy_head = nn.Sequential(nn.Conv2d(channels, 17, (1, 1)))\nself.w... | <|body_start_0|>
super().__init__()
self.common_tower = nn.Sequential(nn.Conv2d(3, channels, (3, 3), padding=(1, 1), bias=False), nn.BatchNorm2d(channels), nn.ReLU(), *(ResBlock(channels, res, separable, squeeze_size, squeeze_bias) for _ in range(blocks)))
self.policy_head = nn.Sequential(nn.Con... | GoogleModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GoogleModel:
def __init__(self, channels: int, blocks: int, wdl_channels: int, wdl_size: int, res: bool, separable: bool, squeeze_size: Optional[int], squeeze_bias: bool):
"""Parameters used in AlphaZero: channels=256 blocks=19 or 39 wdl_channels=1 wdl_size=256 policy_channels=2 Oracle u... | stack_v2_sparse_classes_10k_train_006725 | 3,514 | no_license | [
{
"docstring": "Parameters used in AlphaZero: channels=256 blocks=19 or 39 wdl_channels=1 wdl_size=256 policy_channels=2 Oracle uses 32 channels for both heads.",
"name": "__init__",
"signature": "def __init__(self, channels: int, blocks: int, wdl_channels: int, wdl_size: int, res: bool, separable: bool... | 2 | stack_v2_sparse_classes_30k_train_006057 | Implement the Python class `GoogleModel` described below.
Class description:
Implement the GoogleModel class.
Method signatures and docstrings:
- def __init__(self, channels: int, blocks: int, wdl_channels: int, wdl_size: int, res: bool, separable: bool, squeeze_size: Optional[int], squeeze_bias: bool): Parameters us... | Implement the Python class `GoogleModel` described below.
Class description:
Implement the GoogleModel class.
Method signatures and docstrings:
- def __init__(self, channels: int, blocks: int, wdl_channels: int, wdl_size: int, res: bool, separable: bool, squeeze_size: Optional[int], squeeze_bias: bool): Parameters us... | 42d2fd7f67fb3ea093c2c170cee36dba402313bf | <|skeleton|>
class GoogleModel:
def __init__(self, channels: int, blocks: int, wdl_channels: int, wdl_size: int, res: bool, separable: bool, squeeze_size: Optional[int], squeeze_bias: bool):
"""Parameters used in AlphaZero: channels=256 blocks=19 or 39 wdl_channels=1 wdl_size=256 policy_channels=2 Oracle u... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GoogleModel:
def __init__(self, channels: int, blocks: int, wdl_channels: int, wdl_size: int, res: bool, separable: bool, squeeze_size: Optional[int], squeeze_bias: bool):
"""Parameters used in AlphaZero: channels=256 blocks=19 or 39 wdl_channels=1 wdl_size=256 policy_channels=2 Oracle uses 32 channel... | the_stack_v2_python_sparse | python/models/google.py | KarelPeeters/STTT-Zero | train | 0 | |
125c7e05993e638843671ed269afd2b3a8322c5d | [
"results = []\n\ndef preOrderTraversal(root):\n if not root:\n results.append('None')\n else:\n results.append(str(root.val))\n preOrderTraversal(root.left)\n preOrderTraversal(root.right)\npreOrderTraversal(root)\nreturn ','.join(results)",
"def rebuild(l):\n if l[0] == 'None... | <|body_start_0|>
results = []
def preOrderTraversal(root):
if not root:
results.append('None')
else:
results.append(str(root.val))
preOrderTraversal(root.left)
preOrderTraversal(root.right)
preOrderTraversal... | 层/先序遍历OK 但是None要补全 | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
"""层/先序遍历OK 但是None要补全"""
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... | stack_v2_sparse_classes_10k_train_006726 | 3,147 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
层/先序遍历OK 但是None要补全
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: TreeNod... | Implement the Python class `Codec` described below.
Class description:
层/先序遍历OK 但是None要补全
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: TreeNod... | 44765a7d89423b7ec2c159f70b1a6f6e446523c2 | <|skeleton|>
class Codec:
"""层/先序遍历OK 但是None要补全"""
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... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Codec:
"""层/先序遍历OK 但是None要补全"""
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
results = []
def preOrderTraversal(root):
if not root:
results.append('None')
else:
results... | the_stack_v2_python_sparse | python/_0001_0500/0297_serialize-and-deserialize-binary-tree.py | Wang-Yann/LeetCodeMe | train | 0 |
9f72499ff4beedce04619d5976746a58bd000945 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn ResponseStatus()",
"from .response_type import ResponseType\nfrom .response_type import ResponseType\nfields: Dict[str, Callable[[Any], None]] = {'@odata.type': lambda n: setattr(self, 'odata_type', n.get_str_value()), 'response': lamb... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return ResponseStatus()
<|end_body_0|>
<|body_start_1|>
from .response_type import ResponseType
from .response_type import ResponseType
fields: Dict[str, Callable[[Any], None]] = {'@oda... | ResponseStatus | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResponseStatus:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ResponseStatus:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Retur... | stack_v2_sparse_classes_10k_train_006727 | 3,761 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ResponseStatus",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_valu... | 3 | stack_v2_sparse_classes_30k_train_005047 | Implement the Python class `ResponseStatus` described below.
Class description:
Implement the ResponseStatus class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ResponseStatus: Creates a new instance of the appropriate class based on discriminator va... | Implement the Python class `ResponseStatus` described below.
Class description:
Implement the ResponseStatus class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ResponseStatus: Creates a new instance of the appropriate class based on discriminator va... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class ResponseStatus:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ResponseStatus:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Retur... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ResponseStatus:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ResponseStatus:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ResponseSt... | the_stack_v2_python_sparse | msgraph/generated/models/response_status.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
64ea07b4aadc6bc50690ecb76494d408d1c9839f | [
"print('开始构建 IP 树')\nt1 = time.time()\nIPHelper.ip_tree = IPTree()\nwith open(ip_csv_path, newline='') as csvfile:\n reader = csv.reader(csvfile)\n i = 1\n for row in reader:\n ip_start, ip_end, address_code = (row[0], row[1], row[2])\n IPHelper.ip_tree.train(ip_start, ip_end, address_code)\n... | <|body_start_0|>
print('开始构建 IP 树')
t1 = time.time()
IPHelper.ip_tree = IPTree()
with open(ip_csv_path, newline='') as csvfile:
reader = csv.reader(csvfile)
i = 1
for row in reader:
ip_start, ip_end, address_code = (row[0], row[1], row[... | IPHelper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IPHelper:
def build_tree(ip_csv_path):
"""构建 IP 树 Keyword arguments: ip_csv_path -- csv 文件路径"""
<|body_0|>
def load_region(region_excel_path):
"""导入城市信息 Keyword arguments: argument -- description Return:"""
<|body_1|>
def start(ip_csv_path: str, region_e... | stack_v2_sparse_classes_10k_train_006728 | 3,154 | no_license | [
{
"docstring": "构建 IP 树 Keyword arguments: ip_csv_path -- csv 文件路径",
"name": "build_tree",
"signature": "def build_tree(ip_csv_path)"
},
{
"docstring": "导入城市信息 Keyword arguments: argument -- description Return:",
"name": "load_region",
"signature": "def load_region(region_excel_path)"
... | 4 | stack_v2_sparse_classes_30k_train_000839 | Implement the Python class `IPHelper` described below.
Class description:
Implement the IPHelper class.
Method signatures and docstrings:
- def build_tree(ip_csv_path): 构建 IP 树 Keyword arguments: ip_csv_path -- csv 文件路径
- def load_region(region_excel_path): 导入城市信息 Keyword arguments: argument -- description Return:
- ... | Implement the Python class `IPHelper` described below.
Class description:
Implement the IPHelper class.
Method signatures and docstrings:
- def build_tree(ip_csv_path): 构建 IP 树 Keyword arguments: ip_csv_path -- csv 文件路径
- def load_region(region_excel_path): 导入城市信息 Keyword arguments: argument -- description Return:
- ... | 6bd8b923dd052ee1aa7efc468c505277b9f2c24f | <|skeleton|>
class IPHelper:
def build_tree(ip_csv_path):
"""构建 IP 树 Keyword arguments: ip_csv_path -- csv 文件路径"""
<|body_0|>
def load_region(region_excel_path):
"""导入城市信息 Keyword arguments: argument -- description Return:"""
<|body_1|>
def start(ip_csv_path: str, region_e... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class IPHelper:
def build_tree(ip_csv_path):
"""构建 IP 树 Keyword arguments: ip_csv_path -- csv 文件路径"""
print('开始构建 IP 树')
t1 = time.time()
IPHelper.ip_tree = IPTree()
with open(ip_csv_path, newline='') as csvfile:
reader = csv.reader(csvfile)
i = 1
... | the_stack_v2_python_sparse | exercises/tree/ip_tree.py | zh826256645/my-algorithm-exercises | train | 0 | |
7d815e9da803285f6e5e9ebf4467e0f08c76fb20 | [
"super().__init__()\nimport sklearn\nimport sklearn.discriminant_analysis\nself.model = sklearn.discriminant_analysis.QuadraticDiscriminantAnalysis",
"specs = super(QuadraticDiscriminantAnalysisClassifier, cls).getInputSpecification()\nspecs.description = \"The \\\\xmlNode{QuadraticDiscriminantAnalysisClassifier}... | <|body_start_0|>
super().__init__()
import sklearn
import sklearn.discriminant_analysis
self.model = sklearn.discriminant_analysis.QuadraticDiscriminantAnalysis
<|end_body_0|>
<|body_start_1|>
specs = super(QuadraticDiscriminantAnalysisClassifier, cls).getInputSpecification()
... | KNeighborsClassifier Classifier implementing the k-nearest neighbors vote. | QuadraticDiscriminantAnalysisClassifier | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuadraticDiscriminantAnalysisClassifier:
"""KNeighborsClassifier Classifier implementing the k-nearest neighbors vote."""
def __init__(self):
"""Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None"""
<|body_0|>
def getInputS... | stack_v2_sparse_classes_10k_train_006729 | 5,236 | permissive | [
{
"docstring": "Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Method to get a reference to a class that specifies the input data for class cls. @ In, cls, the class for... | 3 | stack_v2_sparse_classes_30k_train_006900 | Implement the Python class `QuadraticDiscriminantAnalysisClassifier` described below.
Class description:
KNeighborsClassifier Classifier implementing the k-nearest neighbors vote.
Method signatures and docstrings:
- def __init__(self): Constructor that will appropriately initialize a supervised learning object @ In, ... | Implement the Python class `QuadraticDiscriminantAnalysisClassifier` described below.
Class description:
KNeighborsClassifier Classifier implementing the k-nearest neighbors vote.
Method signatures and docstrings:
- def __init__(self): Constructor that will appropriately initialize a supervised learning object @ In, ... | 2b16e7aa3325fe84cab2477947a951414c635381 | <|skeleton|>
class QuadraticDiscriminantAnalysisClassifier:
"""KNeighborsClassifier Classifier implementing the k-nearest neighbors vote."""
def __init__(self):
"""Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None"""
<|body_0|>
def getInputS... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class QuadraticDiscriminantAnalysisClassifier:
"""KNeighborsClassifier Classifier implementing the k-nearest neighbors vote."""
def __init__(self):
"""Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None"""
super().__init__()
import sklearn
... | the_stack_v2_python_sparse | ravenframework/SupervisedLearning/ScikitLearn/DiscriminantAnalysis/QuadraticDiscriminantAnalysis.py | idaholab/raven | train | 201 |
50893a8b3042df00ed29eb9bfb38c65750eafe95 | [
"directory, name, extension = self._split_file_name(file_name)\nextension = self.extension if extension == '' else extension\nfile_name = directory + os.sep + name + extension\nif not file_name.endswith(self.extension):\n raise FileFormatError(\"Invalid file format. '{}' file expected.\".format(self.extension))\... | <|body_start_0|>
directory, name, extension = self._split_file_name(file_name)
extension = self.extension if extension == '' else extension
file_name = directory + os.sep + name + extension
if not file_name.endswith(self.extension):
raise FileFormatError("Invalid file format.... | Reads a Sudoku game file. | SudokuGameReader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SudokuGameReader:
"""Reads a Sudoku game file."""
def read_game(self, file_name):
"""Reads a Sudoku game file and returns a Sudoku game object. @param file_name: the name of the file."""
<|body_0|>
def open_sudoku_file(self, file_name, mode='r'):
"""Opens a file ... | stack_v2_sparse_classes_10k_train_006730 | 1,940 | no_license | [
{
"docstring": "Reads a Sudoku game file and returns a Sudoku game object. @param file_name: the name of the file.",
"name": "read_game",
"signature": "def read_game(self, file_name)"
},
{
"docstring": "Opens a file using a context manager. @param file_name: the name of the file. @param mode: th... | 3 | stack_v2_sparse_classes_30k_train_006668 | Implement the Python class `SudokuGameReader` described below.
Class description:
Reads a Sudoku game file.
Method signatures and docstrings:
- def read_game(self, file_name): Reads a Sudoku game file and returns a Sudoku game object. @param file_name: the name of the file.
- def open_sudoku_file(self, file_name, mod... | Implement the Python class `SudokuGameReader` described below.
Class description:
Reads a Sudoku game file.
Method signatures and docstrings:
- def read_game(self, file_name): Reads a Sudoku game file and returns a Sudoku game object. @param file_name: the name of the file.
- def open_sudoku_file(self, file_name, mod... | 27cc2f7cb52ea787191095c2e581729c22bba62a | <|skeleton|>
class SudokuGameReader:
"""Reads a Sudoku game file."""
def read_game(self, file_name):
"""Reads a Sudoku game file and returns a Sudoku game object. @param file_name: the name of the file."""
<|body_0|>
def open_sudoku_file(self, file_name, mode='r'):
"""Opens a file ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SudokuGameReader:
"""Reads a Sudoku game file."""
def read_game(self, file_name):
"""Reads a Sudoku game file and returns a Sudoku game object. @param file_name: the name of the file."""
directory, name, extension = self._split_file_name(file_name)
extension = self.extension if ex... | the_stack_v2_python_sparse | src/sudoku/reader/game_reader.py | pysudoku/sudoku | train | 1 |
b59442434558ff6d8b45d0cf2c03c3aafcd2a55f | [
"tf.reset_default_graph()\nmodel_config = make_layerwise_model_config()\nmodel_config.number_of_trained_cnn_layers = 1\nmodel = layerwise.build_model(model_config.cnn_model_name, model_config=model_config)\nimages = tf.random.normal((100, 28, 28, 1))\nlabels = tf.random.uniform((100,), minval=0, maxval=10, dtype=tf... | <|body_start_0|>
tf.reset_default_graph()
model_config = make_layerwise_model_config()
model_config.number_of_trained_cnn_layers = 1
model = layerwise.build_model(model_config.cnn_model_name, model_config=model_config)
images = tf.random.normal((100, 28, 28, 1))
labels = ... | LayerwiseTest | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LayerwiseTest:
def test_number_of_trained_cnn_layers_param_should_give_trained_weights(self):
"""Tests the layerswise model with both generated and trained weights."""
<|body_0|>
def test_negative_number_of_trained_cnn_layers_param_trains_last_layers(self):
"""Tests ... | stack_v2_sparse_classes_10k_train_006731 | 4,745 | permissive | [
{
"docstring": "Tests the layerswise model with both generated and trained weights.",
"name": "test_number_of_trained_cnn_layers_param_should_give_trained_weights",
"signature": "def test_number_of_trained_cnn_layers_param_should_give_trained_weights(self)"
},
{
"docstring": "Tests the layerswis... | 3 | null | Implement the Python class `LayerwiseTest` described below.
Class description:
Implement the LayerwiseTest class.
Method signatures and docstrings:
- def test_number_of_trained_cnn_layers_param_should_give_trained_weights(self): Tests the layerswise model with both generated and trained weights.
- def test_negative_n... | Implement the Python class `LayerwiseTest` described below.
Class description:
Implement the LayerwiseTest class.
Method signatures and docstrings:
- def test_number_of_trained_cnn_layers_param_should_give_trained_weights(self): Tests the layerswise model with both generated and trained weights.
- def test_negative_n... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class LayerwiseTest:
def test_number_of_trained_cnn_layers_param_should_give_trained_weights(self):
"""Tests the layerswise model with both generated and trained weights."""
<|body_0|>
def test_negative_number_of_trained_cnn_layers_param_trains_last_layers(self):
"""Tests ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LayerwiseTest:
def test_number_of_trained_cnn_layers_param_should_give_trained_weights(self):
"""Tests the layerswise model with both generated and trained weights."""
tf.reset_default_graph()
model_config = make_layerwise_model_config()
model_config.number_of_trained_cnn_layer... | the_stack_v2_python_sparse | hypertransformer/tf/core/layerwise_test.py | Jimmy-INL/google-research | train | 1 | |
b061db72830bdc3f002957ea94f60c1bf12f99c9 | [
"if root.left == None and root.right == None:\n foundSoFar.append(pathSoFar)\n return\nif root.left != None:\n self.helper(root.left, '->'.join([pathSoFar, str(root.left.val)]), foundSoFar)\nif root.right != None:\n self.helper(root.right, '->'.join([pathSoFar, str(root.right.val)]), foundSoFar)",
"if... | <|body_start_0|>
if root.left == None and root.right == None:
foundSoFar.append(pathSoFar)
return
if root.left != None:
self.helper(root.left, '->'.join([pathSoFar, str(root.left.val)]), foundSoFar)
if root.right != None:
self.helper(root.right, '-... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def helper(self, root, pathSoFar, foundSoFar):
""":type root: TreeNode :type pathSoFar: string :type foundSoFar: List[str] :rtype: List[str]"""
<|body_0|>
def binaryTreePaths(self, root):
""":type root: TreeNode :rtype: List[str]"""
<|body_1|>
<|en... | stack_v2_sparse_classes_10k_train_006732 | 1,006 | no_license | [
{
"docstring": ":type root: TreeNode :type pathSoFar: string :type foundSoFar: List[str] :rtype: List[str]",
"name": "helper",
"signature": "def helper(self, root, pathSoFar, foundSoFar)"
},
{
"docstring": ":type root: TreeNode :rtype: List[str]",
"name": "binaryTreePaths",
"signature": ... | 2 | stack_v2_sparse_classes_30k_train_000264 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def helper(self, root, pathSoFar, foundSoFar): :type root: TreeNode :type pathSoFar: string :type foundSoFar: List[str] :rtype: List[str]
- def binaryTreePaths(self, root): :type... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def helper(self, root, pathSoFar, foundSoFar): :type root: TreeNode :type pathSoFar: string :type foundSoFar: List[str] :rtype: List[str]
- def binaryTreePaths(self, root): :type... | dcf9768aeb120f3ad9925e407193e1a4b282a0a2 | <|skeleton|>
class Solution:
def helper(self, root, pathSoFar, foundSoFar):
""":type root: TreeNode :type pathSoFar: string :type foundSoFar: List[str] :rtype: List[str]"""
<|body_0|>
def binaryTreePaths(self, root):
""":type root: TreeNode :rtype: List[str]"""
<|body_1|>
<|en... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def helper(self, root, pathSoFar, foundSoFar):
""":type root: TreeNode :type pathSoFar: string :type foundSoFar: List[str] :rtype: List[str]"""
if root.left == None and root.right == None:
foundSoFar.append(pathSoFar)
return
if root.left != None:
... | the_stack_v2_python_sparse | Binary_Tree_Paths.py | O5-2/leetcode | train | 0 | |
b250b7a81b52dacf26e239f6b832f2c516810265 | [
"email = self.cleaned_data['email']\nsession = orm.sessionmaker()\nusers = session.query(User).filter_by(email=email).all()\nif len(users) == 0:\n raise forms.ValidationError(_(u\"That e-mail address doesn't have an associated user account. Are you sure\\nyou've registered?\"))\nself.users_cache = [u for u in us... | <|body_start_0|>
email = self.cleaned_data['email']
session = orm.sessionmaker()
users = session.query(User).filter_by(email=email).all()
if len(users) == 0:
raise forms.ValidationError(_(u"That e-mail address doesn't have an associated user account. Are you sure\nyou've regi... | PasswordResetForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PasswordResetForm:
def clean_email(self):
"""Validates that a user exists with the given e-mail address."""
<|body_0|>
def save(self, domain_override=None, subject_template_name='registration/password_reset_subject.txt', email_template_name='registration/password_reset_email... | stack_v2_sparse_classes_10k_train_006733 | 4,569 | no_license | [
{
"docstring": "Validates that a user exists with the given e-mail address.",
"name": "clean_email",
"signature": "def clean_email(self)"
},
{
"docstring": "Generates a one-use only link for resetting password and sends to the user.",
"name": "save",
"signature": "def save(self, domain_o... | 2 | stack_v2_sparse_classes_30k_train_004433 | Implement the Python class `PasswordResetForm` described below.
Class description:
Implement the PasswordResetForm class.
Method signatures and docstrings:
- def clean_email(self): Validates that a user exists with the given e-mail address.
- def save(self, domain_override=None, subject_template_name='registration/pa... | Implement the Python class `PasswordResetForm` described below.
Class description:
Implement the PasswordResetForm class.
Method signatures and docstrings:
- def clean_email(self): Validates that a user exists with the given e-mail address.
- def save(self, domain_override=None, subject_template_name='registration/pa... | a0327728aeb56cedfd7a350590979252c057655b | <|skeleton|>
class PasswordResetForm:
def clean_email(self):
"""Validates that a user exists with the given e-mail address."""
<|body_0|>
def save(self, domain_override=None, subject_template_name='registration/password_reset_subject.txt', email_template_name='registration/password_reset_email... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PasswordResetForm:
def clean_email(self):
"""Validates that a user exists with the given e-mail address."""
email = self.cleaned_data['email']
session = orm.sessionmaker()
users = session.query(User).filter_by(email=email).all()
if len(users) == 0:
raise for... | the_stack_v2_python_sparse | baph/auth/forms.py | devhub/baph | train | 8 | |
154c66289a5308c5c47aac36785aa6564a8a891c | [
"if len(nums) <= 1:\n return 0\nn = len(nums)\ndp = [0] * n\nmax_dump = nums[0]\ndp[0] = 0\ndp[1:max_dump + 1] = [1] * max_dump\nif max_dump >= n - 1:\n return 1\nfor i in range(1, n):\n if i + nums[i] >= n - 1:\n return dp[i] + 1\n if i + nums[i] > max_dump:\n dp[max_dump + 1:i + nums[i] ... | <|body_start_0|>
if len(nums) <= 1:
return 0
n = len(nums)
dp = [0] * n
max_dump = nums[0]
dp[0] = 0
dp[1:max_dump + 1] = [1] * max_dump
if max_dump >= n - 1:
return 1
for i in range(1, n):
if i + nums[i] >= n - 1:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def jump(self, nums):
"""max_dump 在第i个元素最远能跳到的距离 dp[i]:跳到第i个元素最少需要多少步 :type nums: List[int] :rtype: int"""
<|body_0|>
def jump2(self, nums):
"""优化代码 与上面不同的是,这是根据i更新last,上面是根据num[i]和i的和判断是不是能跳过前面跳得最大值。 f[i]: 到达i所需要的最少步数 last: 第一次到达i时上一步的位置 根据贪心得知,令f[i]=f[las... | stack_v2_sparse_classes_10k_train_006734 | 2,924 | no_license | [
{
"docstring": "max_dump 在第i个元素最远能跳到的距离 dp[i]:跳到第i个元素最少需要多少步 :type nums: List[int] :rtype: int",
"name": "jump",
"signature": "def jump(self, nums)"
},
{
"docstring": "优化代码 与上面不同的是,这是根据i更新last,上面是根据num[i]和i的和判断是不是能跳过前面跳得最大值。 f[i]: 到达i所需要的最少步数 last: 第一次到达i时上一步的位置 根据贪心得知,令f[i]=f[last]+1后,f[i]就会是最优... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def jump(self, nums): max_dump 在第i个元素最远能跳到的距离 dp[i]:跳到第i个元素最少需要多少步 :type nums: List[int] :rtype: int
- def jump2(self, nums): 优化代码 与上面不同的是,这是根据i更新last,上面是根据num[i]和i的和判断是不是能跳过前面跳得... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def jump(self, nums): max_dump 在第i个元素最远能跳到的距离 dp[i]:跳到第i个元素最少需要多少步 :type nums: List[int] :rtype: int
- def jump2(self, nums): 优化代码 与上面不同的是,这是根据i更新last,上面是根据num[i]和i的和判断是不是能跳过前面跳得... | 5d3574ccd282d0146c83c286ae28d8baaabd4910 | <|skeleton|>
class Solution:
def jump(self, nums):
"""max_dump 在第i个元素最远能跳到的距离 dp[i]:跳到第i个元素最少需要多少步 :type nums: List[int] :rtype: int"""
<|body_0|>
def jump2(self, nums):
"""优化代码 与上面不同的是,这是根据i更新last,上面是根据num[i]和i的和判断是不是能跳过前面跳得最大值。 f[i]: 到达i所需要的最少步数 last: 第一次到达i时上一步的位置 根据贪心得知,令f[i]=f[las... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def jump(self, nums):
"""max_dump 在第i个元素最远能跳到的距离 dp[i]:跳到第i个元素最少需要多少步 :type nums: List[int] :rtype: int"""
if len(nums) <= 1:
return 0
n = len(nums)
dp = [0] * n
max_dump = nums[0]
dp[0] = 0
dp[1:max_dump + 1] = [1] * max_dump
... | the_stack_v2_python_sparse | 45_跳跃游戏 II.py | lovehhf/LeetCode | train | 0 | |
fa6035d8192666f1a8b0f3dd543e2ac97d291c67 | [
"source_dir = os.path.join(os.path.dirname(dir_path), 'image')\ntarget_dir = os.path.join(os.path.dirname(dir_path), 'image_target')\nself.imageutil = ImageUtils(source_dir, target_dir)",
"print('欢迎来到图片处理页面'.center(100, '*'))\nmenu = ['文件夹下所有图片缩略功能', '获取件夹下所有图片大小数据并且保存到excel']\nfor i in range(len(menu)):\n pri... | <|body_start_0|>
source_dir = os.path.join(os.path.dirname(dir_path), 'image')
target_dir = os.path.join(os.path.dirname(dir_path), 'image_target')
self.imageutil = ImageUtils(source_dir, target_dir)
<|end_body_0|>
<|body_start_1|>
print('欢迎来到图片处理页面'.center(100, '*'))
menu = ['文... | 图片操作类 | ImageManage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageManage:
"""图片操作类"""
def __init__(self):
"""初始化"""
<|body_0|>
def image_page(self):
"""图片处理页面"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
source_dir = os.path.join(os.path.dirname(dir_path), 'image')
target_dir = os.path.join(os.... | stack_v2_sparse_classes_10k_train_006735 | 1,225 | no_license | [
{
"docstring": "初始化",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "图片处理页面",
"name": "image_page",
"signature": "def image_page(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001671 | Implement the Python class `ImageManage` described below.
Class description:
图片操作类
Method signatures and docstrings:
- def __init__(self): 初始化
- def image_page(self): 图片处理页面 | Implement the Python class `ImageManage` described below.
Class description:
图片操作类
Method signatures and docstrings:
- def __init__(self): 初始化
- def image_page(self): 图片处理页面
<|skeleton|>
class ImageManage:
"""图片操作类"""
def __init__(self):
"""初始化"""
<|body_0|>
def image_page(self):
... | 173f3a5fa24176df4c53bd36771cc733a1221dfd | <|skeleton|>
class ImageManage:
"""图片操作类"""
def __init__(self):
"""初始化"""
<|body_0|>
def image_page(self):
"""图片处理页面"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ImageManage:
"""图片操作类"""
def __init__(self):
"""初始化"""
source_dir = os.path.join(os.path.dirname(dir_path), 'image')
target_dir = os.path.join(os.path.dirname(dir_path), 'image_target')
self.imageutil = ImageUtils(source_dir, target_dir)
def image_page(self):
... | the_stack_v2_python_sparse | 0303system-yanchunwei/joker_work/core/image_page.py | Joker2018goon/myGitRepo | train | 1 |
ee70efd608852760f4a82b54956d258fa62a61ad | [
"assert adversary is not None\nif not adversary.is_targeted_attack or adversary.target_label is None:\n target_labels = self._generate_random_target(adversary.original_label)\nelse:\n target_labels = [adversary.target_label]\nfor target in target_labels:\n original_image = adversary.original\n mask = np... | <|body_start_0|>
assert adversary is not None
if not adversary.is_targeted_attack or adversary.target_label is None:
target_labels = self._generate_random_target(adversary.original_label)
else:
target_labels = [adversary.target_label]
for target in target_labels:
... | Implements the Saliency Map Attack. The Jacobian-based Saliency Map Approach (Papernot et al. 2016). Paper link: https://arxiv.org/pdf/1511.07528.pdf | SaliencyMapAttack | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SaliencyMapAttack:
"""Implements the Saliency Map Attack. The Jacobian-based Saliency Map Approach (Papernot et al. 2016). Paper link: https://arxiv.org/pdf/1511.07528.pdf"""
def _apply(self, adversary, max_iter=2000, fast=True, theta=0.1, max_perturbations_per_pixel=7):
"""Apply the... | stack_v2_sparse_classes_10k_train_006736 | 5,906 | permissive | [
{
"docstring": "Apply the JSMA attack. Args: adversary(Adversary): The Adversary object. max_iter(int): The max iterations. fast(bool): Whether evaluate the pixel influence on sum of residual classes. theta(float): Perturbation per pixel relative to [min, max] range. max_perturbations_per_pixel(int): The max co... | 3 | stack_v2_sparse_classes_30k_test_000359 | Implement the Python class `SaliencyMapAttack` described below.
Class description:
Implements the Saliency Map Attack. The Jacobian-based Saliency Map Approach (Papernot et al. 2016). Paper link: https://arxiv.org/pdf/1511.07528.pdf
Method signatures and docstrings:
- def _apply(self, adversary, max_iter=2000, fast=T... | Implement the Python class `SaliencyMapAttack` described below.
Class description:
Implements the Saliency Map Attack. The Jacobian-based Saliency Map Approach (Papernot et al. 2016). Paper link: https://arxiv.org/pdf/1511.07528.pdf
Method signatures and docstrings:
- def _apply(self, adversary, max_iter=2000, fast=T... | a60babdf382aba71fe447b3259441b4bed947414 | <|skeleton|>
class SaliencyMapAttack:
"""Implements the Saliency Map Attack. The Jacobian-based Saliency Map Approach (Papernot et al. 2016). Paper link: https://arxiv.org/pdf/1511.07528.pdf"""
def _apply(self, adversary, max_iter=2000, fast=True, theta=0.1, max_perturbations_per_pixel=7):
"""Apply the... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SaliencyMapAttack:
"""Implements the Saliency Map Attack. The Jacobian-based Saliency Map Approach (Papernot et al. 2016). Paper link: https://arxiv.org/pdf/1511.07528.pdf"""
def _apply(self, adversary, max_iter=2000, fast=True, theta=0.1, max_perturbations_per_pixel=7):
"""Apply the JSMA attack.... | the_stack_v2_python_sparse | PaddleCV/adversarial/advbox/attacks/saliency.py | littletomatodonkey/models | train | 5 |
da8091bc1649b808f9ee65dfd57b4e3bb34ecb64 | [
"ops = block_string.split('_')\noptions = {}\nfor op in ops:\n splits = re.split('(\\\\d.*)', op)\n if len(splits) >= 2:\n key, value = splits[:2]\n options[key] = value\nstride_check = 's' in options and len(options['s']) == 1 or (len(options['s']) == 2 and options['s'][0] == options['s'][1]) o... | <|body_start_0|>
ops = block_string.split('_')
options = {}
for op in ops:
splits = re.split('(\\d.*)', op)
if len(splits) >= 2:
key, value = splits[:2]
options[key] = value
stride_check = 's' in options and len(options['s']) == 1 o... | BlockArgs object to assist in decoding string notation of arguments for MBConvBlock definition. | BlockArgs | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BlockArgs:
"""BlockArgs object to assist in decoding string notation of arguments for MBConvBlock definition."""
def from_string(block_string: str):
"""Get a BlockArgs object from a string notation of arguments. Args: block_string (str): A string notation of arguments. Examples: "r1_... | stack_v2_sparse_classes_10k_train_006737 | 40,667 | permissive | [
{
"docstring": "Get a BlockArgs object from a string notation of arguments. Args: block_string (str): A string notation of arguments. Examples: \"r1_k3_s11_e1_i32_o16_se0.25\". Returns: BlockArgs: namedtuple defined at the top of this function.",
"name": "from_string",
"signature": "def from_string(bloc... | 2 | stack_v2_sparse_classes_30k_train_006425 | Implement the Python class `BlockArgs` described below.
Class description:
BlockArgs object to assist in decoding string notation of arguments for MBConvBlock definition.
Method signatures and docstrings:
- def from_string(block_string: str): Get a BlockArgs object from a string notation of arguments. Args: block_str... | Implement the Python class `BlockArgs` described below.
Class description:
BlockArgs object to assist in decoding string notation of arguments for MBConvBlock definition.
Method signatures and docstrings:
- def from_string(block_string: str): Get a BlockArgs object from a string notation of arguments. Args: block_str... | e48c3e2c741fa3fc705c4425d17ac4a5afac6c47 | <|skeleton|>
class BlockArgs:
"""BlockArgs object to assist in decoding string notation of arguments for MBConvBlock definition."""
def from_string(block_string: str):
"""Get a BlockArgs object from a string notation of arguments. Args: block_string (str): A string notation of arguments. Examples: "r1_... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BlockArgs:
"""BlockArgs object to assist in decoding string notation of arguments for MBConvBlock definition."""
def from_string(block_string: str):
"""Get a BlockArgs object from a string notation of arguments. Args: block_string (str): A string notation of arguments. Examples: "r1_k3_s11_e1_i32... | the_stack_v2_python_sparse | monai/networks/nets/efficientnet.py | Project-MONAI/MONAI | train | 4,805 |
a9035bad76c1e9068b587c89e388b6f6cc41c029 | [
"if self.state_model.op_state in [DevState.FAULT, DevState.UNKNOWN, DevState.ON]:\n tango.Except.throw_exception(f'Disable() is not allowed in current state {self.state_model.op_state}', 'Failed to invoke Disable command on SdpMasterLeafNode.', 'SdpMasterLeafNode.Disable() ', tango.ErrSeverity.ERR)\nreturn True"... | <|body_start_0|>
if self.state_model.op_state in [DevState.FAULT, DevState.UNKNOWN, DevState.ON]:
tango.Except.throw_exception(f'Disable() is not allowed in current state {self.state_model.op_state}', 'Failed to invoke Disable command on SdpMasterLeafNode.', 'SdpMasterLeafNode.Disable() ', tango.Err... | A class for SDP master's Disable() command. Disable command is inherited from BaseCommand. Sets the State to Disable. | Disable | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Disable:
"""A class for SDP master's Disable() command. Disable command is inherited from BaseCommand. Sets the State to Disable."""
def check_allowed(self):
"""Check Whether this command is allowed to be run in current device state. :return: True if this command is allowed to be run... | stack_v2_sparse_classes_10k_train_006738 | 3,959 | permissive | [
{
"docstring": "Check Whether this command is allowed to be run in current device state. :return: True if this command is allowed to be run in current device state. :rtype: boolean :raises: DevFailed if this command is not allowed to be run in current device state.",
"name": "check_allowed",
"signature"... | 3 | stack_v2_sparse_classes_30k_train_005657 | Implement the Python class `Disable` described below.
Class description:
A class for SDP master's Disable() command. Disable command is inherited from BaseCommand. Sets the State to Disable.
Method signatures and docstrings:
- def check_allowed(self): Check Whether this command is allowed to be run in current device ... | Implement the Python class `Disable` described below.
Class description:
A class for SDP master's Disable() command. Disable command is inherited from BaseCommand. Sets the State to Disable.
Method signatures and docstrings:
- def check_allowed(self): Check Whether this command is allowed to be run in current device ... | 7ee65a9c8dada9b28893144b372a398bd0646195 | <|skeleton|>
class Disable:
"""A class for SDP master's Disable() command. Disable command is inherited from BaseCommand. Sets the State to Disable."""
def check_allowed(self):
"""Check Whether this command is allowed to be run in current device state. :return: True if this command is allowed to be run... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Disable:
"""A class for SDP master's Disable() command. Disable command is inherited from BaseCommand. Sets the State to Disable."""
def check_allowed(self):
"""Check Whether this command is allowed to be run in current device state. :return: True if this command is allowed to be run in current d... | the_stack_v2_python_sparse | temp_src/ska_tmc_sdpmasterleafnode_mid/disable_command.py | ska-telescope/tmc-prototype | train | 4 |
15e99ba95c604a8f555305823cf1d8d017f8a145 | [
"self.maxNumbers = maxNumbers\nself.used = set()\nself.freed = list()",
"if len(self.used) == self.maxNumbers:\n return -1\nif not self.freed:\n res = len(self.used)\nelse:\n res = self.freed.pop(0)\nself.used.add(res)\nreturn res",
"if number in self.used:\n return False\nreturn True",
"if number... | <|body_start_0|>
self.maxNumbers = maxNumbers
self.used = set()
self.freed = list()
<|end_body_0|>
<|body_start_1|>
if len(self.used) == self.maxNumbers:
return -1
if not self.freed:
res = len(self.used)
else:
res = self.freed.pop(0)
... | PhoneDirectory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PhoneDirectory:
def __init__(self, maxNumbers: int):
"""Initialize your data structure here @param maxNumbers - The maximum numbers that can be stored in the phone directory."""
<|body_0|>
def get(self) -> int:
"""Provide a number which is not assigned to anyone. @re... | stack_v2_sparse_classes_10k_train_006739 | 4,081 | no_license | [
{
"docstring": "Initialize your data structure here @param maxNumbers - The maximum numbers that can be stored in the phone directory.",
"name": "__init__",
"signature": "def __init__(self, maxNumbers: int)"
},
{
"docstring": "Provide a number which is not assigned to anyone. @return - Return an... | 4 | null | Implement the Python class `PhoneDirectory` described below.
Class description:
Implement the PhoneDirectory class.
Method signatures and docstrings:
- def __init__(self, maxNumbers: int): Initialize your data structure here @param maxNumbers - The maximum numbers that can be stored in the phone directory.
- def get(... | Implement the Python class `PhoneDirectory` described below.
Class description:
Implement the PhoneDirectory class.
Method signatures and docstrings:
- def __init__(self, maxNumbers: int): Initialize your data structure here @param maxNumbers - The maximum numbers that can be stored in the phone directory.
- def get(... | 6b24724da055a08510c83c645455eaa4ed201298 | <|skeleton|>
class PhoneDirectory:
def __init__(self, maxNumbers: int):
"""Initialize your data structure here @param maxNumbers - The maximum numbers that can be stored in the phone directory."""
<|body_0|>
def get(self) -> int:
"""Provide a number which is not assigned to anyone. @re... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PhoneDirectory:
def __init__(self, maxNumbers: int):
"""Initialize your data structure here @param maxNumbers - The maximum numbers that can be stored in the phone directory."""
self.maxNumbers = maxNumbers
self.used = set()
self.freed = list()
def get(self) -> int:
... | the_stack_v2_python_sparse | Design/python/leetcode/design_phone_directory.py | sankeerth/Algorithms | train | 0 | |
9e7a32ae9f6da41d06b0a066bc8fd2ff2d931ced | [
"for testvalue, expected in self.knownvalues:\n p = project.Project()\n for d in self.directions:\n for s in self.seasons:\n for f in self.frames:\n for l in self.layers:\n result = p.image_path(d, s, f, l, testvalue, validate=True)\n self... | <|body_start_0|>
for testvalue, expected in self.knownvalues:
p = project.Project()
for d in self.directions:
for s in self.seasons:
for f in self.frames:
for l in self.layers:
result = p.image_path(d... | Test image path validator and image path settings | image_path | [
"BSD-2-Clause",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class image_path:
"""Test image path validator and image path settings"""
def test_knownvalues_validate(self):
"""Test that known values are validated correctly"""
<|body_0|>
def test_knownvalues_set(self):
"""Test that known values are set correctly"""
<|body_... | stack_v2_sparse_classes_10k_train_006740 | 3,994 | permissive | [
{
"docstring": "Test that known values are validated correctly",
"name": "test_knownvalues_validate",
"signature": "def test_knownvalues_validate(self)"
},
{
"docstring": "Test that known values are set correctly",
"name": "test_knownvalues_set",
"signature": "def test_knownvalues_set(se... | 3 | stack_v2_sparse_classes_30k_train_001199 | Implement the Python class `image_path` described below.
Class description:
Test image path validator and image path settings
Method signatures and docstrings:
- def test_knownvalues_validate(self): Test that known values are validated correctly
- def test_knownvalues_set(self): Test that known values are set correct... | Implement the Python class `image_path` described below.
Class description:
Test image path validator and image path settings
Method signatures and docstrings:
- def test_knownvalues_validate(self): Test that known values are validated correctly
- def test_knownvalues_set(self): Test that known values are set correct... | 307a9de864566fece1a999888e19048aeef9734c | <|skeleton|>
class image_path:
"""Test image path validator and image path settings"""
def test_knownvalues_validate(self):
"""Test that known values are validated correctly"""
<|body_0|>
def test_knownvalues_set(self):
"""Test that known values are set correctly"""
<|body_... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class image_path:
"""Test image path validator and image path settings"""
def test_knownvalues_validate(self):
"""Test that known values are validated correctly"""
for testvalue, expected in self.knownvalues:
p = project.Project()
for d in self.directions:
... | the_stack_v2_python_sparse | project_test.py | An-dz/tilecutter | train | 4 |
828834957515fcb5d972577a44c7b92568fd54ec | [
"assert isinstance(reversible_blocks, nn.ModuleList)\nfor block in reversible_blocks:\n assert isinstance(block, ReversibleBlock)\n x = block(x)\nctx.y = x.detach()\nctx.reversible_blocks = reversible_blocks\nctx.eagerly_discard_variables = eagerly_discard_variables\nreturn x",
"y = ctx.y\nif ctx.eagerly_di... | <|body_start_0|>
assert isinstance(reversible_blocks, nn.ModuleList)
for block in reversible_blocks:
assert isinstance(block, ReversibleBlock)
x = block(x)
ctx.y = x.detach()
ctx.reversible_blocks = reversible_blocks
ctx.eagerly_discard_variables = eagerly... | Integrates the reversible sequence into the autograd framework | _ReversibleModuleFunction | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _ReversibleModuleFunction:
"""Integrates the reversible sequence into the autograd framework"""
def forward(ctx, x, reversible_blocks, eagerly_discard_variables):
"""Performs the forward pass of a reversible sequence within the autograd framework :param ctx: autograd context :param x... | stack_v2_sparse_classes_10k_train_006741 | 8,406 | no_license | [
{
"docstring": "Performs the forward pass of a reversible sequence within the autograd framework :param ctx: autograd context :param x: input tensor :param reversible_blocks: nn.Modulelist of reversible blocks :return: output tensor",
"name": "forward",
"signature": "def forward(ctx, x, reversible_block... | 2 | stack_v2_sparse_classes_30k_train_002052 | Implement the Python class `_ReversibleModuleFunction` described below.
Class description:
Integrates the reversible sequence into the autograd framework
Method signatures and docstrings:
- def forward(ctx, x, reversible_blocks, eagerly_discard_variables): Performs the forward pass of a reversible sequence within the... | Implement the Python class `_ReversibleModuleFunction` described below.
Class description:
Integrates the reversible sequence into the autograd framework
Method signatures and docstrings:
- def forward(ctx, x, reversible_blocks, eagerly_discard_variables): Performs the forward pass of a reversible sequence within the... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class _ReversibleModuleFunction:
"""Integrates the reversible sequence into the autograd framework"""
def forward(ctx, x, reversible_blocks, eagerly_discard_variables):
"""Performs the forward pass of a reversible sequence within the autograd framework :param ctx: autograd context :param x... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class _ReversibleModuleFunction:
"""Integrates the reversible sequence into the autograd framework"""
def forward(ctx, x, reversible_blocks, eagerly_discard_variables):
"""Performs the forward pass of a reversible sequence within the autograd framework :param ctx: autograd context :param x: input tenso... | the_stack_v2_python_sparse | generated/test_RobinBruegger_RevTorch.py | jansel/pytorch-jit-paritybench | train | 35 |
2768a94678051e1936abaac060d27f333c602d37 | [
"k %= len(nums)\nself.reverse(nums, 0, len(nums) - 1)\nself.reverse(nums, 0, k - 1)\nself.reverse(nums, k, len(nums) - 1)",
"while start < end:\n nums[start], nums[end] = (nums[end], nums[start])\n start += 1\n end -= 1"
] | <|body_start_0|>
k %= len(nums)
self.reverse(nums, 0, len(nums) - 1)
self.reverse(nums, 0, k - 1)
self.reverse(nums, k, len(nums) - 1)
<|end_body_0|>
<|body_start_1|>
while start < end:
nums[start], nums[end] = (nums[end], nums[start])
start += 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rotate(self, nums, k):
"""Do not return anything, modify nums in-place instead. Args: nums: list[int] k: int"""
<|body_0|>
def reverse(self, nums, start, end):
"""Args: nums: list[int] start: int end: int"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_10k_train_006742 | 1,342 | no_license | [
{
"docstring": "Do not return anything, modify nums in-place instead. Args: nums: list[int] k: int",
"name": "rotate",
"signature": "def rotate(self, nums, k)"
},
{
"docstring": "Args: nums: list[int] start: int end: int",
"name": "reverse",
"signature": "def reverse(self, nums, start, e... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, nums, k): Do not return anything, modify nums in-place instead. Args: nums: list[int] k: int
- def reverse(self, nums, start, end): Args: nums: list[int] start: ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, nums, k): Do not return anything, modify nums in-place instead. Args: nums: list[int] k: int
- def reverse(self, nums, start, end): Args: nums: list[int] start: ... | 101bce2fac8b188a4eb2f5e017293d21ad0ecb21 | <|skeleton|>
class Solution:
def rotate(self, nums, k):
"""Do not return anything, modify nums in-place instead. Args: nums: list[int] k: int"""
<|body_0|>
def reverse(self, nums, start, end):
"""Args: nums: list[int] start: int end: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def rotate(self, nums, k):
"""Do not return anything, modify nums in-place instead. Args: nums: list[int] k: int"""
k %= len(nums)
self.reverse(nums, 0, len(nums) - 1)
self.reverse(nums, 0, k - 1)
self.reverse(nums, k, len(nums) - 1)
def reverse(self, num... | the_stack_v2_python_sparse | code/189. 旋转数组.py | AiZhanghan/Leetcode | train | 0 | |
f42487cd68137f31655bb1896769dd2e504c68b7 | [
"super().__init__(name)\nself._image = image\nself._command = command\nself._volumes = volumes\nself._devices = devices\nself._environment = environment\nself._network = network\nself._shm_size = shm_size\nself._triton_exec = None\nself._logging_thread = None\nself._log_file_path = pathlib.Path(log_file)",
"devic... | <|body_start_0|>
super().__init__(name)
self._image = image
self._command = command
self._volumes = volumes
self._devices = devices
self._environment = environment
self._network = network
self._shm_size = shm_size
self._triton_exec = None
s... | TritonServerContainer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TritonServerContainer:
def __init__(self, name: str, command: str, image: str, volumes: Dict, devices: Union[list, int], environment: Dict, log_file: Union[pathlib.Path, str], network: str='host', shm_size: str='1G'):
"""Initialize Triton Server Container Args: name: Container name comma... | stack_v2_sparse_classes_10k_train_006743 | 5,403 | permissive | [
{
"docstring": "Initialize Triton Server Container Args: name: Container name command: Triton Server command to exec on container start image: Docker Image volumes: Volumes to mount inside container devices: Devices which has to be visible in container environment: Environment variables log_file: Path where log... | 5 | null | Implement the Python class `TritonServerContainer` described below.
Class description:
Implement the TritonServerContainer class.
Method signatures and docstrings:
- def __init__(self, name: str, command: str, image: str, volumes: Dict, devices: Union[list, int], environment: Dict, log_file: Union[pathlib.Path, str],... | Implement the Python class `TritonServerContainer` described below.
Class description:
Implement the TritonServerContainer class.
Method signatures and docstrings:
- def __init__(self, name: str, command: str, image: str, volumes: Dict, devices: Union[list, int], environment: Dict, log_file: Union[pathlib.Path, str],... | a5388a45f71a949639b35cc5b990bd130d2d8164 | <|skeleton|>
class TritonServerContainer:
def __init__(self, name: str, command: str, image: str, volumes: Dict, devices: Union[list, int], environment: Dict, log_file: Union[pathlib.Path, str], network: str='host', shm_size: str='1G'):
"""Initialize Triton Server Container Args: name: Container name comma... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TritonServerContainer:
def __init__(self, name: str, command: str, image: str, volumes: Dict, devices: Union[list, int], environment: Dict, log_file: Union[pathlib.Path, str], network: str='host', shm_size: str='1G'):
"""Initialize Triton Server Container Args: name: Container name command: Triton Ser... | the_stack_v2_python_sparse | PyTorch/LanguageModeling/BERT/triton/runner/maintainer/docker/containers/triton_server_container.py | NVIDIA/DeepLearningExamples | train | 11,838 | |
653d0e56877183e3b3e47cb2230dc65a5d0e150e | [
"scrolled.ScrolledPanel.__init__(self, parent, -1, size=(100, 500))\nself.visualizer = visualizer\nself.mode = mode\nself.sizer = wx.GridBagSizer()\nself.projectionBox = wx.RadioBox(self, -1, 'View projection', choices=['Max. IP', 'Avg. IP'], majorDimension=1, style=wx.RA_SPECIFY_COLS)\nself.updateButton = wx.Butto... | <|body_start_0|>
scrolled.ScrolledPanel.__init__(self, parent, -1, size=(100, 500))
self.visualizer = visualizer
self.mode = mode
self.sizer = wx.GridBagSizer()
self.projectionBox = wx.RadioBox(self, -1, 'View projection', choices=['Max. IP', 'Avg. IP'], majorDimension=1, style=w... | A configuration panel for the projection view | SimpleConfigurationPanel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimpleConfigurationPanel:
"""A configuration panel for the projection view"""
def __init__(self, parent, visualizer, mode, **kws):
"""Initialization"""
<|body_0|>
def onSetProjectionMode(self, event):
"""Configure what projection to show"""
<|body_1|>
<|... | stack_v2_sparse_classes_10k_train_006744 | 6,623 | no_license | [
{
"docstring": "Initialization",
"name": "__init__",
"signature": "def __init__(self, parent, visualizer, mode, **kws)"
},
{
"docstring": "Configure what projection to show",
"name": "onSetProjectionMode",
"signature": "def onSetProjectionMode(self, event)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000066 | Implement the Python class `SimpleConfigurationPanel` described below.
Class description:
A configuration panel for the projection view
Method signatures and docstrings:
- def __init__(self, parent, visualizer, mode, **kws): Initialization
- def onSetProjectionMode(self, event): Configure what projection to show | Implement the Python class `SimpleConfigurationPanel` described below.
Class description:
A configuration panel for the projection view
Method signatures and docstrings:
- def __init__(self, parent, visualizer, mode, **kws): Initialization
- def onSetProjectionMode(self, event): Configure what projection to show
<|s... | ea8bafa073de5090bd8f83fb4f5ca16669d0211f | <|skeleton|>
class SimpleConfigurationPanel:
"""A configuration panel for the projection view"""
def __init__(self, parent, visualizer, mode, **kws):
"""Initialization"""
<|body_0|>
def onSetProjectionMode(self, event):
"""Configure what projection to show"""
<|body_1|>
<|... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SimpleConfigurationPanel:
"""A configuration panel for the projection view"""
def __init__(self, parent, visualizer, mode, **kws):
"""Initialization"""
scrolled.ScrolledPanel.__init__(self, parent, -1, size=(100, 500))
self.visualizer = visualizer
self.mode = mode
... | the_stack_v2_python_sparse | Graphs/LX-2/molecule_otsu = False/BioImageXD-1.0/Modules/Visualization/Simple.py | giacomo21/Image-analysis | train | 1 |
5587c4f7dfff44dac2a119e2496c1c9512ac691a | [
"if model._meta.app_label == 'statis':\n return 'statis'\nreturn None",
"if model._meta.app_label == 'statis':\n return 'statis'\nreturn None",
"if obj1._meta.app_label == 'statis' or obj2._meta.app_label == 'statis':\n return True\nreturn None"
] | <|body_start_0|>
if model._meta.app_label == 'statis':
return 'statis'
return None
<|end_body_0|>
<|body_start_1|>
if model._meta.app_label == 'statis':
return 'statis'
return None
<|end_body_1|>
<|body_start_2|>
if obj1._meta.app_label == 'statis' or ob... | A router to control all database operations on models in the auth application. | StatisRouter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StatisRouter:
"""A router to control all database operations on models in the auth application."""
def db_for_read(self, model, **hints):
"""Attempts to read auth models go to auth_db."""
<|body_0|>
def db_for_write(self, model, **hints):
"""Attempts to write aut... | stack_v2_sparse_classes_10k_train_006745 | 1,986 | permissive | [
{
"docstring": "Attempts to read auth models go to auth_db.",
"name": "db_for_read",
"signature": "def db_for_read(self, model, **hints)"
},
{
"docstring": "Attempts to write auth models go to auth_db.",
"name": "db_for_write",
"signature": "def db_for_write(self, model, **hints)"
},
... | 3 | stack_v2_sparse_classes_30k_train_006435 | Implement the Python class `StatisRouter` described below.
Class description:
A router to control all database operations on models in the auth application.
Method signatures and docstrings:
- def db_for_read(self, model, **hints): Attempts to read auth models go to auth_db.
- def db_for_write(self, model, **hints): ... | Implement the Python class `StatisRouter` described below.
Class description:
A router to control all database operations on models in the auth application.
Method signatures and docstrings:
- def db_for_read(self, model, **hints): Attempts to read auth models go to auth_db.
- def db_for_write(self, model, **hints): ... | 38a551ad768b078278f749e8db8947a00827f1e5 | <|skeleton|>
class StatisRouter:
"""A router to control all database operations on models in the auth application."""
def db_for_read(self, model, **hints):
"""Attempts to read auth models go to auth_db."""
<|body_0|>
def db_for_write(self, model, **hints):
"""Attempts to write aut... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class StatisRouter:
"""A router to control all database operations on models in the auth application."""
def db_for_read(self, model, **hints):
"""Attempts to read auth models go to auth_db."""
if model._meta.app_label == 'statis':
return 'statis'
return None
def db_for... | the_stack_v2_python_sparse | web_project/app/dbrouter/router.py | cash2one/fruit | train | 0 |
0bda9f6572a872c51895eb44ebea3c386176da9a | [
"self._pt_1 = pt_3d_1\nself._pt_2 = pt_3d_2\nself._pt_3 = pt_3d_3",
"def versor3d(pt_1, pt_2):\n \"\"\"\n\n :param pt_1:\n :param pt_2:\n :return:\n \"\"\"\n return Segment(pt_1, pt_2).vector().versor_full()\n\ndef is_pt_in_fascio(pt_1, pt_2, pt_3):\n \"\"\"\n\... | <|body_start_0|>
self._pt_1 = pt_3d_1
self._pt_2 = pt_3d_2
self._pt_3 = pt_3d_3
<|end_body_0|>
<|body_start_1|>
def versor3d(pt_1, pt_2):
"""
:param pt_1:
:param pt_2:
:return:
"""
r... | CartesianTriangle | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CartesianTriangle:
def __init__(self, pt_3d_1, pt_3d_2, pt_3d_3):
""":param pt_3d_1: :param pt_3d_2: :param pt_3d_3:"""
<|body_0|>
def is_pt_within(self, pt_3d):
""":param pt_3d: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self._pt_1 = ... | stack_v2_sparse_classes_10k_train_006746 | 18,232 | no_license | [
{
"docstring": ":param pt_3d_1: :param pt_3d_2: :param pt_3d_3:",
"name": "__init__",
"signature": "def __init__(self, pt_3d_1, pt_3d_2, pt_3d_3)"
},
{
"docstring": ":param pt_3d: :return:",
"name": "is_pt_within",
"signature": "def is_pt_within(self, pt_3d)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006145 | Implement the Python class `CartesianTriangle` described below.
Class description:
Implement the CartesianTriangle class.
Method signatures and docstrings:
- def __init__(self, pt_3d_1, pt_3d_2, pt_3d_3): :param pt_3d_1: :param pt_3d_2: :param pt_3d_3:
- def is_pt_within(self, pt_3d): :param pt_3d: :return: | Implement the Python class `CartesianTriangle` described below.
Class description:
Implement the CartesianTriangle class.
Method signatures and docstrings:
- def __init__(self, pt_3d_1, pt_3d_2, pt_3d_3): :param pt_3d_1: :param pt_3d_2: :param pt_3d_3:
- def is_pt_within(self, pt_3d): :param pt_3d: :return:
<|skelet... | b07ab23400b4ff4151555c2e81392a7adf99fc33 | <|skeleton|>
class CartesianTriangle:
def __init__(self, pt_3d_1, pt_3d_2, pt_3d_3):
""":param pt_3d_1: :param pt_3d_2: :param pt_3d_3:"""
<|body_0|>
def is_pt_within(self, pt_3d):
""":param pt_3d: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CartesianTriangle:
def __init__(self, pt_3d_1, pt_3d_2, pt_3d_3):
""":param pt_3d_1: :param pt_3d_2: :param pt_3d_3:"""
self._pt_1 = pt_3d_1
self._pt_2 = pt_3d_2
self._pt_3 = pt_3d_3
def is_pt_within(self, pt_3d):
""":param pt_3d: :return:"""
def versor3d(p... | the_stack_v2_python_sparse | pygsf/spatial/vectorial/meshes.py | mauroalberti/qgSurf | train | 5 | |
d592c134d1f42716119ababe80909bd8d0ec0044 | [
"self._entity_ids = entity_ids\nself._attr_name = name\nself._attr_extra_state_attributes = {ATTR_ENTITY_ID: entity_ids}\nself._attr_unique_id = unique_id\nself._attr_event_types = []",
"@callback\ndef async_state_changed_listener(event: EventType[EventStateChangedData]) -> None:\n \"\"\"Handle child updates.\... | <|body_start_0|>
self._entity_ids = entity_ids
self._attr_name = name
self._attr_extra_state_attributes = {ATTR_ENTITY_ID: entity_ids}
self._attr_unique_id = unique_id
self._attr_event_types = []
<|end_body_0|>
<|body_start_1|>
@callback
def async_state_changed_l... | Representation of an event group. | EventGroup | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EventGroup:
"""Representation of an event group."""
def __init__(self, unique_id: str | None, name: str, entity_ids: list[str]) -> None:
"""Initialize an event group."""
<|body_0|>
async def async_added_to_hass(self) -> None:
"""Register callbacks."""
<|b... | stack_v2_sparse_classes_10k_train_006747 | 5,729 | permissive | [
{
"docstring": "Initialize an event group.",
"name": "__init__",
"signature": "def __init__(self, unique_id: str | None, name: str, entity_ids: list[str]) -> None"
},
{
"docstring": "Register callbacks.",
"name": "async_added_to_hass",
"signature": "async def async_added_to_hass(self) ->... | 3 | null | Implement the Python class `EventGroup` described below.
Class description:
Representation of an event group.
Method signatures and docstrings:
- def __init__(self, unique_id: str | None, name: str, entity_ids: list[str]) -> None: Initialize an event group.
- async def async_added_to_hass(self) -> None: Register call... | Implement the Python class `EventGroup` described below.
Class description:
Representation of an event group.
Method signatures and docstrings:
- def __init__(self, unique_id: str | None, name: str, entity_ids: list[str]) -> None: Initialize an event group.
- async def async_added_to_hass(self) -> None: Register call... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class EventGroup:
"""Representation of an event group."""
def __init__(self, unique_id: str | None, name: str, entity_ids: list[str]) -> None:
"""Initialize an event group."""
<|body_0|>
async def async_added_to_hass(self) -> None:
"""Register callbacks."""
<|b... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EventGroup:
"""Representation of an event group."""
def __init__(self, unique_id: str | None, name: str, entity_ids: list[str]) -> None:
"""Initialize an event group."""
self._entity_ids = entity_ids
self._attr_name = name
self._attr_extra_state_attributes = {ATTR_ENTITY_I... | the_stack_v2_python_sparse | homeassistant/components/group/event.py | home-assistant/core | train | 35,501 |
f1ba6b584cde4ab86970e3ca1c829b1fc9abaf9b | [
"if not nums:\n return []\nm = len(nums)\nres = []\nfor i in range(m):\n tmp = 0\n for j in range(i + 1, m):\n if nums[i] > nums[j]:\n tmp += 1\n res.append(tmp)\nreturn res",
"import bisect\nsortns = []\nres = []\nfor n in reversed(nums):\n idx = bisect.bisect_left(sortns, n)\n ... | <|body_start_0|>
if not nums:
return []
m = len(nums)
res = []
for i in range(m):
tmp = 0
for j in range(i + 1, m):
if nums[i] > nums[j]:
tmp += 1
res.append(tmp)
return res
<|end_body_0|>
<|body... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def countSmaller(self, nums):
"""暴力: O(n^2) 超时"""
<|body_0|>
def countSmaller1(self, nums):
"""逆序插入 数组反过来插入一个有序数组(降序)中,插入的位置就是在原数组中位于它右侧的元素的个数。 O(nlogn)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not nums:
return []
... | stack_v2_sparse_classes_10k_train_006748 | 968 | no_license | [
{
"docstring": "暴力: O(n^2) 超时",
"name": "countSmaller",
"signature": "def countSmaller(self, nums)"
},
{
"docstring": "逆序插入 数组反过来插入一个有序数组(降序)中,插入的位置就是在原数组中位于它右侧的元素的个数。 O(nlogn)",
"name": "countSmaller1",
"signature": "def countSmaller1(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001637 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countSmaller(self, nums): 暴力: O(n^2) 超时
- def countSmaller1(self, nums): 逆序插入 数组反过来插入一个有序数组(降序)中,插入的位置就是在原数组中位于它右侧的元素的个数。 O(nlogn) | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countSmaller(self, nums): 暴力: O(n^2) 超时
- def countSmaller1(self, nums): 逆序插入 数组反过来插入一个有序数组(降序)中,插入的位置就是在原数组中位于它右侧的元素的个数。 O(nlogn)
<|skeleton|>
class Solution:
def coun... | 57f303aa6e76f7c5292fa60bffdfddcb4ff9ddfb | <|skeleton|>
class Solution:
def countSmaller(self, nums):
"""暴力: O(n^2) 超时"""
<|body_0|>
def countSmaller1(self, nums):
"""逆序插入 数组反过来插入一个有序数组(降序)中,插入的位置就是在原数组中位于它右侧的元素的个数。 O(nlogn)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def countSmaller(self, nums):
"""暴力: O(n^2) 超时"""
if not nums:
return []
m = len(nums)
res = []
for i in range(m):
tmp = 0
for j in range(i + 1, m):
if nums[i] > nums[j]:
tmp += 1
... | the_stack_v2_python_sparse | 4_LEETCODE/1_DataStructure/5_TREE/2_TreeArray/315. 计算右侧小于当前元素的个数.py | fzingithub/SwordRefers2Offer | train | 1 | |
f7829bf4c540f1c02bc6e0d73f3bd8422b888847 | [
"super().__init__(force_update=force_update, sleeping_time=sleeping_time)\nassert self.entity_provider is not None\nassert self.entity_schema is not None\nself.exchanges = exchanges\nif codes is None and code is not None:\n self.codes = [code]\nelse:\n self.codes = codes\nself.day_data = day_data\nself.entity... | <|body_start_0|>
super().__init__(force_update=force_update, sleeping_time=sleeping_time)
assert self.entity_provider is not None
assert self.entity_schema is not None
self.exchanges = exchanges
if codes is None and code is not None:
self.codes = [code]
else:
... | EntityEventRecorder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EntityEventRecorder:
def __init__(self, force_update=False, sleeping_time=10, exchanges=None, entity_id=None, entity_ids=None, code=None, codes=None, day_data=False, entity_filters=None, ignore_failed=True) -> None:
""":param code: :param ignore_failed: :param entity_filters: :param exch... | stack_v2_sparse_classes_10k_train_006749 | 24,497 | permissive | [
{
"docstring": ":param code: :param ignore_failed: :param entity_filters: :param exchanges: :param entity_id: for record single entity :param entity_ids: set entity_ids or (entity_type,exchanges,codes) :param codes: :param day_data: one record per day,set to True if you want skip recording it when data of today... | 2 | stack_v2_sparse_classes_30k_train_000463 | Implement the Python class `EntityEventRecorder` described below.
Class description:
Implement the EntityEventRecorder class.
Method signatures and docstrings:
- def __init__(self, force_update=False, sleeping_time=10, exchanges=None, entity_id=None, entity_ids=None, code=None, codes=None, day_data=False, entity_filt... | Implement the Python class `EntityEventRecorder` described below.
Class description:
Implement the EntityEventRecorder class.
Method signatures and docstrings:
- def __init__(self, force_update=False, sleeping_time=10, exchanges=None, entity_id=None, entity_ids=None, code=None, codes=None, day_data=False, entity_filt... | 03aee869fd432bb933d59ba419401cfc11501392 | <|skeleton|>
class EntityEventRecorder:
def __init__(self, force_update=False, sleeping_time=10, exchanges=None, entity_id=None, entity_ids=None, code=None, codes=None, day_data=False, entity_filters=None, ignore_failed=True) -> None:
""":param code: :param ignore_failed: :param entity_filters: :param exch... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EntityEventRecorder:
def __init__(self, force_update=False, sleeping_time=10, exchanges=None, entity_id=None, entity_ids=None, code=None, codes=None, day_data=False, entity_filters=None, ignore_failed=True) -> None:
""":param code: :param ignore_failed: :param entity_filters: :param exchanges: :param ... | the_stack_v2_python_sparse | src/zvt/contract/recorder.py | zvtvz/zvt | train | 2,782 | |
fabe7a434ec485e953176a31b9c49f7aea655746 | [
"if node.op_type in OP_TYPES_WITH_PARAMS:\n if len(node.input) >= param_index + 1:\n param_name = node.input[param_index]\n for param in model.graph.initializer:\n if param.name == param_name:\n return param.dims\n assert 'Param not present in the node'\nelse:\n asse... | <|body_start_0|>
if node.op_type in OP_TYPES_WITH_PARAMS:
if len(node.input) >= param_index + 1:
param_name = node.input[param_index]
for param in model.graph.initializer:
if param.name == param_name:
return param.dims
... | Param utilities | ParamUtils | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParamUtils:
"""Param utilities"""
def get_shape(model: onnx_pb.ModelProto, node: onnx_pb.NodeProto, param_index: int) -> List:
"""Returns a list of shape for the param specifies :param model: ONNX model :param node: ONNX node to which the param feeds to :param param_index: Index at w... | stack_v2_sparse_classes_10k_train_006750 | 17,157 | permissive | [
{
"docstring": "Returns a list of shape for the param specifies :param model: ONNX model :param node: ONNX node to which the param feeds to :param param_index: Index at which param feeds to the ONNX node",
"name": "get_shape",
"signature": "def get_shape(model: onnx_pb.ModelProto, node: onnx_pb.NodeProt... | 2 | stack_v2_sparse_classes_30k_train_005490 | Implement the Python class `ParamUtils` described below.
Class description:
Param utilities
Method signatures and docstrings:
- def get_shape(model: onnx_pb.ModelProto, node: onnx_pb.NodeProto, param_index: int) -> List: Returns a list of shape for the param specifies :param model: ONNX model :param node: ONNX node t... | Implement the Python class `ParamUtils` described below.
Class description:
Param utilities
Method signatures and docstrings:
- def get_shape(model: onnx_pb.ModelProto, node: onnx_pb.NodeProto, param_index: int) -> List: Returns a list of shape for the param specifies :param model: ONNX model :param node: ONNX node t... | 5a406e657082b6a4f6e4bf48f0e46e085cb1e351 | <|skeleton|>
class ParamUtils:
"""Param utilities"""
def get_shape(model: onnx_pb.ModelProto, node: onnx_pb.NodeProto, param_index: int) -> List:
"""Returns a list of shape for the param specifies :param model: ONNX model :param node: ONNX node to which the param feeds to :param param_index: Index at w... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ParamUtils:
"""Param utilities"""
def get_shape(model: onnx_pb.ModelProto, node: onnx_pb.NodeProto, param_index: int) -> List:
"""Returns a list of shape for the param specifies :param model: ONNX model :param node: ONNX node to which the param feeds to :param param_index: Index at which param fe... | the_stack_v2_python_sparse | TrainingExtensions/onnx/src/python/aimet_onnx/utils.py | quic/aimet | train | 1,676 |
2a011e14734a9bb742faf657d1b2d6b629697d31 | [
"n = len(nums)\nif val not in nums:\n return n\nleft, right = (0, 0)\nwhile left < n - 1 and right < n:\n if nums[left] != val:\n left += 1\n continue\n if right == 0:\n right = left + 1\n if nums[right] == val:\n right += 1\n continue\n nums[left], nums[right] = (n... | <|body_start_0|>
n = len(nums)
if val not in nums:
return n
left, right = (0, 0)
while left < n - 1 and right < n:
if nums[left] != val:
left += 1
continue
if right == 0:
right = left + 1
if n... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
"""双指针。"""
<|body_0|>
def removeElement2(self, nums: List[int], val: int) -> int:
"""双指针。"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n = len(nums)
if val not in nums:
... | stack_v2_sparse_classes_10k_train_006751 | 3,564 | no_license | [
{
"docstring": "双指针。",
"name": "removeElement",
"signature": "def removeElement(self, nums: List[int], val: int) -> int"
},
{
"docstring": "双指针。",
"name": "removeElement2",
"signature": "def removeElement2(self, nums: List[int], val: int) -> int"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeElement(self, nums: List[int], val: int) -> int: 双指针。
- def removeElement2(self, nums: List[int], val: int) -> int: 双指针。 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeElement(self, nums: List[int], val: int) -> int: 双指针。
- def removeElement2(self, nums: List[int], val: int) -> int: 双指针。
<|skeleton|>
class Solution:
def removeEl... | 6932d69353b94ec824dd0ddc86a92453f6673232 | <|skeleton|>
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
"""双指针。"""
<|body_0|>
def removeElement2(self, nums: List[int], val: int) -> int:
"""双指针。"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
"""双指针。"""
n = len(nums)
if val not in nums:
return n
left, right = (0, 0)
while left < n - 1 and right < n:
if nums[left] != val:
left += 1
cont... | the_stack_v2_python_sparse | 0027_remove-element.py | Nigirimeshi/leetcode | train | 0 | |
07a5a08de00dfad9ee22820ed6e10c7b44eca0e9 | [
"if len(names) == 0:\n self._leader = None\nelse:\n self._leader = Person(names[0])\n current_person = self._leader\n for name in names[1:]:\n current_person.next = Person(name)\n current_person = current_person.next",
"if self._leader is None:\n raise ShortChainError\nelse:\n retu... | <|body_start_0|>
if len(names) == 0:
self._leader = None
else:
self._leader = Person(names[0])
current_person = self._leader
for name in names[1:]:
current_person.next = Person(name)
current_person = current_person.next
<|en... | A chain of people. | PeopleChain | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PeopleChain:
"""A chain of people."""
def __init__(self, names):
"""Create people linked together in the order provided in <names>. The leader of the chain is the first person in <names>. @type self: PeopleChain @type names: list[str] @rtype: None"""
<|body_0|>
def get_l... | stack_v2_sparse_classes_10k_train_006752 | 2,417 | no_license | [
{
"docstring": "Create people linked together in the order provided in <names>. The leader of the chain is the first person in <names>. @type self: PeopleChain @type names: list[str] @rtype: None",
"name": "__init__",
"signature": "def __init__(self, names)"
},
{
"docstring": "Return the name of... | 2 | stack_v2_sparse_classes_30k_train_001190 | Implement the Python class `PeopleChain` described below.
Class description:
A chain of people.
Method signatures and docstrings:
- def __init__(self, names): Create people linked together in the order provided in <names>. The leader of the chain is the first person in <names>. @type self: PeopleChain @type names: li... | Implement the Python class `PeopleChain` described below.
Class description:
A chain of people.
Method signatures and docstrings:
- def __init__(self, names): Create people linked together in the order provided in <names>. The leader of the chain is the first person in <names>. @type self: PeopleChain @type names: li... | e00ae4246165e031b00cb7be0e9c0c1d60d49a75 | <|skeleton|>
class PeopleChain:
"""A chain of people."""
def __init__(self, names):
"""Create people linked together in the order provided in <names>. The leader of the chain is the first person in <names>. @type self: PeopleChain @type names: list[str] @rtype: None"""
<|body_0|>
def get_l... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PeopleChain:
"""A chain of people."""
def __init__(self, names):
"""Create people linked together in the order provided in <names>. The leader of the chain is the first person in <names>. @type self: PeopleChain @type names: list[str] @rtype: None"""
if len(names) == 0:
self._... | the_stack_v2_python_sparse | python_class_proj/pycharm/csc148/exercises/ex2/tsets.py | Mohan-Zhang-u/From_UofT | train | 0 |
6c7b92d711a3149db2cf5a313b492ffda70a088a | [
"super().__init__(*args, **kwargs)\nself.num_parallel_samples = num_parallel_samples\nself.sample_noise = sample_noise",
"kernel_args, sigma = self.get_gp_params(F, past_target, past_time_feat, feat_static_cat)\ngp = GaussianProcess(sigma=sigma, kernel=self.kernel_output.kernel(kernel_args), context_length=self.c... | <|body_start_0|>
super().__init__(*args, **kwargs)
self.num_parallel_samples = num_parallel_samples
self.sample_noise = sample_noise
<|end_body_0|>
<|body_start_1|>
kernel_args, sigma = self.get_gp_params(F, past_target, past_time_feat, feat_static_cat)
gp = GaussianProcess(sigm... | GaussianProcessPredictionNetwork | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GaussianProcessPredictionNetwork:
def __init__(self, num_parallel_samples: int, sample_noise: bool, *args, **kwargs) -> None:
"""Parameters ---------- num_parallel_samples Number of samples to be drawn. sample_noise Boolean to determine whether to add :math:`\\sigma^2I` to the predictive... | stack_v2_sparse_classes_10k_train_006753 | 9,486 | permissive | [
{
"docstring": "Parameters ---------- num_parallel_samples Number of samples to be drawn. sample_noise Boolean to determine whether to add :math:`\\\\sigma^2I` to the predictive covariance matrix. *args Variable length argument list. **kwargs Arbitrary keyword arguments.",
"name": "__init__",
"signature... | 2 | null | Implement the Python class `GaussianProcessPredictionNetwork` described below.
Class description:
Implement the GaussianProcessPredictionNetwork class.
Method signatures and docstrings:
- def __init__(self, num_parallel_samples: int, sample_noise: bool, *args, **kwargs) -> None: Parameters ---------- num_parallel_sam... | Implement the Python class `GaussianProcessPredictionNetwork` described below.
Class description:
Implement the GaussianProcessPredictionNetwork class.
Method signatures and docstrings:
- def __init__(self, num_parallel_samples: int, sample_noise: bool, *args, **kwargs) -> None: Parameters ---------- num_parallel_sam... | df4256b0e67120db555c109a1bf6cfa2b3bd3cd8 | <|skeleton|>
class GaussianProcessPredictionNetwork:
def __init__(self, num_parallel_samples: int, sample_noise: bool, *args, **kwargs) -> None:
"""Parameters ---------- num_parallel_samples Number of samples to be drawn. sample_noise Boolean to determine whether to add :math:`\\sigma^2I` to the predictive... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GaussianProcessPredictionNetwork:
def __init__(self, num_parallel_samples: int, sample_noise: bool, *args, **kwargs) -> None:
"""Parameters ---------- num_parallel_samples Number of samples to be drawn. sample_noise Boolean to determine whether to add :math:`\\sigma^2I` to the predictive covariance ma... | the_stack_v2_python_sparse | src/gluonts/model/gp_forecaster/_network.py | mbohlkeschneider/gluon-ts | train | 54 | |
7f9335ddca10a3ee38c897d2fe124757df4832be | [
"if server_ip == '' and server_port != 0 or (server_ip != '' and server_port == 0):\n raise Exception('server_ip和server_port必须同时指定')\nself._server_ip = server_ip\nself._server_port = server_port\nself._service_name = service_name\nself._host = host",
"headers = {'org': org, 'user': user}\nroute_name = ''\nserv... | <|body_start_0|>
if server_ip == '' and server_port != 0 or (server_ip != '' and server_port == 0):
raise Exception('server_ip和server_port必须同时指定')
self._server_ip = server_ip
self._server_port = server_port
self._service_name = service_name
self._host = host
<|end_bod... | CollectorHistoryClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CollectorHistoryClient:
def __init__(self, server_ip='', server_port=0, service_name='', host=''):
"""初始化client :param server_ip: 指定sdk请求的server_ip,为空时走名字服务路由 :param server_port: 指定sdk请求的server_port,与server_ip一起使用, 为空时走名字服务路由 :param service_name: 指定sdk请求的service_name, 为空时按契约名称路由。如果server... | stack_v2_sparse_classes_10k_train_006754 | 3,038 | permissive | [
{
"docstring": "初始化client :param server_ip: 指定sdk请求的server_ip,为空时走名字服务路由 :param server_port: 指定sdk请求的server_port,与server_ip一起使用, 为空时走名字服务路由 :param service_name: 指定sdk请求的service_name, 为空时按契约名称路由。如果server_ip和service_name同时设置,server_ip优先级更高 :param host: 指定sdk请求服务的host名称, 如cmdb.easyops-only.com",
"name": "__ini... | 2 | null | Implement the Python class `CollectorHistoryClient` described below.
Class description:
Implement the CollectorHistoryClient class.
Method signatures and docstrings:
- def __init__(self, server_ip='', server_port=0, service_name='', host=''): 初始化client :param server_ip: 指定sdk请求的server_ip,为空时走名字服务路由 :param server_port... | Implement the Python class `CollectorHistoryClient` described below.
Class description:
Implement the CollectorHistoryClient class.
Method signatures and docstrings:
- def __init__(self, server_ip='', server_port=0, service_name='', host=''): 初始化client :param server_ip: 指定sdk请求的server_ip,为空时走名字服务路由 :param server_port... | adf6e3bad33fa6266b5fa0a449dd4ac42f8447d0 | <|skeleton|>
class CollectorHistoryClient:
def __init__(self, server_ip='', server_port=0, service_name='', host=''):
"""初始化client :param server_ip: 指定sdk请求的server_ip,为空时走名字服务路由 :param server_port: 指定sdk请求的server_port,与server_ip一起使用, 为空时走名字服务路由 :param service_name: 指定sdk请求的service_name, 为空时按契约名称路由。如果server... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CollectorHistoryClient:
def __init__(self, server_ip='', server_port=0, service_name='', host=''):
"""初始化client :param server_ip: 指定sdk请求的server_ip,为空时走名字服务路由 :param server_port: 指定sdk请求的server_port,与server_ip一起使用, 为空时走名字服务路由 :param service_name: 指定sdk请求的service_name, 为空时按契约名称路由。如果server_ip和service_na... | the_stack_v2_python_sparse | resource_manage_sdk/api/collector_history/collector_history_client.py | easyopsapis/easyops-api-python | train | 5 | |
8dc399961b337d8324ae2ef537fed33ca75f82cd | [
"super(WikiParser, self).__init__(base_url)\nself.inclusions = [doc_id] if doc_id else []\nself.registerInternalLinkHook('Include', self._hook_include)\nself.registerInternalLinkHook('I', self._hook_include)\nself.registerInternalLinkHook('Template', self._hook_template)\nself.registerInternalLinkHook('T', self._ho... | <|body_start_0|>
super(WikiParser, self).__init__(base_url)
self.inclusions = [doc_id] if doc_id else []
self.registerInternalLinkHook('Include', self._hook_include)
self.registerInternalLinkHook('I', self._hook_include)
self.registerInternalLinkHook('Template', self._hook_templa... | An extension of the parser from the forums adding more crazy features {for} tags, inclusions, and templates--oh my! | WikiParser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WikiParser:
"""An extension of the parser from the forums adding more crazy features {for} tags, inclusions, and templates--oh my!"""
def __init__(self, base_url=None, doc_id=None):
"""doc_id -- If you want to be nice, pass the ID of the Document you are rendering. This will make rec... | stack_v2_sparse_classes_10k_train_006755 | 19,586 | permissive | [
{
"docstring": "doc_id -- If you want to be nice, pass the ID of the Document you are rendering. This will make recursive inclusions fail immediately rather than after the first round of recursion.",
"name": "__init__",
"signature": "def __init__(self, base_url=None, doc_id=None)"
},
{
"docstrin... | 4 | null | Implement the Python class `WikiParser` described below.
Class description:
An extension of the parser from the forums adding more crazy features {for} tags, inclusions, and templates--oh my!
Method signatures and docstrings:
- def __init__(self, base_url=None, doc_id=None): doc_id -- If you want to be nice, pass the... | Implement the Python class `WikiParser` described below.
Class description:
An extension of the parser from the forums adding more crazy features {for} tags, inclusions, and templates--oh my!
Method signatures and docstrings:
- def __init__(self, base_url=None, doc_id=None): doc_id -- If you want to be nice, pass the... | 67ec527bfc32c715bf9f29d5e01362c4903aebd2 | <|skeleton|>
class WikiParser:
"""An extension of the parser from the forums adding more crazy features {for} tags, inclusions, and templates--oh my!"""
def __init__(self, base_url=None, doc_id=None):
"""doc_id -- If you want to be nice, pass the ID of the Document you are rendering. This will make rec... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class WikiParser:
"""An extension of the parser from the forums adding more crazy features {for} tags, inclusions, and templates--oh my!"""
def __init__(self, base_url=None, doc_id=None):
"""doc_id -- If you want to be nice, pass the ID of the Document you are rendering. This will make recursive inclus... | the_stack_v2_python_sparse | kitsune/wiki/parser.py | mozilla/kitsune | train | 1,218 |
215c8ce6eea8bb844c7171d1b8b43276d9381cb5 | [
"key = cache_key('followers', obj.pk, obj.__class__.__name__)\nfollowers = cache.get(key)\nif followers is None:\n follower_classname = obj.__class__.__name__.lower()\n qs = Follow.objects.select_related('follower').filter(object_id=obj.pk, content_type__model=follower_classname)\n followers = [u.follower ... | <|body_start_0|>
key = cache_key('followers', obj.pk, obj.__class__.__name__)
followers = cache.get(key)
if followers is None:
follower_classname = obj.__class__.__name__.lower()
qs = Follow.objects.select_related('follower').filter(object_id=obj.pk, content_type__model=f... | Following manager | FollowingManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FollowingManager:
"""Following manager"""
def followers(self, obj):
"""Return a list of all followers"""
<|body_0|>
def following(self, user, followee_class):
"""Return a list of all objects of the followee_class the given user follows"""
<|body_1|>
... | stack_v2_sparse_classes_10k_train_006756 | 5,784 | no_license | [
{
"docstring": "Return a list of all followers",
"name": "followers",
"signature": "def followers(self, obj)"
},
{
"docstring": "Return a list of all objects of the followee_class the given user follows",
"name": "following",
"signature": "def following(self, user, followee_class)"
},
... | 5 | stack_v2_sparse_classes_30k_train_004282 | Implement the Python class `FollowingManager` described below.
Class description:
Following manager
Method signatures and docstrings:
- def followers(self, obj): Return a list of all followers
- def following(self, user, followee_class): Return a list of all objects of the followee_class the given user follows
- def ... | Implement the Python class `FollowingManager` described below.
Class description:
Following manager
Method signatures and docstrings:
- def followers(self, obj): Return a list of all followers
- def following(self, user, followee_class): Return a list of all objects of the followee_class the given user follows
- def ... | 4f7aa41fd0697af61539efd1aba2062addb63009 | <|skeleton|>
class FollowingManager:
"""Following manager"""
def followers(self, obj):
"""Return a list of all followers"""
<|body_0|>
def following(self, user, followee_class):
"""Return a list of all objects of the followee_class the given user follows"""
<|body_1|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FollowingManager:
"""Following manager"""
def followers(self, obj):
"""Return a list of all followers"""
key = cache_key('followers', obj.pk, obj.__class__.__name__)
followers = cache.get(key)
if followers is None:
follower_classname = obj.__class__.__name__.lo... | the_stack_v2_python_sparse | barddo/follow/models.py | bruno-ortiz/barddo | train | 0 |
2e881321078ed1895683f2270c89801624f32e97 | [
"self.tlen = tlen\nself.delta_f = delta_f\nself.dtype = dtype\nself.snr_threshold = snr_threshold\nself.flow = low_frequency_cutoff\nself.fhigh = high_frequency_cutoff\nself.matched_filter_and_cluster = self.full_matched_filter_and_cluster\nself.snr_plus_mem = zeros(self.tlen, dtype=self.dtype)\nself.corr_plus_mem ... | <|body_start_0|>
self.tlen = tlen
self.delta_f = delta_f
self.dtype = dtype
self.snr_threshold = snr_threshold
self.flow = low_frequency_cutoff
self.fhigh = high_frequency_cutoff
self.matched_filter_and_cluster = self.full_matched_filter_and_cluster
self.s... | MatchedFilterSkyMaxControl | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MatchedFilterSkyMaxControl:
def __init__(self, low_frequency_cutoff, high_frequency_cutoff, snr_threshold, tlen, delta_f, dtype):
"""Create a matched filter engine. Parameters ---------- low_frequency_cutoff : {None, float}, optional The frequency to begin the filter calculation. If None... | stack_v2_sparse_classes_10k_train_006757 | 49,102 | no_license | [
{
"docstring": "Create a matched filter engine. Parameters ---------- low_frequency_cutoff : {None, float}, optional The frequency to begin the filter calculation. If None, begin at the first frequency after DC. high_frequency_cutoff : {None, float}, optional The frequency to stop the filter calculation. If Non... | 2 | null | Implement the Python class `MatchedFilterSkyMaxControl` described below.
Class description:
Implement the MatchedFilterSkyMaxControl class.
Method signatures and docstrings:
- def __init__(self, low_frequency_cutoff, high_frequency_cutoff, snr_threshold, tlen, delta_f, dtype): Create a matched filter engine. Paramete... | Implement the Python class `MatchedFilterSkyMaxControl` described below.
Class description:
Implement the MatchedFilterSkyMaxControl class.
Method signatures and docstrings:
- def __init__(self, low_frequency_cutoff, high_frequency_cutoff, snr_threshold, tlen, delta_f, dtype): Create a matched filter engine. Paramete... | bd9d481ca1ad183bfe9802408830c71eb8aa3b58 | <|skeleton|>
class MatchedFilterSkyMaxControl:
def __init__(self, low_frequency_cutoff, high_frequency_cutoff, snr_threshold, tlen, delta_f, dtype):
"""Create a matched filter engine. Parameters ---------- low_frequency_cutoff : {None, float}, optional The frequency to begin the filter calculation. If None... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MatchedFilterSkyMaxControl:
def __init__(self, low_frequency_cutoff, high_frequency_cutoff, snr_threshold, tlen, delta_f, dtype):
"""Create a matched filter engine. Parameters ---------- low_frequency_cutoff : {None, float}, optional The frequency to begin the filter calculation. If None, begin at the... | the_stack_v2_python_sparse | pycbc/filter/matchedfilter.py | mbejger/pycbc | train | 2 | |
fe112d44d20a4ab18a5484315af5045c967f735f | [
"if result == []:\n result.append(target)\n return result\nfirst = 0\nlast = len(result) - 1\nwhile last - first > 1:\n mid = (first + last) // 2\n if result[mid] > target:\n last = mid\n else:\n first = mid\nif result[first] >= target:\n result[first] = target\nelif result[last] >= ... | <|body_start_0|>
if result == []:
result.append(target)
return result
first = 0
last = len(result) - 1
while last - first > 1:
mid = (first + last) // 2
if result[mid] > target:
last = mid
else:
f... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def binaryinsert(self, result, target):
""":type result: list :type target: int"""
<|body_0|>
def lengthOfLIS(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if result == []:
re... | stack_v2_sparse_classes_10k_train_006758 | 993 | no_license | [
{
"docstring": ":type result: list :type target: int",
"name": "binaryinsert",
"signature": "def binaryinsert(self, result, target)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "lengthOfLIS",
"signature": "def lengthOfLIS(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000061 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def binaryinsert(self, result, target): :type result: list :type target: int
- def lengthOfLIS(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 binaryinsert(self, result, target): :type result: list :type target: int
- def lengthOfLIS(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
d... | 9bd2d706f014ce84356ba38fc7801da0285a91d3 | <|skeleton|>
class Solution:
def binaryinsert(self, result, target):
""":type result: list :type target: int"""
<|body_0|>
def lengthOfLIS(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def binaryinsert(self, result, target):
""":type result: list :type target: int"""
if result == []:
result.append(target)
return result
first = 0
last = len(result) - 1
while last - first > 1:
mid = (first + last) // 2
... | the_stack_v2_python_sparse | leetcode/lengthOfLIS-300.py | pittcat/Algorithm_Practice | train | 0 | |
494a613e76dbacf68cf0840eb6dba43f5c1e567d | [
"try:\n params = request._serialize()\n headers = request.headers\n body = self.call('ImageToImage', params, headers=headers)\n response = json.loads(body)\n model = models.ImageToImageResponse()\n model._deserialize(response['Response'])\n return model\nexcept Exception as e:\n if isinstanc... | <|body_start_0|>
try:
params = request._serialize()
headers = request.headers
body = self.call('ImageToImage', params, headers=headers)
response = json.loads(body)
model = models.ImageToImageResponse()
model._deserialize(response['Response'... | AiartClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AiartClient:
def ImageToImage(self, request):
"""智能图生图接口将根据输入的图片及辅助描述文本,智能生成与之相关的结果图。 输入:单边分辨率小于2000、转成 Base64 字符串后小于 5MB 的图片,建议同时输入描述文本。 输出:对应风格及分辨率的 AI 生成图。 可支持的风格详见 [智能图生图风格列表](https://cloud.tencent.com/document/product/1668/86250),请将列表中的“风格编号”传入 Styles 数组,建议选择一种风格。 请求频率限制为1次/秒。 :para... | stack_v2_sparse_classes_10k_train_006759 | 3,676 | permissive | [
{
"docstring": "智能图生图接口将根据输入的图片及辅助描述文本,智能生成与之相关的结果图。 输入:单边分辨率小于2000、转成 Base64 字符串后小于 5MB 的图片,建议同时输入描述文本。 输出:对应风格及分辨率的 AI 生成图。 可支持的风格详见 [智能图生图风格列表](https://cloud.tencent.com/document/product/1668/86250),请将列表中的“风格编号”传入 Styles 数组,建议选择一种风格。 请求频率限制为1次/秒。 :param request: Request instance for ImageToImage. :type reque... | 2 | null | Implement the Python class `AiartClient` described below.
Class description:
Implement the AiartClient class.
Method signatures and docstrings:
- def ImageToImage(self, request): 智能图生图接口将根据输入的图片及辅助描述文本,智能生成与之相关的结果图。 输入:单边分辨率小于2000、转成 Base64 字符串后小于 5MB 的图片,建议同时输入描述文本。 输出:对应风格及分辨率的 AI 生成图。 可支持的风格详见 [智能图生图风格列表](https://... | Implement the Python class `AiartClient` described below.
Class description:
Implement the AiartClient class.
Method signatures and docstrings:
- def ImageToImage(self, request): 智能图生图接口将根据输入的图片及辅助描述文本,智能生成与之相关的结果图。 输入:单边分辨率小于2000、转成 Base64 字符串后小于 5MB 的图片,建议同时输入描述文本。 输出:对应风格及分辨率的 AI 生成图。 可支持的风格详见 [智能图生图风格列表](https://... | 6baf00a5a56ba58b6a1123423e0a1422d17a0201 | <|skeleton|>
class AiartClient:
def ImageToImage(self, request):
"""智能图生图接口将根据输入的图片及辅助描述文本,智能生成与之相关的结果图。 输入:单边分辨率小于2000、转成 Base64 字符串后小于 5MB 的图片,建议同时输入描述文本。 输出:对应风格及分辨率的 AI 生成图。 可支持的风格详见 [智能图生图风格列表](https://cloud.tencent.com/document/product/1668/86250),请将列表中的“风格编号”传入 Styles 数组,建议选择一种风格。 请求频率限制为1次/秒。 :para... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AiartClient:
def ImageToImage(self, request):
"""智能图生图接口将根据输入的图片及辅助描述文本,智能生成与之相关的结果图。 输入:单边分辨率小于2000、转成 Base64 字符串后小于 5MB 的图片,建议同时输入描述文本。 输出:对应风格及分辨率的 AI 生成图。 可支持的风格详见 [智能图生图风格列表](https://cloud.tencent.com/document/product/1668/86250),请将列表中的“风格编号”传入 Styles 数组,建议选择一种风格。 请求频率限制为1次/秒。 :param request: Req... | the_stack_v2_python_sparse | tencentcloud/aiart/v20221229/aiart_client.py | TencentCloud/tencentcloud-sdk-python | train | 594 | |
0ee6b97f1af112dc4cb78cd78a37fe62d3de36a9 | [
"email_log = EMAIL_TIMES[self.level]\nemail_backlog = EMAIL_BACKLOG[self.level]\nnow = time.time()\noldest_email_time = min(email_log)\nif oldest_email_time < now - EMAIL_THROTTLE_TIME:\n email_log.append(now)\n if len(email_backlog) > 0:\n backlog = '\\n'.join(email_backlog)\n record.msg = str(... | <|body_start_0|>
email_log = EMAIL_TIMES[self.level]
email_backlog = EMAIL_BACKLOG[self.level]
now = time.time()
oldest_email_time = min(email_log)
if oldest_email_time < now - EMAIL_THROTTLE_TIME:
email_log.append(now)
if len(email_backlog) > 0:
... | PyExpLabSys modified SMTP handler | CustomSMTPHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomSMTPHandler:
"""PyExpLabSys modified SMTP handler"""
def emit(self, record):
"""Custom emit that throttles the number of email sent"""
<|body_0|>
def getSubject(self, record):
"""Returns subject with hostname"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_10k_train_006760 | 7,447 | no_license | [
{
"docstring": "Custom emit that throttles the number of email sent",
"name": "emit",
"signature": "def emit(self, record)"
},
{
"docstring": "Returns subject with hostname",
"name": "getSubject",
"signature": "def getSubject(self, record)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002342 | Implement the Python class `CustomSMTPHandler` described below.
Class description:
PyExpLabSys modified SMTP handler
Method signatures and docstrings:
- def emit(self, record): Custom emit that throttles the number of email sent
- def getSubject(self, record): Returns subject with hostname | Implement the Python class `CustomSMTPHandler` described below.
Class description:
PyExpLabSys modified SMTP handler
Method signatures and docstrings:
- def emit(self, record): Custom emit that throttles the number of email sent
- def getSubject(self, record): Returns subject with hostname
<|skeleton|>
class CustomS... | 14d2a24c3031a78da0d2d686c42bc01ffe18faca | <|skeleton|>
class CustomSMTPHandler:
"""PyExpLabSys modified SMTP handler"""
def emit(self, record):
"""Custom emit that throttles the number of email sent"""
<|body_0|>
def getSubject(self, record):
"""Returns subject with hostname"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CustomSMTPHandler:
"""PyExpLabSys modified SMTP handler"""
def emit(self, record):
"""Custom emit that throttles the number of email sent"""
email_log = EMAIL_TIMES[self.level]
email_backlog = EMAIL_BACKLOG[self.level]
now = time.time()
oldest_email_time = min(emai... | the_stack_v2_python_sparse | PyExpLabSys/common/utilities.py | jlopezBolt/PyExpLabSys | train | 0 |
fa8fc943a3ed3989ac740a4ba965bd855eb29dfe | [
"check_type(session, RestSession)\nsuper(AdminAuditEventsAPI, self).__init__()\nself._session = session\nself._object_factory = object_factory",
"check_type(orgId, basestring)\ncheck_type(_from, basestring)\ncheck_type(to, basestring)\ncheck_type(actorId, basestring, optional=True)\ncheck_type(max, int)\ncheck_ty... | <|body_start_0|>
check_type(session, RestSession)
super(AdminAuditEventsAPI, self).__init__()
self._session = session
self._object_factory = object_factory
<|end_body_0|>
<|body_start_1|>
check_type(orgId, basestring)
check_type(_from, basestring)
check_type(to, ... | Admin Audit Events API. Wraps the Webex Teams Admin Audit Events API and exposes the API as native Python methods that return native Python objects. | AdminAuditEventsAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdminAuditEventsAPI:
"""Admin Audit Events API. Wraps the Webex Teams Admin Audit Events API and exposes the API as native Python methods that return native Python objects."""
def __init__(self, session, object_factory):
"""Init a new AdminAuditEventsAPI object with the provided Rest... | stack_v2_sparse_classes_10k_train_006761 | 4,953 | permissive | [
{
"docstring": "Init a new AdminAuditEventsAPI object with the provided RestSession. Args: session(RestSession): The RESTful session object to be used for API calls to the Webex Teams service. Raises: TypeError: If the parameter types are incorrect.",
"name": "__init__",
"signature": "def __init__(self,... | 2 | stack_v2_sparse_classes_30k_train_004373 | Implement the Python class `AdminAuditEventsAPI` described below.
Class description:
Admin Audit Events API. Wraps the Webex Teams Admin Audit Events API and exposes the API as native Python methods that return native Python objects.
Method signatures and docstrings:
- def __init__(self, session, object_factory): Ini... | Implement the Python class `AdminAuditEventsAPI` described below.
Class description:
Admin Audit Events API. Wraps the Webex Teams Admin Audit Events API and exposes the API as native Python methods that return native Python objects.
Method signatures and docstrings:
- def __init__(self, session, object_factory): Ini... | d031aab82e3fa5ce7cf57b257fef8c9a4c63d71e | <|skeleton|>
class AdminAuditEventsAPI:
"""Admin Audit Events API. Wraps the Webex Teams Admin Audit Events API and exposes the API as native Python methods that return native Python objects."""
def __init__(self, session, object_factory):
"""Init a new AdminAuditEventsAPI object with the provided Rest... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AdminAuditEventsAPI:
"""Admin Audit Events API. Wraps the Webex Teams Admin Audit Events API and exposes the API as native Python methods that return native Python objects."""
def __init__(self, session, object_factory):
"""Init a new AdminAuditEventsAPI object with the provided RestSession. Args... | the_stack_v2_python_sparse | venv/lib/python3.9/site-packages/webexteamssdk/api/admin_audit_events.py | CiscoDevNet/meraki-code | train | 67 |
348ad7251140216a28de93c4c165690bae51ddc7 | [
"if self.survey_passwords:\n extra_vars = json.loads(self.extra_vars)\n for key, value in self.survey_passwords.items():\n if key in extra_vars:\n extra_vars[key] = value\n return json.dumps(extra_vars)\nelse:\n return self.extra_vars",
"if self.survey_passwords:\n extra_vars = js... | <|body_start_0|>
if self.survey_passwords:
extra_vars = json.loads(self.extra_vars)
for key, value in self.survey_passwords.items():
if key in extra_vars:
extra_vars[key] = value
return json.dumps(extra_vars)
else:
retur... | SurveyJobMixin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SurveyJobMixin:
def display_extra_vars(self):
"""Hides fields marked as passwords in survey."""
<|body_0|>
def decrypted_extra_vars(self):
"""Decrypts fields marked as passwords in survey."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if self.surv... | stack_v2_sparse_classes_10k_train_006762 | 28,356 | permissive | [
{
"docstring": "Hides fields marked as passwords in survey.",
"name": "display_extra_vars",
"signature": "def display_extra_vars(self)"
},
{
"docstring": "Decrypts fields marked as passwords in survey.",
"name": "decrypted_extra_vars",
"signature": "def decrypted_extra_vars(self)"
}
] | 2 | null | Implement the Python class `SurveyJobMixin` described below.
Class description:
Implement the SurveyJobMixin class.
Method signatures and docstrings:
- def display_extra_vars(self): Hides fields marked as passwords in survey.
- def decrypted_extra_vars(self): Decrypts fields marked as passwords in survey. | Implement the Python class `SurveyJobMixin` described below.
Class description:
Implement the SurveyJobMixin class.
Method signatures and docstrings:
- def display_extra_vars(self): Hides fields marked as passwords in survey.
- def decrypted_extra_vars(self): Decrypts fields marked as passwords in survey.
<|skeleton... | 5e105c2cbd3fe828160540b3043cf6f605ed26be | <|skeleton|>
class SurveyJobMixin:
def display_extra_vars(self):
"""Hides fields marked as passwords in survey."""
<|body_0|>
def decrypted_extra_vars(self):
"""Decrypts fields marked as passwords in survey."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SurveyJobMixin:
def display_extra_vars(self):
"""Hides fields marked as passwords in survey."""
if self.survey_passwords:
extra_vars = json.loads(self.extra_vars)
for key, value in self.survey_passwords.items():
if key in extra_vars:
... | the_stack_v2_python_sparse | awx/main/models/mixins.py | ansible/awx | train | 13,353 | |
a7bd2a80bcf6a27c11ef916604536f12ff6d21f2 | [
"lines = []\nfor line in parent._lines:\n if len(line) > 120:\n DocWarning(path, f'Code line length over 120 chars: {line!r}')\n line = line[:120]\n lines.append(line)\nself = object.__new__(cls)\nself.language = parent._language\nself.lines = lines\nreturn self",
"result = ['<', self.__class_... | <|body_start_0|>
lines = []
for line in parent._lines:
if len(line) > 120:
DocWarning(path, f'Code line length over 120 chars: {line!r}')
line = line[:120]
lines.append(line)
self = object.__new__(cls)
self.language = parent._langua... | Represents a graved code block part of a docstring. Attributes ---------- language : `None`, `str` The language of the code if applicable. lines : `list` of `str` The lines of the code-block | GravedCodeBlock | [
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GravedCodeBlock:
"""Represents a graved code block part of a docstring. Attributes ---------- language : `None`, `str` The language of the code if applicable. lines : `list` of `str` The lines of the code-block"""
def __new__(cls, parent, path):
"""Creates a new graved code block.. P... | stack_v2_sparse_classes_10k_train_006763 | 25,556 | permissive | [
{
"docstring": "Creates a new graved code block.. Parameters ---------- parent : ``TextCodeBlock`` The source code block. path : ``QualPath`` The path of the respective docstring. Returns ------- self : ``GravedCodeBlock``",
"name": "__new__",
"signature": "def __new__(cls, parent, path)"
},
{
"... | 2 | null | Implement the Python class `GravedCodeBlock` described below.
Class description:
Represents a graved code block part of a docstring. Attributes ---------- language : `None`, `str` The language of the code if applicable. lines : `list` of `str` The lines of the code-block
Method signatures and docstrings:
- def __new_... | Implement the Python class `GravedCodeBlock` described below.
Class description:
Represents a graved code block part of a docstring. Attributes ---------- language : `None`, `str` The language of the code if applicable. lines : `list` of `str` The lines of the code-block
Method signatures and docstrings:
- def __new_... | 53f24fdb38459dc5a4fd04f11bdbfee8295b76a4 | <|skeleton|>
class GravedCodeBlock:
"""Represents a graved code block part of a docstring. Attributes ---------- language : `None`, `str` The language of the code if applicable. lines : `list` of `str` The lines of the code-block"""
def __new__(cls, parent, path):
"""Creates a new graved code block.. P... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GravedCodeBlock:
"""Represents a graved code block part of a docstring. Attributes ---------- language : `None`, `str` The language of the code if applicable. lines : `list` of `str` The lines of the code-block"""
def __new__(cls, parent, path):
"""Creates a new graved code block.. Parameters ---... | the_stack_v2_python_sparse | hata/ext/patchouli/graver.py | HuyaneMatsu/hata | train | 3 |
0a023162405f264f2db69bdd9772be6959cc4857 | [
"self.params = {'keyword': keyword, 'resource_type': kwargs['resource_type'], 'content_type': kwargs['content_type']}\nres = self.api_send(self.data['search_resource'])\nreturn res",
"self.params = {'keyword': keyword, 'resource_type': kwargs['resource_type'], 'content_type': kwargs['content_type']}\nres = self.a... | <|body_start_0|>
self.params = {'keyword': keyword, 'resource_type': kwargs['resource_type'], 'content_type': kwargs['content_type']}
res = self.api_send(self.data['search_resource'])
return res
<|end_body_0|>
<|body_start_1|>
self.params = {'keyword': keyword, 'resource_type': kwargs['... | search 接口集 | Search | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Search:
"""search 接口集"""
def search_resource(self, keyword, **kwargs):
"""搜索内容"""
<|body_0|>
def search_suggest(self, keyword, **kwargs):
"""关键字匹配"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.params = {'keyword': keyword, 'resource_type'... | stack_v2_sparse_classes_10k_train_006764 | 991 | no_license | [
{
"docstring": "搜索内容",
"name": "search_resource",
"signature": "def search_resource(self, keyword, **kwargs)"
},
{
"docstring": "关键字匹配",
"name": "search_suggest",
"signature": "def search_suggest(self, keyword, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003419 | Implement the Python class `Search` described below.
Class description:
search 接口集
Method signatures and docstrings:
- def search_resource(self, keyword, **kwargs): 搜索内容
- def search_suggest(self, keyword, **kwargs): 关键字匹配 | Implement the Python class `Search` described below.
Class description:
search 接口集
Method signatures and docstrings:
- def search_resource(self, keyword, **kwargs): 搜索内容
- def search_suggest(self, keyword, **kwargs): 关键字匹配
<|skeleton|>
class Search:
"""search 接口集"""
def search_resource(self, keyword, **kwar... | 89a18576934822e6294a465e87bdbc9afa29f177 | <|skeleton|>
class Search:
"""search 接口集"""
def search_resource(self, keyword, **kwargs):
"""搜索内容"""
<|body_0|>
def search_suggest(self, keyword, **kwargs):
"""关键字匹配"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Search:
"""search 接口集"""
def search_resource(self, keyword, **kwargs):
"""搜索内容"""
self.params = {'keyword': keyword, 'resource_type': kwargs['resource_type'], 'content_type': kwargs['content_type']}
res = self.api_send(self.data['search_resource'])
return res
def sear... | the_stack_v2_python_sparse | api/app_api/search.py | bigllxx/testframework-api | train | 1 |
95d1af9bb9a34775ea089799b14cf80864985e86 | [
"super(TypeShareCoder, self).__init__(structure, conf)\nself.taskindices = {t: i for i, t in enumerate(structure.tasks.keys())}\nself.typeindices = dict()\nindex = len(structure.tasks)\nfor argtype in structure.types:\n self.typeindices[argtype] = {t: i + index for i, t in enumerate(structure.types[argtype].opti... | <|body_start_0|>
super(TypeShareCoder, self).__init__(structure, conf)
self.taskindices = {t: i for i, t in enumerate(structure.tasks.keys())}
self.typeindices = dict()
index = len(structure.tasks)
for argtype in structure.types:
self.typeindices[argtype] = {t: i + in... | a Coder that shares the places for args with the same type | TypeShareCoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TypeShareCoder:
"""a Coder that shares the places for args with the same type"""
def __init__(self, structure, conf):
"""Coder constructor Args: structure: a Structure object"""
<|body_0|>
def encode(self, task):
"""encode the task representation into a vector Ar... | stack_v2_sparse_classes_10k_train_006765 | 3,430 | no_license | [
{
"docstring": "Coder constructor Args: structure: a Structure object",
"name": "__init__",
"signature": "def __init__(self, structure, conf)"
},
{
"docstring": "encode the task representation into a vector Args: task: the task reresentation as a Task object Returns: the encoded task representat... | 3 | stack_v2_sparse_classes_30k_train_005817 | Implement the Python class `TypeShareCoder` described below.
Class description:
a Coder that shares the places for args with the same type
Method signatures and docstrings:
- def __init__(self, structure, conf): Coder constructor Args: structure: a Structure object
- def encode(self, task): encode the task representa... | Implement the Python class `TypeShareCoder` described below.
Class description:
a Coder that shares the places for args with the same type
Method signatures and docstrings:
- def __init__(self, structure, conf): Coder constructor Args: structure: a Structure object
- def encode(self, task): encode the task representa... | fcbe609505f86f142cc6e78686e5c25b0e58e178 | <|skeleton|>
class TypeShareCoder:
"""a Coder that shares the places for args with the same type"""
def __init__(self, structure, conf):
"""Coder constructor Args: structure: a Structure object"""
<|body_0|>
def encode(self, task):
"""encode the task representation into a vector Ar... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TypeShareCoder:
"""a Coder that shares the places for args with the same type"""
def __init__(self, structure, conf):
"""Coder constructor Args: structure: a Structure object"""
super(TypeShareCoder, self).__init__(structure, conf)
self.taskindices = {t: i for i, t in enumerate(st... | the_stack_v2_python_sparse | assist/tasks/typeshare_coder.py | GillesDepypere/assist | train | 1 |
7b2139b174309dcf4c032d7844d6227f85ea14d4 | [
"self.directory = dr\nself.images = []\nself.srclists = []\nself.populate()",
"if dr is not None:\n self.directory = dr\nfor k in OM.glob_strings:\n string = self.directory + '/' + OM.glob_strings[k]\n print('OM::populate -- Checking ', k, ' (', string, ')', end='')\n fnames = glob.glob(string)\n p... | <|body_start_0|>
self.directory = dr
self.images = []
self.srclists = []
self.populate()
<|end_body_0|>
<|body_start_1|>
if dr is not None:
self.directory = dr
for k in OM.glob_strings:
string = self.directory + '/' + OM.glob_strings[k]
... | OM | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OM:
def __init__(self, dr):
"""Parameters ---------- dr : str, directory"""
<|body_0|>
def populate(self, dr=None):
"""Use glob strings to populate the filename arrays"""
<|body_1|>
def source_positions(self, dist_cutoff=None):
"""Sky coordinates... | stack_v2_sparse_classes_10k_train_006766 | 5,127 | no_license | [
{
"docstring": "Parameters ---------- dr : str, directory",
"name": "__init__",
"signature": "def __init__(self, dr)"
},
{
"docstring": "Use glob strings to populate the filename arrays",
"name": "populate",
"signature": "def populate(self, dr=None)"
},
{
"docstring": "Sky coordi... | 4 | stack_v2_sparse_classes_30k_train_005465 | Implement the Python class `OM` described below.
Class description:
Implement the OM class.
Method signatures and docstrings:
- def __init__(self, dr): Parameters ---------- dr : str, directory
- def populate(self, dr=None): Use glob strings to populate the filename arrays
- def source_positions(self, dist_cutoff=Non... | Implement the Python class `OM` described below.
Class description:
Implement the OM class.
Method signatures and docstrings:
- def __init__(self, dr): Parameters ---------- dr : str, directory
- def populate(self, dr=None): Use glob strings to populate the filename arrays
- def source_positions(self, dist_cutoff=Non... | dbd06e111859d3a173180d1b39469c4de55b3c73 | <|skeleton|>
class OM:
def __init__(self, dr):
"""Parameters ---------- dr : str, directory"""
<|body_0|>
def populate(self, dr=None):
"""Use glob strings to populate the filename arrays"""
<|body_1|>
def source_positions(self, dist_cutoff=None):
"""Sky coordinates... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OM:
def __init__(self, dr):
"""Parameters ---------- dr : str, directory"""
self.directory = dr
self.images = []
self.srclists = []
self.populate()
def populate(self, dr=None):
"""Use glob strings to populate the filename arrays"""
if dr is not None... | the_stack_v2_python_sparse | ana/tools/om.py | pcschneider/solar_analogs | train | 0 | |
cd3e8572e1e7bfc4607a40f4198109b33d10a843 | [
"try:\n verify_token(request.headers)\nexcept Exception as err:\n ns.abort(401, message=err)\noffset = request.args.get('offset', '0')\nlimit = request.args.get('limit', '10')\norder_by = request.args.get('order_by', 'id')\norder = request.args.get('order', 'ASC')\nper_page = request.args.get('per_page', '10'... | <|body_start_0|>
try:
verify_token(request.headers)
except Exception as err:
ns.abort(401, message=err)
offset = request.args.get('offset', '0')
limit = request.args.get('limit', '10')
order_by = request.args.get('order_by', 'id')
order = request.a... | ObservacionPreAsfList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ObservacionPreAsfList:
def get(self):
"""To fetch several observations (preliminares de la ASF). On Success it returns two custom headers: X-SOA-Total-Items, X-SOA-Total-Pages"""
<|body_0|>
def post(self):
"""To create an observation (preliminar de la ASF)."""
... | stack_v2_sparse_classes_10k_train_006767 | 13,540 | no_license | [
{
"docstring": "To fetch several observations (preliminares de la ASF). On Success it returns two custom headers: X-SOA-Total-Items, X-SOA-Total-Pages",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "To create an observation (preliminar de la ASF).",
"name": "post",
"sign... | 2 | stack_v2_sparse_classes_30k_train_004674 | Implement the Python class `ObservacionPreAsfList` described below.
Class description:
Implement the ObservacionPreAsfList class.
Method signatures and docstrings:
- def get(self): To fetch several observations (preliminares de la ASF). On Success it returns two custom headers: X-SOA-Total-Items, X-SOA-Total-Pages
- ... | Implement the Python class `ObservacionPreAsfList` described below.
Class description:
Implement the ObservacionPreAsfList class.
Method signatures and docstrings:
- def get(self): To fetch several observations (preliminares de la ASF). On Success it returns two custom headers: X-SOA-Total-Items, X-SOA-Total-Pages
- ... | e00610fac26ef3ca078fd037c0649b70fa0e9a09 | <|skeleton|>
class ObservacionPreAsfList:
def get(self):
"""To fetch several observations (preliminares de la ASF). On Success it returns two custom headers: X-SOA-Total-Items, X-SOA-Total-Pages"""
<|body_0|>
def post(self):
"""To create an observation (preliminar de la ASF)."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ObservacionPreAsfList:
def get(self):
"""To fetch several observations (preliminares de la ASF). On Success it returns two custom headers: X-SOA-Total-Items, X-SOA-Total-Pages"""
try:
verify_token(request.headers)
except Exception as err:
ns.abort(401, message=e... | the_stack_v2_python_sparse | DOS/soa/service/genl/endpoints/observaciones_pre_asf.py | Telematica/knight-rider | train | 1 | |
099d098cfeef4209e750d9db6057d85f5358f72b | [
"parser.add_argument('user', metavar='USERNAME', help='User name for the owner of the sample.')\nparser.add_argument('sample_dir', metavar='SAMPLE_DIRECTORY', help='User name for the owner of the sample.')\nparser.add_argument('name', metavar='SAMPLE_NAME', help='Sample tag associated with sample.')\nparser.add_arg... | <|body_start_0|>
parser.add_argument('user', metavar='USERNAME', help='User name for the owner of the sample.')
parser.add_argument('sample_dir', metavar='SAMPLE_DIRECTORY', help='User name for the owner of the sample.')
parser.add_argument('name', metavar='SAMPLE_NAME', help='Sample tag associa... | Insert the results of sample analysis into the database. | Command | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Command:
"""Insert the results of sample analysis into the database."""
def add_arguments(self, parser):
"""Command line arguements."""
<|body_0|>
def handle(self, *args, **opts):
"""Insert the results of sample analysis into the database."""
<|body_1|>
... | stack_v2_sparse_classes_10k_train_006768 | 4,597 | no_license | [
{
"docstring": "Command line arguements.",
"name": "add_arguments",
"signature": "def add_arguments(self, parser)"
},
{
"docstring": "Insert the results of sample analysis into the database.",
"name": "handle",
"signature": "def handle(self, *args, **opts)"
},
{
"docstring": "The... | 3 | stack_v2_sparse_classes_30k_train_004774 | Implement the Python class `Command` described below.
Class description:
Insert the results of sample analysis into the database.
Method signatures and docstrings:
- def add_arguments(self, parser): Command line arguements.
- def handle(self, *args, **opts): Insert the results of sample analysis into the database.
- ... | Implement the Python class `Command` described below.
Class description:
Insert the results of sample analysis into the database.
Method signatures and docstrings:
- def add_arguments(self, parser): Command line arguements.
- def handle(self, *args, **opts): Insert the results of sample analysis into the database.
- ... | 2c35ee47e131a74642e60fae6f1cc23561d8b1a6 | <|skeleton|>
class Command:
"""Insert the results of sample analysis into the database."""
def add_arguments(self, parser):
"""Command line arguements."""
<|body_0|>
def handle(self, *args, **opts):
"""Insert the results of sample analysis into the database."""
<|body_1|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Command:
"""Insert the results of sample analysis into the database."""
def add_arguments(self, parser):
"""Command line arguements."""
parser.add_argument('user', metavar='USERNAME', help='User name for the owner of the sample.')
parser.add_argument('sample_dir', metavar='SAMPLE_... | the_stack_v2_python_sparse | sample/management/commands/insert_analysis_results.py | staphopia/staphopia-web | train | 5 |
dd505beeab289a88129187e103c67ad510c5a85f | [
"if path is None:\n outpath = os.path.dirname(os.path.abspath(configfile))\nelse:\n outpath = path\nself.config = Configuration(configfile, outpath=path)\nself.pixel = pixel\nself.nside = nside",
"if not self.config.galfile_pixelized:\n raise ValueError('Code only runs with pixelized galfile.')\nself.con... | <|body_start_0|>
if path is None:
outpath = os.path.dirname(os.path.abspath(configfile))
else:
outpath = path
self.config = Configuration(configfile, outpath=path)
self.pixel = pixel
self.nside = nside
<|end_body_0|>
<|body_start_1|>
if not self.c... | Class to run redshift-scanning (zscan) on a single healpix pixel, for distributed runs. | RunZScanPixelTask | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RunZScanPixelTask:
"""Class to run redshift-scanning (zscan) on a single healpix pixel, for distributed runs."""
def __init__(self, configfile, pixel, nside, path=None):
"""Instantiate a RunZScanPixelTask. Parameters ---------- configfile: `str` Configuration yaml filename. pixel: `i... | stack_v2_sparse_classes_10k_train_006769 | 10,033 | permissive | [
{
"docstring": "Instantiate a RunZScanPixelTask. Parameters ---------- configfile: `str` Configuration yaml filename. pixel: `int` Healpix pixel to run on. nside: `int` Healpix nside associated with pixel. path: `str`, optional Output path. Default is None, use same absolute path as configfile. percolation_mask... | 2 | stack_v2_sparse_classes_30k_train_003935 | Implement the Python class `RunZScanPixelTask` described below.
Class description:
Class to run redshift-scanning (zscan) on a single healpix pixel, for distributed runs.
Method signatures and docstrings:
- def __init__(self, configfile, pixel, nside, path=None): Instantiate a RunZScanPixelTask. Parameters ----------... | Implement the Python class `RunZScanPixelTask` described below.
Class description:
Class to run redshift-scanning (zscan) on a single healpix pixel, for distributed runs.
Method signatures and docstrings:
- def __init__(self, configfile, pixel, nside, path=None): Instantiate a RunZScanPixelTask. Parameters ----------... | d3a8b432c2f3a20aa518a7781c0f2aa315624855 | <|skeleton|>
class RunZScanPixelTask:
"""Class to run redshift-scanning (zscan) on a single healpix pixel, for distributed runs."""
def __init__(self, configfile, pixel, nside, path=None):
"""Instantiate a RunZScanPixelTask. Parameters ---------- configfile: `str` Configuration yaml filename. pixel: `i... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RunZScanPixelTask:
"""Class to run redshift-scanning (zscan) on a single healpix pixel, for distributed runs."""
def __init__(self, configfile, pixel, nside, path=None):
"""Instantiate a RunZScanPixelTask. Parameters ---------- configfile: `str` Configuration yaml filename. pixel: `int` Healpix p... | the_stack_v2_python_sparse | redmapper/pipeline/redmappertask.py | erykoff/redmapper | train | 20 |
79bc9528800b8a2ace60e4eadc303367a3edbeff | [
"if model.has_built(obj):\n warnings.warn('Object %s has already been built.' % obj)\n return None\nfor obj_cls in type(obj).__mro__:\n if obj_cls in cls.builders:\n break\nelse:\n raise BuildError('Cannot build object of type %r' % type(obj).__name__)\nreturn cls.builders[obj_cls](model, obj, *a... | <|body_start_0|>
if model.has_built(obj):
warnings.warn('Object %s has already been built.' % obj)
return None
for obj_cls in type(obj).__mro__:
if obj_cls in cls.builders:
break
else:
raise BuildError('Cannot build object of type %... | Manages the build functions known to the Nengo build process. Consists of two class methods to encapsulate the build function registry. All build functions should use the `.Builder.register` method as a decorator. For example:: @nengo.builder.Builder.register(MyRule) def build_my_rule(model, my_rule, rule): ... registe... | Builder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Builder:
"""Manages the build functions known to the Nengo build process. Consists of two class methods to encapsulate the build function registry. All build functions should use the `.Builder.register` method as a decorator. For example:: @nengo.builder.Builder.register(MyRule) def build_my_rule... | stack_v2_sparse_classes_10k_train_006770 | 8,755 | no_license | [
{
"docstring": "Build ``obj`` into ``model``. This method looks up the appropriate build function for ``obj`` and calls it with the model and other arguments provided. Note that if a build function is not specified for a particular type (e.g., `.EnsembleArray`), the type's method resolution order will be examin... | 2 | stack_v2_sparse_classes_30k_train_006922 | Implement the Python class `Builder` described below.
Class description:
Manages the build functions known to the Nengo build process. Consists of two class methods to encapsulate the build function registry. All build functions should use the `.Builder.register` method as a decorator. For example:: @nengo.builder.Bui... | Implement the Python class `Builder` described below.
Class description:
Manages the build functions known to the Nengo build process. Consists of two class methods to encapsulate the build function registry. All build functions should use the `.Builder.register` method as a decorator. For example:: @nengo.builder.Bui... | ee72a44640cf81c56721f44fbad5b16e0643aa88 | <|skeleton|>
class Builder:
"""Manages the build functions known to the Nengo build process. Consists of two class methods to encapsulate the build function registry. All build functions should use the `.Builder.register` method as a decorator. For example:: @nengo.builder.Builder.register(MyRule) def build_my_rule... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Builder:
"""Manages the build functions known to the Nengo build process. Consists of two class methods to encapsulate the build function registry. All build functions should use the `.Builder.register` method as a decorator. For example:: @nengo.builder.Builder.register(MyRule) def build_my_rule(model, my_ru... | the_stack_v2_python_sparse | gosmann_frontiers2017/optimized/builder/builder.py | ctn-archive/gosmann-frontiers2017 | train | 3 |
b817d36fa230efc334acda923e1884f139e48f18 | [
"super(SelfAttention, self).__init__()\nself.U = tf.keras.layers.Dense(units)\nself.V = tf.keras.layers.Dense(1)\nself.W = tf.keras.layers.Dense(units)",
"query = tf.expand_dims(s_prev, 1)\ntfadd = tf.math.add(self.W(query), self.U(hidden_states))\nscore = self.V(tf.nn.tanh(tfadd))\nweigh = tf.nn.softmax(score, a... | <|body_start_0|>
super(SelfAttention, self).__init__()
self.U = tf.keras.layers.Dense(units)
self.V = tf.keras.layers.Dense(1)
self.W = tf.keras.layers.Dense(units)
<|end_body_0|>
<|body_start_1|>
query = tf.expand_dims(s_prev, 1)
tfadd = tf.math.add(self.W(query), self.... | class RNNEncoder class that inherits from tensorflow.keras.layers.Layer to calculate the attention for machine translation based on this paper: https://arxiv.org/pdf/1409.0473.pdf Args: tf ([type]): [description] | SelfAttention | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SelfAttention:
"""class RNNEncoder class that inherits from tensorflow.keras.layers.Layer to calculate the attention for machine translation based on this paper: https://arxiv.org/pdf/1409.0473.pdf Args: tf ([type]): [description]"""
def __init__(self, units):
"""[Class constructor] ... | stack_v2_sparse_classes_10k_train_006771 | 2,066 | no_license | [
{
"docstring": "[Class constructor] Args: units ([int]): [number of hidden units in the RNN cell] Sets the following public instance attributes: W: A Dense layer with units units, to be applied to the previous decoder hidden state U: A Dense layer with units units, to be applied to the encoder hidden states V: ... | 2 | null | Implement the Python class `SelfAttention` described below.
Class description:
class RNNEncoder class that inherits from tensorflow.keras.layers.Layer to calculate the attention for machine translation based on this paper: https://arxiv.org/pdf/1409.0473.pdf Args: tf ([type]): [description]
Method signatures and docs... | Implement the Python class `SelfAttention` described below.
Class description:
class RNNEncoder class that inherits from tensorflow.keras.layers.Layer to calculate the attention for machine translation based on this paper: https://arxiv.org/pdf/1409.0473.pdf Args: tf ([type]): [description]
Method signatures and docs... | eb47cd4d12e2f0627bb5e5af28cc0802ff13d0d9 | <|skeleton|>
class SelfAttention:
"""class RNNEncoder class that inherits from tensorflow.keras.layers.Layer to calculate the attention for machine translation based on this paper: https://arxiv.org/pdf/1409.0473.pdf Args: tf ([type]): [description]"""
def __init__(self, units):
"""[Class constructor] ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SelfAttention:
"""class RNNEncoder class that inherits from tensorflow.keras.layers.Layer to calculate the attention for machine translation based on this paper: https://arxiv.org/pdf/1409.0473.pdf Args: tf ([type]): [description]"""
def __init__(self, units):
"""[Class constructor] Args: units (... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/1-self_attention.py | rodrigocruz13/holbertonschool-machine_learning | train | 4 |
bb9a92fb19344cdd66ace0c11684016e67668eef | [
"def dfs(root: TreeNode, curNum: int) -> int:\n if not root:\n return 0\n curNum = (curNum << 1) + root.val\n if not root.left and (not root.right):\n return curNum\n return dfs(root.left, curNum) + dfs(root.right, curNum)\nreturn dfs(root, 0)",
"if not root:\n return 0\nret = 0\nstac... | <|body_start_0|>
def dfs(root: TreeNode, curNum: int) -> int:
if not root:
return 0
curNum = (curNum << 1) + root.val
if not root.left and (not root.right):
return curNum
return dfs(root.left, curNum) + dfs(root.right, curNum)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sumRootToLeaf_MK1(self, root: TreeNode) -> int:
"""Recursive Preorder Traversal. Time complexity: O(N). N is a number of nodes. Space complexity: O(H). H is a tree height."""
<|body_0|>
def sumRootToLeaf_MK2(self, root: TreeNode) -> int:
"""Iterative Pr... | stack_v2_sparse_classes_10k_train_006772 | 2,503 | no_license | [
{
"docstring": "Recursive Preorder Traversal. Time complexity: O(N). N is a number of nodes. Space complexity: O(H). H is a tree height.",
"name": "sumRootToLeaf_MK1",
"signature": "def sumRootToLeaf_MK1(self, root: TreeNode) -> int"
},
{
"docstring": "Iterative Preorder Traversal. Time complexi... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sumRootToLeaf_MK1(self, root: TreeNode) -> int: Recursive Preorder Traversal. Time complexity: O(N). N is a number of nodes. Space complexity: O(H). H is a tree height.
- def... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sumRootToLeaf_MK1(self, root: TreeNode) -> int: Recursive Preorder Traversal. Time complexity: O(N). N is a number of nodes. Space complexity: O(H). H is a tree height.
- def... | d7ba416d22becfa8f2a2ae4eee04c86617cd9332 | <|skeleton|>
class Solution:
def sumRootToLeaf_MK1(self, root: TreeNode) -> int:
"""Recursive Preorder Traversal. Time complexity: O(N). N is a number of nodes. Space complexity: O(H). H is a tree height."""
<|body_0|>
def sumRootToLeaf_MK2(self, root: TreeNode) -> int:
"""Iterative Pr... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def sumRootToLeaf_MK1(self, root: TreeNode) -> int:
"""Recursive Preorder Traversal. Time complexity: O(N). N is a number of nodes. Space complexity: O(H). H is a tree height."""
def dfs(root: TreeNode, curNum: int) -> int:
if not root:
return 0
... | the_stack_v2_python_sparse | 1022. Sum of Root To Leaf Binary Numbers/Solution.py | faterazer/LeetCode | train | 4 | |
6a163677610ac84225bfba4488e1d17aa3eb5af6 | [
"visited = set([0])\n\ndef dfs(i):\n for r in rooms[i]:\n if r not in visited:\n visited.add(r)\n dfs(r)\ndfs(0)\nreturn len(visited) == len(rooms)",
"n = len(rooms)\nvisited = [False] * n\nkeys = deque([0])\nwhile keys:\n key = keys.popleft()\n if visited[key]:\n cont... | <|body_start_0|>
visited = set([0])
def dfs(i):
for r in rooms[i]:
if r not in visited:
visited.add(r)
dfs(r)
dfs(0)
return len(visited) == len(rooms)
<|end_body_0|>
<|body_start_1|>
n = len(rooms)
visi... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
"""Sep 26, 2020 15:10"""
<|body_0|>
def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
"""Feb 19, 2023 17:13"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
visited = set... | stack_v2_sparse_classes_10k_train_006773 | 2,415 | no_license | [
{
"docstring": "Sep 26, 2020 15:10",
"name": "canVisitAllRooms",
"signature": "def canVisitAllRooms(self, rooms: List[List[int]]) -> bool"
},
{
"docstring": "Feb 19, 2023 17:13",
"name": "canVisitAllRooms",
"signature": "def canVisitAllRooms(self, rooms: List[List[int]]) -> bool"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: Sep 26, 2020 15:10
- def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: Feb 19, 2023 17:13 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: Sep 26, 2020 15:10
- def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: Feb 19, 2023 17:13
<|skeleton|>
clas... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
"""Sep 26, 2020 15:10"""
<|body_0|>
def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
"""Feb 19, 2023 17:13"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
"""Sep 26, 2020 15:10"""
visited = set([0])
def dfs(i):
for r in rooms[i]:
if r not in visited:
visited.add(r)
dfs(r)
dfs(0)
return... | the_stack_v2_python_sparse | leetcode/solved/871_Keys_and_Rooms/solution.py | sungminoh/algorithms | train | 0 | |
e5308cbb43f3477e9ad8a6d29c14daac171cb072 | [
"xor = len(nums)\nfor i in range(0, len(nums)):\n xor = xor ^ i ^ nums[i]\nreturn xor",
"n = len(nums)\nideal_total = n * (n + 1) / 2\ntotal = 0\nfor num in nums:\n total += num\nreturn ideal_total - total"
] | <|body_start_0|>
xor = len(nums)
for i in range(0, len(nums)):
xor = xor ^ i ^ nums[i]
return xor
<|end_body_0|>
<|body_start_1|>
n = len(nums)
ideal_total = n * (n + 1) / 2
total = 0
for num in nums:
total += num
return ideal_tota... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def missingNumber(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def missingNumberClassic(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
xor = len(nums)
for i in r... | stack_v2_sparse_classes_10k_train_006774 | 984 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "missingNumber",
"signature": "def missingNumber(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "missingNumberClassic",
"signature": "def missingNumberClassic(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006782 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def missingNumber(self, nums): :type nums: List[int] :rtype: int
- def missingNumberClassic(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 missingNumber(self, nums): :type nums: List[int] :rtype: int
- def missingNumberClassic(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def ... | 664ca26b70ddc7461f2428c28ed13b632fc1f8fd | <|skeleton|>
class Solution:
def missingNumber(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def missingNumberClassic(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def missingNumber(self, nums):
""":type nums: List[int] :rtype: int"""
xor = len(nums)
for i in range(0, len(nums)):
xor = xor ^ i ^ nums[i]
return xor
def missingNumberClassic(self, nums):
""":type nums: List[int] :rtype: int"""
n = l... | the_stack_v2_python_sparse | missing_number.py | sshukla31/leetcode | train | 0 | |
d8ec72ef261e1a1772a41205c7ce2af85cad41c0 | [
"ImageRender.__init__(self, image_render)\nself.image_wrapper = image_wrapper\nself.crop_param = crop_param",
"if self.image_render:\n self.image_wrapper = self.image_render.render()\nif self.crop_param is None:\n return self.image_wrapper\ncrop_image = Image.new('F', (self.crop_param.width, self.crop_param... | <|body_start_0|>
ImageRender.__init__(self, image_render)
self.image_wrapper = image_wrapper
self.crop_param = crop_param
<|end_body_0|>
<|body_start_1|>
if self.image_render:
self.image_wrapper = self.image_render.render()
if self.crop_param is None:
ret... | 切割渲染类 | CropRender | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CropRender:
"""切割渲染类"""
def __init__(self, image_wrapper, crop_param, image_render=None):
"""切割渲染. :param image_wrapper: :param crop_param: :param image_render:"""
<|body_0|>
def render(self):
"""执行渲染逻辑. :return: image_wrapper"""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_10k_train_006775 | 4,912 | no_license | [
{
"docstring": "切割渲染. :param image_wrapper: :param crop_param: :param image_render:",
"name": "__init__",
"signature": "def __init__(self, image_wrapper, crop_param, image_render=None)"
},
{
"docstring": "执行渲染逻辑. :return: image_wrapper",
"name": "render",
"signature": "def render(self)"
... | 2 | stack_v2_sparse_classes_30k_train_002640 | Implement the Python class `CropRender` described below.
Class description:
切割渲染类
Method signatures and docstrings:
- def __init__(self, image_wrapper, crop_param, image_render=None): 切割渲染. :param image_wrapper: :param crop_param: :param image_render:
- def render(self): 执行渲染逻辑. :return: image_wrapper | Implement the Python class `CropRender` described below.
Class description:
切割渲染类
Method signatures and docstrings:
- def __init__(self, image_wrapper, crop_param, image_render=None): 切割渲染. :param image_wrapper: :param crop_param: :param image_render:
- def render(self): 执行渲染逻辑. :return: image_wrapper
<|skeleton|>
c... | bf1ff4fa5b82e6a34669a16f34f3aec5e9c4d09d | <|skeleton|>
class CropRender:
"""切割渲染类"""
def __init__(self, image_wrapper, crop_param, image_render=None):
"""切割渲染. :param image_wrapper: :param crop_param: :param image_render:"""
<|body_0|>
def render(self):
"""执行渲染逻辑. :return: image_wrapper"""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CropRender:
"""切割渲染类"""
def __init__(self, image_wrapper, crop_param, image_render=None):
"""切割渲染. :param image_wrapper: :param crop_param: :param image_render:"""
ImageRender.__init__(self, image_render)
self.image_wrapper = image_wrapper
self.crop_param = crop_param
... | the_stack_v2_python_sparse | commons/imageprocessor.py | wangleimvp/python-project-components | train | 0 |
7acb9b9c4781b5b2fa1f32e0080c3b5d6e727805 | [
"super(FeatureSqueezing).__init__()\nassert 8 >= bit_depth > 0\nassert kernel_size > 0\nself.bit_value = 2 ** bit_depth - 1\nself.kernel_size = kernel_size\nself.padding = _quadruple(math.floor(kernel_size / 2))",
"squeezed = torch.floor(image * self.bit_value) / self.bit_value\nsqueezed = F.pad(squeezed, self.pa... | <|body_start_0|>
super(FeatureSqueezing).__init__()
assert 8 >= bit_depth > 0
assert kernel_size > 0
self.bit_value = 2 ** bit_depth - 1
self.kernel_size = kernel_size
self.padding = _quadruple(math.floor(kernel_size / 2))
<|end_body_0|>
<|body_start_1|>
squeezed... | Implementation of Feature Squeezing defence. Original paper: https://arxiv.org/pdf/1704.01155.pdf | FeatureSqueezing | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeatureSqueezing:
"""Implementation of Feature Squeezing defence. Original paper: https://arxiv.org/pdf/1704.01155.pdf"""
def __init__(self, bit_depth=7, kernel_size=3):
""":param bit_depth: Number of bits used to encode image colors. Use 8 for no bit reduction. :param kernel_size: S... | stack_v2_sparse_classes_10k_train_006776 | 1,555 | permissive | [
{
"docstring": ":param bit_depth: Number of bits used to encode image colors. Use 8 for no bit reduction. :param kernel_size: Size of filter to use for blurring. Larger size means more blurring. Use kernel size 1 for no blurring.",
"name": "__init__",
"signature": "def __init__(self, bit_depth=7, kernel... | 2 | stack_v2_sparse_classes_30k_train_005217 | Implement the Python class `FeatureSqueezing` described below.
Class description:
Implementation of Feature Squeezing defence. Original paper: https://arxiv.org/pdf/1704.01155.pdf
Method signatures and docstrings:
- def __init__(self, bit_depth=7, kernel_size=3): :param bit_depth: Number of bits used to encode image ... | Implement the Python class `FeatureSqueezing` described below.
Class description:
Implementation of Feature Squeezing defence. Original paper: https://arxiv.org/pdf/1704.01155.pdf
Method signatures and docstrings:
- def __init__(self, bit_depth=7, kernel_size=3): :param bit_depth: Number of bits used to encode image ... | f5a79e3aa5dc15d7f2fd677ea64f41dd3a1e9cd8 | <|skeleton|>
class FeatureSqueezing:
"""Implementation of Feature Squeezing defence. Original paper: https://arxiv.org/pdf/1704.01155.pdf"""
def __init__(self, bit_depth=7, kernel_size=3):
""":param bit_depth: Number of bits used to encode image colors. Use 8 for no bit reduction. :param kernel_size: S... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FeatureSqueezing:
"""Implementation of Feature Squeezing defence. Original paper: https://arxiv.org/pdf/1704.01155.pdf"""
def __init__(self, bit_depth=7, kernel_size=3):
""":param bit_depth: Number of bits used to encode image colors. Use 8 for no bit reduction. :param kernel_size: Size of filter... | the_stack_v2_python_sparse | sat/defence/FeatureSqueezing.py | larsksy/Semantic-Adversarial-Toolbox | train | 1 |
44635dea5130342b4c472cd00307d82ed1808b76 | [
"geopoint = value\nif geopoint is not None:\n if isinstance(geopoint, str):\n geopoint_split = geopoint.split(',')\n lon = float(geopoint_split[0])\n lat = float(geopoint_split[1])\n return Point(lon, lat)\n if isinstance(geopoint, list):\n lon = float(geopoint[0])\n ... | <|body_start_0|>
geopoint = value
if geopoint is not None:
if isinstance(geopoint, str):
geopoint_split = geopoint.split(',')
lon = float(geopoint_split[0])
lat = float(geopoint_split[1])
return Point(lon, lat)
if is... | Custom Field for Geopoint | GeopointField | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GeopointField:
"""Custom Field for Geopoint"""
def to_internal_value(self, value):
"""Custom conversion for GeopointField"""
<|body_0|>
def to_representation(self, value):
"""Custom conversion to representation for GeopointField"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_10k_train_006777 | 6,527 | permissive | [
{
"docstring": "Custom conversion for GeopointField",
"name": "to_internal_value",
"signature": "def to_internal_value(self, value)"
},
{
"docstring": "Custom conversion to representation for GeopointField",
"name": "to_representation",
"signature": "def to_representation(self, value)"
... | 2 | stack_v2_sparse_classes_30k_train_005687 | Implement the Python class `GeopointField` described below.
Class description:
Custom Field for Geopoint
Method signatures and docstrings:
- def to_internal_value(self, value): Custom conversion for GeopointField
- def to_representation(self, value): Custom conversion to representation for GeopointField | Implement the Python class `GeopointField` described below.
Class description:
Custom Field for Geopoint
Method signatures and docstrings:
- def to_internal_value(self, value): Custom conversion for GeopointField
- def to_representation(self, value): Custom conversion to representation for GeopointField
<|skeleton|>... | 5faff50a2f3575f0df91a6b20afe37d43a592381 | <|skeleton|>
class GeopointField:
"""Custom Field for Geopoint"""
def to_internal_value(self, value):
"""Custom conversion for GeopointField"""
<|body_0|>
def to_representation(self, value):
"""Custom conversion to representation for GeopointField"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GeopointField:
"""Custom Field for Geopoint"""
def to_internal_value(self, value):
"""Custom conversion for GeopointField"""
geopoint = value
if geopoint is not None:
if isinstance(geopoint, str):
geopoint_split = geopoint.split(',')
lon... | the_stack_v2_python_sparse | tasking/serializers/location.py | onaio/tasking | train | 6 |
7f9be951db40216dbef352b4d1c8c1487bfcec29 | [
"self.threshold = threshold\nself.sampling_method = sampling_method\nself.eps = eps\nself.delta = delta\nself._store_every = store_every\nself.func_of_freq = func_of_freq\nself._inclusion_prob = [0.0]\nself.elements = set()",
"if not isinstance(sample, ThresholdSample):\n raise TypeError('Tried to create a pri... | <|body_start_0|>
self.threshold = threshold
self.sampling_method = sampling_method
self.eps = eps
self.delta = delta
self._store_every = store_every
self.func_of_freq = func_of_freq
self._inclusion_prob = [0.0]
self.elements = set()
<|end_body_0|>
<|body_... | Threshold sampling with differential privacy (returns sampled keys only). This class implements threshold sampling, and then performs subsampling to satisfy the differential privacy constraints. The private sample only includes keys (and no information about their frequencies). The sketch only supports aggregated data:... | PrivateThresholdSampleKeysOnly | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrivateThresholdSampleKeysOnly:
"""Threshold sampling with differential privacy (returns sampled keys only). This class implements threshold sampling, and then performs subsampling to satisfy the differential privacy constraints. The private sample only includes keys (and no information about the... | stack_v2_sparse_classes_10k_train_006778 | 32,453 | permissive | [
{
"docstring": "Initializes an empty sample. Args: threshold: The sampling threshold eps: The differential privacy parameter epsilon delta: The differential privacy parameter delta sampling_method: A class that provides functions to compute the score and inclusion probability according to the underlying non-pri... | 4 | null | Implement the Python class `PrivateThresholdSampleKeysOnly` described below.
Class description:
Threshold sampling with differential privacy (returns sampled keys only). This class implements threshold sampling, and then performs subsampling to satisfy the differential privacy constraints. The private sample only incl... | Implement the Python class `PrivateThresholdSampleKeysOnly` described below.
Class description:
Threshold sampling with differential privacy (returns sampled keys only). This class implements threshold sampling, and then performs subsampling to satisfy the differential privacy constraints. The private sample only incl... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class PrivateThresholdSampleKeysOnly:
"""Threshold sampling with differential privacy (returns sampled keys only). This class implements threshold sampling, and then performs subsampling to satisfy the differential privacy constraints. The private sample only includes keys (and no information about the... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PrivateThresholdSampleKeysOnly:
"""Threshold sampling with differential privacy (returns sampled keys only). This class implements threshold sampling, and then performs subsampling to satisfy the differential privacy constraints. The private sample only includes keys (and no information about their frequencie... | the_stack_v2_python_sparse | private_sampling/private_sampling.py | Jimmy-INL/google-research | train | 1 |
cc8ad53b6ab4e33f96eead9a3c58683ea5e3ec44 | [
"triplets = []\nlength = len(nums)\nif length < 3:\n return triplets\nnums.sort()\nfor i in range(length):\n target = 0 - nums[i]\n hashmap = {}\n for j in range(i + 1, length):\n item_j = nums[j]\n if target - item_j in hashmap:\n triplet = [nums[i], target - item_j, item_j]\n ... | <|body_start_0|>
triplets = []
length = len(nums)
if length < 3:
return triplets
nums.sort()
for i in range(length):
target = 0 - nums[i]
hashmap = {}
for j in range(i + 1, length):
item_j = nums[j]
i... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def threeSum(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def threeSum2(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
triplets = []
leng... | stack_v2_sparse_classes_10k_train_006779 | 1,433 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "threeSum",
"signature": "def threeSum(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "threeSum2",
"signature": "def threeSum2(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004127 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def threeSum(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def threeSum2(self, nums): :type nums: List[int] :rtype: List[List[int]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def threeSum(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def threeSum2(self, nums): :type nums: List[int] :rtype: List[List[int]]
<|skeleton|>
class Solution:
... | 3f8a1acc28520e65714296b337f817148ec3e0af | <|skeleton|>
class Solution:
def threeSum(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def threeSum2(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def threeSum(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
triplets = []
length = len(nums)
if length < 3:
return triplets
nums.sort()
for i in range(length):
target = 0 - nums[i]
hashmap = {}
... | the_stack_v2_python_sparse | lintcode/TwoPointers/3Sum.py | sassyst/leetcode-python | train | 0 | |
d2fa7a5f79fefea431b71652c888172e4bd74ad4 | [
"if A != []:\n for j in a[i]:\n if j in A:\n tree[i]['children'].append(j)\n tree[j]['father'] = i\n A.remove(j)\n tree, A = self.get_tree(tree, A, a, j)\nreturn (tree, A)",
"G = nx.Graph()\ndistance = lambda x, y: math.sqrt(np.sum((x - y) ** 2))\nfor i in ran... | <|body_start_0|>
if A != []:
for j in a[i]:
if j in A:
tree[i]['children'].append(j)
tree[j]['father'] = i
A.remove(j)
tree, A = self.get_tree(tree, A, a, j)
return (tree, A)
<|end_body_0|>
<|bod... | Apply Kruskal to a tree structure | Kruskal | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Kruskal:
"""Apply Kruskal to a tree structure"""
def get_tree(self, tree, A, a, i):
"""Use to convert one tree to another :param tree: original tree :param A: list of nodes :param a: new tree :param i: node number :return: tree, A"""
<|body_0|>
def __call__(self, tree):
... | stack_v2_sparse_classes_10k_train_006780 | 1,908 | permissive | [
{
"docstring": "Use to convert one tree to another :param tree: original tree :param A: list of nodes :param a: new tree :param i: node number :return: tree, A",
"name": "get_tree",
"signature": "def get_tree(self, tree, A, a, i)"
},
{
"docstring": "Use Kruskal :param tree: true structure :retur... | 2 | stack_v2_sparse_classes_30k_train_001456 | Implement the Python class `Kruskal` described below.
Class description:
Apply Kruskal to a tree structure
Method signatures and docstrings:
- def get_tree(self, tree, A, a, i): Use to convert one tree to another :param tree: original tree :param A: list of nodes :param a: new tree :param i: node number :return: tree... | Implement the Python class `Kruskal` described below.
Class description:
Apply Kruskal to a tree structure
Method signatures and docstrings:
- def get_tree(self, tree, A, a, i): Use to convert one tree to another :param tree: original tree :param A: list of nodes :param a: new tree :param i: node number :return: tree... | 91dbb0eebba64f1fa2c18562e2c9f35f532ef7c0 | <|skeleton|>
class Kruskal:
"""Apply Kruskal to a tree structure"""
def get_tree(self, tree, A, a, i):
"""Use to convert one tree to another :param tree: original tree :param A: list of nodes :param a: new tree :param i: node number :return: tree, A"""
<|body_0|>
def __call__(self, tree):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Kruskal:
"""Apply Kruskal to a tree structure"""
def get_tree(self, tree, A, a, i):
"""Use to convert one tree to another :param tree: original tree :param A: list of nodes :param a: new tree :param i: node number :return: tree, A"""
if A != []:
for j in a[i]:
... | the_stack_v2_python_sparse | src/python_code/compostela/tree_optimization/kruskal.py | ipmach/Thesis2021 | train | 0 |
390b55ad55a201edb5db7cb6bbd8448294d25856 | [
"self._rep = rep\nself._output_sizes = output_sizes\nself._type = att_type\nself._scale = scale\nself._normalise = normalise\nif self._type == 'multihead':\n self._num_heads = num_heads",
"if self._rep == 'identity':\n k, q = (x1, x2)\nelif self._rep == 'mlp':\n k = batch_mlp(x1, self._output_sizes)\n ... | <|body_start_0|>
self._rep = rep
self._output_sizes = output_sizes
self._type = att_type
self._scale = scale
self._normalise = normalise
if self._type == 'multihead':
self._num_heads = num_heads
<|end_body_0|>
<|body_start_1|>
if self._rep == 'identit... | The Attention module. | Attention | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Attention:
"""The Attention module."""
def __init__(self, rep, output_sizes, att_type, scale=1.0, normalise=True, num_heads=8):
"""Creates a attention module. Takes in context inputs, target inputs and representations of each context input/output pair to output an aggregated represen... | stack_v2_sparse_classes_10k_train_006781 | 32,302 | permissive | [
{
"docstring": "Creates a attention module. Takes in context inputs, target inputs and representations of each context input/output pair to output an aggregated representation of the context data. Args: rep: transformation to apply to contexts before computing attention. One of: ['identity', 'mlp']. output_size... | 2 | null | Implement the Python class `Attention` described below.
Class description:
The Attention module.
Method signatures and docstrings:
- def __init__(self, rep, output_sizes, att_type, scale=1.0, normalise=True, num_heads=8): Creates a attention module. Takes in context inputs, target inputs and representations of each c... | Implement the Python class `Attention` described below.
Class description:
The Attention module.
Method signatures and docstrings:
- def __init__(self, rep, output_sizes, att_type, scale=1.0, normalise=True, num_heads=8): Creates a attention module. Takes in context inputs, target inputs and representations of each c... | 480c909e0835a455606e829310ff949c9dd23549 | <|skeleton|>
class Attention:
"""The Attention module."""
def __init__(self, rep, output_sizes, att_type, scale=1.0, normalise=True, num_heads=8):
"""Creates a attention module. Takes in context inputs, target inputs and representations of each context input/output pair to output an aggregated represen... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Attention:
"""The Attention module."""
def __init__(self, rep, output_sizes, att_type, scale=1.0, normalise=True, num_heads=8):
"""Creates a attention module. Takes in context inputs, target inputs and representations of each context input/output pair to output an aggregated representation of the... | the_stack_v2_python_sparse | t2t_bert/utils/tensor2tensor/layers/gaussian_process.py | yyht/BERT | train | 37 |
3ff36a6b3da7b14c44d0deebb97a1cfbc57cbceb | [
"self.title = title\nself.fail_jobs = fail_jobs\nself.job_display = 'none'\nself.fail_job_content = ''\nself.env_content = ''\nself.alarm_info = ''\nself.log_path = log_path\nself.__construct_mail_env(env)\nself.__construct_alarm_info(results)\nself.__construct_fail_job(fail_jobs)",
"if isinstance(env, dict):\n ... | <|body_start_0|>
self.title = title
self.fail_jobs = fail_jobs
self.job_display = 'none'
self.fail_job_content = ''
self.env_content = ''
self.alarm_info = ''
self.log_path = log_path
self.__construct_mail_env(env)
self.__construct_alarm_info(resul... | construct email for benchmark result. | EmailTemplate | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmailTemplate:
"""construct email for benchmark result."""
def __init__(self, title, env, results, log_path, fail_jobs=[]):
"""Args: title(str): benchmark | op_benchmark | benchmark_distribute env(dict): running environment. results(dict): {"Speed": {"header": [table_header0, table_h... | stack_v2_sparse_classes_10k_train_006782 | 5,907 | no_license | [
{
"docstring": "Args: title(str): benchmark | op_benchmark | benchmark_distribute env(dict): running environment. results(dict): {\"Speed\": {\"header\": [table_header0, table_header1, table_header2,] \"data\": [[{'value':, 'color':, }, {'value':, 'color':, }, {'value':, 'color':, }] ...]} \"Mem\": {\"header\":... | 5 | stack_v2_sparse_classes_30k_train_005819 | Implement the Python class `EmailTemplate` described below.
Class description:
construct email for benchmark result.
Method signatures and docstrings:
- def __init__(self, title, env, results, log_path, fail_jobs=[]): Args: title(str): benchmark | op_benchmark | benchmark_distribute env(dict): running environment. re... | Implement the Python class `EmailTemplate` described below.
Class description:
construct email for benchmark result.
Method signatures and docstrings:
- def __init__(self, title, env, results, log_path, fail_jobs=[]): Args: title(str): benchmark | op_benchmark | benchmark_distribute env(dict): running environment. re... | f0e0a303e9af29abb2e86e8918c102b152a37883 | <|skeleton|>
class EmailTemplate:
"""construct email for benchmark result."""
def __init__(self, title, env, results, log_path, fail_jobs=[]):
"""Args: title(str): benchmark | op_benchmark | benchmark_distribute env(dict): running environment. results(dict): {"Speed": {"header": [table_header0, table_h... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EmailTemplate:
"""construct email for benchmark result."""
def __init__(self, title, env, results, log_path, fail_jobs=[]):
"""Args: title(str): benchmark | op_benchmark | benchmark_distribute env(dict): running environment. results(dict): {"Speed": {"header": [table_header0, table_header1, table... | the_stack_v2_python_sparse | scripts/template.py | PaddlePaddle/benchmark | train | 78 |
0b1a60e767d7de7ca2687912534877a99d16c454 | [
"self.host = host\nself.port = port\nself.user = user\nself.password = password",
"for chunk in data:\n if not isinstance(chunk, tuple):\n continue\n match = UID_EXTRACTOR.search(chunk[0])\n if match is None:\n logger.debug(f'Could not find UID in: {chunk[0]}')\n raise IMAPClientErro... | <|body_start_0|>
self.host = host
self.port = port
self.user = user
self.password = password
<|end_body_0|>
<|body_start_1|>
for chunk in data:
if not isinstance(chunk, tuple):
continue
match = UID_EXTRACTOR.search(chunk[0])
if... | IMAP4 (SSL) email client. Attributes: DEFAULT_PORT: Value to be used for the `port` attribute of the constructor if unspecified. Set to the standard IMAP4 SSL port. DEFAULT_MAILBOX: Value to be used for the `mailbox` attribute of the yield_messages() method if unspecified. Set to "INBOX". | IMAP_SSLClient | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IMAP_SSLClient:
"""IMAP4 (SSL) email client. Attributes: DEFAULT_PORT: Value to be used for the `port` attribute of the constructor if unspecified. Set to the standard IMAP4 SSL port. DEFAULT_MAILBOX: Value to be used for the `mailbox` attribute of the yield_messages() method if unspecified. Set ... | stack_v2_sparse_classes_10k_train_006783 | 11,807 | no_license | [
{
"docstring": "Constructor. Args: host: The hostname (without protocol or port) of the IMAP4 server. port: The port of the IMAP4 server to connect to. If unspecified, uses the default. user: The user name or email address to send with the LOGIN command. password: The password to send with the LOGIN command.",
... | 3 | stack_v2_sparse_classes_30k_train_001086 | Implement the Python class `IMAP_SSLClient` described below.
Class description:
IMAP4 (SSL) email client. Attributes: DEFAULT_PORT: Value to be used for the `port` attribute of the constructor if unspecified. Set to the standard IMAP4 SSL port. DEFAULT_MAILBOX: Value to be used for the `mailbox` attribute of the yield... | Implement the Python class `IMAP_SSLClient` described below.
Class description:
IMAP4 (SSL) email client. Attributes: DEFAULT_PORT: Value to be used for the `port` attribute of the constructor if unspecified. Set to the standard IMAP4 SSL port. DEFAULT_MAILBOX: Value to be used for the `mailbox` attribute of the yield... | 72e73cd10465095b19772c79c45432e997f9a7e7 | <|skeleton|>
class IMAP_SSLClient:
"""IMAP4 (SSL) email client. Attributes: DEFAULT_PORT: Value to be used for the `port` attribute of the constructor if unspecified. Set to the standard IMAP4 SSL port. DEFAULT_MAILBOX: Value to be used for the `mailbox` attribute of the yield_messages() method if unspecified. Set ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class IMAP_SSLClient:
"""IMAP4 (SSL) email client. Attributes: DEFAULT_PORT: Value to be used for the `port` attribute of the constructor if unspecified. Set to the standard IMAP4 SSL port. DEFAULT_MAILBOX: Value to be used for the `mailbox` attribute of the yield_messages() method if unspecified. Set to "INBOX".""... | the_stack_v2_python_sparse | windowbox/clients/imap.py | smitelli/windowbox | train | 0 |
f32108115d31efc5130237e9f523d05e7255a515 | [
"if State.__instance is None:\n State.__instance = State()\nreturn State.__instance",
"if State.__instance is not None:\n raise Exception('This class is a singleton!')\nelse:\n State.__instance = self\n self.stocks_realtime_data = RealtimeDataState()\n self.futures_realtime_data = RealtimeDataState... | <|body_start_0|>
if State.__instance is None:
State.__instance = State()
return State.__instance
<|end_body_0|>
<|body_start_1|>
if State.__instance is not None:
raise Exception('This class is a singleton!')
else:
State.__instance = self
s... | State | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class State:
def getInstance() -> State:
"""Static access method."""
<|body_0|>
def __init__(self):
"""Virtually private constructor."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if State.__instance is None:
State.__instance = State()
... | stack_v2_sparse_classes_10k_train_006784 | 903 | no_license | [
{
"docstring": "Static access method.",
"name": "getInstance",
"signature": "def getInstance() -> State"
},
{
"docstring": "Virtually private constructor.",
"name": "__init__",
"signature": "def __init__(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005508 | Implement the Python class `State` described below.
Class description:
Implement the State class.
Method signatures and docstrings:
- def getInstance() -> State: Static access method.
- def __init__(self): Virtually private constructor. | Implement the Python class `State` described below.
Class description:
Implement the State class.
Method signatures and docstrings:
- def getInstance() -> State: Static access method.
- def __init__(self): Virtually private constructor.
<|skeleton|>
class State:
def getInstance() -> State:
"""Static acc... | a18922ebcc54af461ec9123ff0300ba2e0d1a044 | <|skeleton|>
class State:
def getInstance() -> State:
"""Static access method."""
<|body_0|>
def __init__(self):
"""Virtually private constructor."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class State:
def getInstance() -> State:
"""Static access method."""
if State.__instance is None:
State.__instance = State()
return State.__instance
def __init__(self):
"""Virtually private constructor."""
if State.__instance is not None:
raise Ex... | the_stack_v2_python_sparse | finance_app/ui/state/main.py | lukaskellerstein/FinanceApp | train | 0 | |
5e1ef1805bc7114fe85f699e97c96f0d5022d630 | [
"if not isinstance(optimizer, optimization.ExponentialMovingAverage):\n raise ValueError('Optimizer has to be instance ofoptimization.ExponentialMovingAverage forEMACheckpointing action')\nexport_dir = os.path.join(export_dir, 'ema_checkpoints')\ntf.io.gfile.makedirs(os.path.dirname(export_dir))\nself._optimizer... | <|body_start_0|>
if not isinstance(optimizer, optimization.ExponentialMovingAverage):
raise ValueError('Optimizer has to be instance ofoptimization.ExponentialMovingAverage forEMACheckpointing action')
export_dir = os.path.join(export_dir, 'ema_checkpoints')
tf.io.gfile.makedirs(os.p... | Eval action to save checkpoint with average weights when EMA is used. This action swaps the weights of the model with the average weights, then it saves the checkpoint under export_dir/ema_checkpoints. Checkpointing is expensive for large models, so doing this action in eval is more efficient than training. | EMACheckpointing | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EMACheckpointing:
"""Eval action to save checkpoint with average weights when EMA is used. This action swaps the weights of the model with the average weights, then it saves the checkpoint under export_dir/ema_checkpoints. Checkpointing is expensive for large models, so doing this action in eval ... | stack_v2_sparse_classes_10k_train_006785 | 8,466 | permissive | [
{
"docstring": "Initializes the instance. Args: export_dir: `str` for the export directory of the EMA average weights. optimizer: `tf.keras.optimizers.Optimizer` optimizer instance used for training. This will be used to swap the model weights with the average weigths. checkpoint: `tf.train.Checkpoint` instance... | 2 | null | Implement the Python class `EMACheckpointing` described below.
Class description:
Eval action to save checkpoint with average weights when EMA is used. This action swaps the weights of the model with the average weights, then it saves the checkpoint under export_dir/ema_checkpoints. Checkpointing is expensive for larg... | Implement the Python class `EMACheckpointing` described below.
Class description:
Eval action to save checkpoint with average weights when EMA is used. This action swaps the weights of the model with the average weights, then it saves the checkpoint under export_dir/ema_checkpoints. Checkpointing is expensive for larg... | d3507b550a3ade40cade60a79eb5b8978b56c7ae | <|skeleton|>
class EMACheckpointing:
"""Eval action to save checkpoint with average weights when EMA is used. This action swaps the weights of the model with the average weights, then it saves the checkpoint under export_dir/ema_checkpoints. Checkpointing is expensive for large models, so doing this action in eval ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EMACheckpointing:
"""Eval action to save checkpoint with average weights when EMA is used. This action swaps the weights of the model with the average weights, then it saves the checkpoint under export_dir/ema_checkpoints. Checkpointing is expensive for large models, so doing this action in eval is more effic... | the_stack_v2_python_sparse | official/core/actions.py | jianzhnie/models | train | 2 |
c2744166669b99c6e32a885d92505d613db28787 | [
"point_cloud_1 = [[[1.0, 1.0, 1.0], [2.0, 2.0, 2.0], [3.0, 3.0, 3.0]]]\npoint_cloud_2 = [[[1.0, 1.0, 1.0], [2.0, 2.0, 2.0], [3.0, 3.0, 3.0]]]\ntf_point_cloud_1 = tf.constant(point_cloud_1)\ntf_point_cloud_2 = tf.constant(point_cloud_2)\ndist1, idx1, dist2, idx2 = tf_nndistance.nn_distance(tf_point_cloud_1, tf_point... | <|body_start_0|>
point_cloud_1 = [[[1.0, 1.0, 1.0], [2.0, 2.0, 2.0], [3.0, 3.0, 3.0]]]
point_cloud_2 = [[[1.0, 1.0, 1.0], [2.0, 2.0, 2.0], [3.0, 3.0, 3.0]]]
tf_point_cloud_1 = tf.constant(point_cloud_1)
tf_point_cloud_2 = tf.constant(point_cloud_2)
dist1, idx1, dist2, idx2 = tf_n... | NearestNeighborTest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NearestNeighborTest:
def test_nn_distance(self):
"""Test for nearest neighbor algorithm where distance should be 0."""
<|body_0|>
def test_nn_distance_2(self):
"""Test for nearest neighbor algorithm where distance is non-zero."""
<|body_1|>
def test_nn_d... | stack_v2_sparse_classes_10k_train_006786 | 4,084 | permissive | [
{
"docstring": "Test for nearest neighbor algorithm where distance should be 0.",
"name": "test_nn_distance",
"signature": "def test_nn_distance(self)"
},
{
"docstring": "Test for nearest neighbor algorithm where distance is non-zero.",
"name": "test_nn_distance_2",
"signature": "def tes... | 5 | stack_v2_sparse_classes_30k_train_005624 | Implement the Python class `NearestNeighborTest` described below.
Class description:
Implement the NearestNeighborTest class.
Method signatures and docstrings:
- def test_nn_distance(self): Test for nearest neighbor algorithm where distance should be 0.
- def test_nn_distance_2(self): Test for nearest neighbor algori... | Implement the Python class `NearestNeighborTest` described below.
Class description:
Implement the NearestNeighborTest class.
Method signatures and docstrings:
- def test_nn_distance(self): Test for nearest neighbor algorithm where distance should be 0.
- def test_nn_distance_2(self): Test for nearest neighbor algori... | f3cb31909666012dfcf38e5fe0b0f6feb3801560 | <|skeleton|>
class NearestNeighborTest:
def test_nn_distance(self):
"""Test for nearest neighbor algorithm where distance should be 0."""
<|body_0|>
def test_nn_distance_2(self):
"""Test for nearest neighbor algorithm where distance is non-zero."""
<|body_1|>
def test_nn_d... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NearestNeighborTest:
def test_nn_distance(self):
"""Test for nearest neighbor algorithm where distance should be 0."""
point_cloud_1 = [[[1.0, 1.0, 1.0], [2.0, 2.0, 2.0], [3.0, 3.0, 3.0]]]
point_cloud_2 = [[[1.0, 1.0, 1.0], [2.0, 2.0, 2.0], [3.0, 3.0, 3.0]]]
tf_point_cloud_1 = ... | the_stack_v2_python_sparse | src/tf_ops/nn_distance/tf_nndistance_test.py | minghanz/monopsr | train | 0 | |
986b27ecd3188def636acd8d3dca2b517b53693d | [
"self.name = name\nself.international = international\nself.emoji = emoji",
"tag = session.query(Tag).get(name)\nif tag and emoji:\n tag.emoji = True\n if tag.international is True:\n tag.international = False\nif tag and (not international) and tag.international:\n tag.international = False\nif t... | <|body_start_0|>
self.name = name
self.international = international
self.emoji = emoji
<|end_body_0|>
<|body_start_1|>
tag = session.query(Tag).get(name)
if tag and emoji:
tag.emoji = True
if tag.international is True:
tag.international =... | The model for a sticker. | Tag | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Tag:
"""The model for a sticker."""
def __init__(self, name, international, emoji):
"""Create a new sticker."""
<|body_0|>
def get_or_create(session, name, international, emoji=False):
"""Get or create a new sticker."""
<|body_1|>
<|end_skeleton|>
<|bod... | stack_v2_sparse_classes_10k_train_006787 | 1,813 | permissive | [
{
"docstring": "Create a new sticker.",
"name": "__init__",
"signature": "def __init__(self, name, international, emoji)"
},
{
"docstring": "Get or create a new sticker.",
"name": "get_or_create",
"signature": "def get_or_create(session, name, international, emoji=False)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007090 | Implement the Python class `Tag` described below.
Class description:
The model for a sticker.
Method signatures and docstrings:
- def __init__(self, name, international, emoji): Create a new sticker.
- def get_or_create(session, name, international, emoji=False): Get or create a new sticker. | Implement the Python class `Tag` described below.
Class description:
The model for a sticker.
Method signatures and docstrings:
- def __init__(self, name, international, emoji): Create a new sticker.
- def get_or_create(session, name, international, emoji=False): Get or create a new sticker.
<|skeleton|>
class Tag:
... | 873468f8de26cc32d1de9b688140569b8086ab5b | <|skeleton|>
class Tag:
"""The model for a sticker."""
def __init__(self, name, international, emoji):
"""Create a new sticker."""
<|body_0|>
def get_or_create(session, name, international, emoji=False):
"""Get or create a new sticker."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Tag:
"""The model for a sticker."""
def __init__(self, name, international, emoji):
"""Create a new sticker."""
self.name = name
self.international = international
self.emoji = emoji
def get_or_create(session, name, international, emoji=False):
"""Get or creat... | the_stack_v2_python_sparse | stickerfinder/models/tag.py | arlessweschler/sticker-finder | train | 0 |
338d8b8b6d1547208b069f31b3f73533834694b3 | [
"if not root:\n return []\nmapping = collections.defaultdict(int)\ng_max = 0\nunvisited = [root]\nwhile unvisited:\n p = unvisited.pop()\n if not p:\n continue\n mapping[p.val] += 1\n if g_max < mapping[p.val]:\n g_max = mapping[p.val]\n if p.left:\n unvisited.append(p.left)\n... | <|body_start_0|>
if not root:
return []
mapping = collections.defaultdict(int)
g_max = 0
unvisited = [root]
while unvisited:
p = unvisited.pop()
if not p:
continue
mapping[p.val] += 1
if g_max < mapping[p... | Runtime: 109 ms, faster than 14.15% of Python online submissions for Find Mode in Binary Search Tree. Memory Usage: 21.3 MB, less than 49.52% of Python online submissions for Find Mode in Binary Search Tree. | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""Runtime: 109 ms, faster than 14.15% of Python online submissions for Find Mode in Binary Search Tree. Memory Usage: 21.3 MB, less than 49.52% of Python online submissions for Find Mode in Binary Search Tree."""
def findMode(self, root):
""":type root: TreeNode :rtype: Li... | stack_v2_sparse_classes_10k_train_006788 | 2,494 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: List[int]",
"name": "findMode",
"signature": "def findMode(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: List[int]",
"name": "findMode",
"signature": "def findMode(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005852 | Implement the Python class `Solution` described below.
Class description:
Runtime: 109 ms, faster than 14.15% of Python online submissions for Find Mode in Binary Search Tree. Memory Usage: 21.3 MB, less than 49.52% of Python online submissions for Find Mode in Binary Search Tree.
Method signatures and docstrings:
- ... | Implement the Python class `Solution` described below.
Class description:
Runtime: 109 ms, faster than 14.15% of Python online submissions for Find Mode in Binary Search Tree. Memory Usage: 21.3 MB, less than 49.52% of Python online submissions for Find Mode in Binary Search Tree.
Method signatures and docstrings:
- ... | 843db7190a95ebe310f5e867c02d28d43ca99248 | <|skeleton|>
class Solution:
"""Runtime: 109 ms, faster than 14.15% of Python online submissions for Find Mode in Binary Search Tree. Memory Usage: 21.3 MB, less than 49.52% of Python online submissions for Find Mode in Binary Search Tree."""
def findMode(self, root):
""":type root: TreeNode :rtype: Li... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
"""Runtime: 109 ms, faster than 14.15% of Python online submissions for Find Mode in Binary Search Tree. Memory Usage: 21.3 MB, less than 49.52% of Python online submissions for Find Mode in Binary Search Tree."""
def findMode(self, root):
""":type root: TreeNode :rtype: List[int]"""
... | the_stack_v2_python_sparse | datastructure/tree/find_mode_in_binary_search_tree.py | YuanZheCSYZ/algorithm | train | 0 |
ab2505776a3967f7e4f497ce64dfd80e1ce3d398 | [
"cql = 'MATCH(n:' + node_type + '{name:$node_value}) DETACH DELETE(n);'\ntry:\n tx.run(cql, node_value=node_value)\nexcept Exception as e:\n print(str(e))",
"if node_value_1 is None and node_type_1 is None:\n cql = 'MATCH ()-[u:' + relationship + ']-(w:' + node_type_2 + '{name:$node_value_2}) DELETE u;'\... | <|body_start_0|>
cql = 'MATCH(n:' + node_type + '{name:$node_value}) DETACH DELETE(n);'
try:
tx.run(cql, node_value=node_value)
except Exception as e:
print(str(e))
<|end_body_0|>
<|body_start_1|>
if node_value_1 is None and node_type_1 is None:
cql =... | This class contains a number of transactions functions, focused on deletion of nodes and relationships in the graph. According to Neo4j official docs, Transaction functions are the recommended form for containing transactional units of work. This form requires minimal boilerplate code and allows for a clear separation ... | DeleteTransactionFunctions | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeleteTransactionFunctions:
"""This class contains a number of transactions functions, focused on deletion of nodes and relationships in the graph. According to Neo4j official docs, Transaction functions are the recommended form for containing transactional units of work. This form requires minim... | stack_v2_sparse_classes_10k_train_006789 | 12,659 | no_license | [
{
"docstring": "Delete node and all respective relationships :param tx: :param node_value: :param node_type: :return:",
"name": "delete_node",
"signature": "def delete_node(tx, node_value, node_type)"
},
{
"docstring": "Delete Utterance Relationship, based on input nodes :param tx: :param name1:... | 2 | stack_v2_sparse_classes_30k_train_005113 | Implement the Python class `DeleteTransactionFunctions` described below.
Class description:
This class contains a number of transactions functions, focused on deletion of nodes and relationships in the graph. According to Neo4j official docs, Transaction functions are the recommended form for containing transactional ... | Implement the Python class `DeleteTransactionFunctions` described below.
Class description:
This class contains a number of transactions functions, focused on deletion of nodes and relationships in the graph. According to Neo4j official docs, Transaction functions are the recommended form for containing transactional ... | 2177d43c75939a0c4906aa3761772365d4bf79e2 | <|skeleton|>
class DeleteTransactionFunctions:
"""This class contains a number of transactions functions, focused on deletion of nodes and relationships in the graph. According to Neo4j official docs, Transaction functions are the recommended form for containing transactional units of work. This form requires minim... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DeleteTransactionFunctions:
"""This class contains a number of transactions functions, focused on deletion of nodes and relationships in the graph. According to Neo4j official docs, Transaction functions are the recommended form for containing transactional units of work. This form requires minimal boilerplat... | the_stack_v2_python_sparse | deliverable/SourceCode/streaming/src/graph/transaction_functions.py | eldrad294/ICS5114_Practical_Assignment | train | 0 |
14c4bc9375274d83f0d9cdd9799505ba24934674 | [
"assert isinstance(output_size, (int, tuple))\nassert isinstance(return_tensor, bool)\nassert isinstance(channel_first, bool)\nassert isinstance(interpolation, int)\nself.output_size = output_size\nself.return_tensor = return_tensor\nself.channel_first = channel_first\nself.interpolation = interpolation",
"if sel... | <|body_start_0|>
assert isinstance(output_size, (int, tuple))
assert isinstance(return_tensor, bool)
assert isinstance(channel_first, bool)
assert isinstance(interpolation, int)
self.output_size = output_size
self.return_tensor = return_tensor
self.channel_first =... | Rescales a collection of images in a given sample, to a specified size. | BatchRescale | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BatchRescale:
"""Rescales a collection of images in a given sample, to a specified size."""
def __init__(self, output_size, return_tensor=True, channel_first=True, interpolation=cv2.INTER_LANCZOS4):
"""Instantiates a new BatchResize object. Parameters ---------- output_size : int or ... | stack_v2_sparse_classes_10k_train_006790 | 14,169 | no_license | [
{
"docstring": "Instantiates a new BatchResize object. Parameters ---------- output_size : int or tuple The output size of the image (height and width). If an integer is passed as input, then the output size of the image is determined by scaling the height and width of the original image. return_tensor : {True,... | 2 | stack_v2_sparse_classes_30k_test_000117 | Implement the Python class `BatchRescale` described below.
Class description:
Rescales a collection of images in a given sample, to a specified size.
Method signatures and docstrings:
- def __init__(self, output_size, return_tensor=True, channel_first=True, interpolation=cv2.INTER_LANCZOS4): Instantiates a new BatchR... | Implement the Python class `BatchRescale` described below.
Class description:
Rescales a collection of images in a given sample, to a specified size.
Method signatures and docstrings:
- def __init__(self, output_size, return_tensor=True, channel_first=True, interpolation=cv2.INTER_LANCZOS4): Instantiates a new BatchR... | a7c30481822ecb945e3ff6ad184d104361a40ed1 | <|skeleton|>
class BatchRescale:
"""Rescales a collection of images in a given sample, to a specified size."""
def __init__(self, output_size, return_tensor=True, channel_first=True, interpolation=cv2.INTER_LANCZOS4):
"""Instantiates a new BatchResize object. Parameters ---------- output_size : int or ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BatchRescale:
"""Rescales a collection of images in a given sample, to a specified size."""
def __init__(self, output_size, return_tensor=True, channel_first=True, interpolation=cv2.INTER_LANCZOS4):
"""Instantiates a new BatchResize object. Parameters ---------- output_size : int or tuple The out... | the_stack_v2_python_sparse | cheapfake/contrib/transforms.py | hu-simon/cheapfake | train | 0 |
a9f187228de29ab695ec509016128a19d23883dc | [
"re = cloudparking_service().mockCarInOut(send_data['carNum'], 0, send_data['inClientID'])\nresult = re\nAssertions().assert_in_text(result, expect['mockCarInMessage'])",
"re = Information(userLogin).getPresentCar(send_data['parkName'], send_data['carNum'])\nresult = re\nAssertions().assert_in_text(result, expect... | <|body_start_0|>
re = cloudparking_service().mockCarInOut(send_data['carNum'], 0, send_data['inClientID'])
result = re
Assertions().assert_in_text(result, expect['mockCarInMessage'])
<|end_body_0|>
<|body_start_1|>
re = Information(userLogin).getPresentCar(send_data['parkName'], send_da... | 临时车宽进,不需缴费宽出 | TestCarLightRuleInOutNoPay | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCarLightRuleInOutNoPay:
"""临时车宽进,不需缴费宽出"""
def test_mockCarIn(self, send_data, expect):
"""模拟进场"""
<|body_0|>
def test_presentCar(self, userLogin, send_data, expect):
"""查看在场记录"""
<|body_1|>
def test_mockCarOut(self, send_data, expect):
"... | stack_v2_sparse_classes_10k_train_006791 | 1,885 | no_license | [
{
"docstring": "模拟进场",
"name": "test_mockCarIn",
"signature": "def test_mockCarIn(self, send_data, expect)"
},
{
"docstring": "查看在场记录",
"name": "test_presentCar",
"signature": "def test_presentCar(self, userLogin, send_data, expect)"
},
{
"docstring": "模拟离场",
"name": "test_mo... | 4 | stack_v2_sparse_classes_30k_train_001645 | Implement the Python class `TestCarLightRuleInOutNoPay` described below.
Class description:
临时车宽进,不需缴费宽出
Method signatures and docstrings:
- def test_mockCarIn(self, send_data, expect): 模拟进场
- def test_presentCar(self, userLogin, send_data, expect): 查看在场记录
- def test_mockCarOut(self, send_data, expect): 模拟离场
- def te... | Implement the Python class `TestCarLightRuleInOutNoPay` described below.
Class description:
临时车宽进,不需缴费宽出
Method signatures and docstrings:
- def test_mockCarIn(self, send_data, expect): 模拟进场
- def test_presentCar(self, userLogin, send_data, expect): 查看在场记录
- def test_mockCarOut(self, send_data, expect): 模拟离场
- def te... | 34c368c109867da26d9256bca85f872b0fac2ea7 | <|skeleton|>
class TestCarLightRuleInOutNoPay:
"""临时车宽进,不需缴费宽出"""
def test_mockCarIn(self, send_data, expect):
"""模拟进场"""
<|body_0|>
def test_presentCar(self, userLogin, send_data, expect):
"""查看在场记录"""
<|body_1|>
def test_mockCarOut(self, send_data, expect):
"... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestCarLightRuleInOutNoPay:
"""临时车宽进,不需缴费宽出"""
def test_mockCarIn(self, send_data, expect):
"""模拟进场"""
re = cloudparking_service().mockCarInOut(send_data['carNum'], 0, send_data['inClientID'])
result = re
Assertions().assert_in_text(result, expect['mockCarInMessage'])
... | the_stack_v2_python_sparse | test_suite/parkingConfig/freeParking/lightRuleChannel/test_carLightRuleInOut_noPay.py | oyebino/pomp_api | train | 1 |
e0b32925aee455ca49a8ba47f6d45a72e7d74ee0 | [
"super().__init__()\nself.self_attn_layer_norm = nn.LayerNorm(hid_dim)\nself.ff_layer_norm = nn.LayerNorm(hid_dim)\nself.self_attention = MultiHeadAttentionLayer(hid_dim, n_heads, dropout)\nself.positionwise_feedforward = PositionwiseFeedforwardLayer(hid_dim, pf_dim, dropout)\nself.dropout = nn.Dropout(dropout)",
... | <|body_start_0|>
super().__init__()
self.self_attn_layer_norm = nn.LayerNorm(hid_dim)
self.ff_layer_norm = nn.LayerNorm(hid_dim)
self.self_attention = MultiHeadAttentionLayer(hid_dim, n_heads, dropout)
self.positionwise_feedforward = PositionwiseFeedforwardLayer(hid_dim, pf_dim, ... | TransformerEncoderLayer is made up of self-attn and feedforward network. Args: hid_dim: the hidden size of the encoder n_heads: the number of heads in the multi-head attention layers pf_dim: the dimension of the feedforward network model dropout: the dropout value device: the device on which the model is running | TransformerEncoderLayer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransformerEncoderLayer:
"""TransformerEncoderLayer is made up of self-attn and feedforward network. Args: hid_dim: the hidden size of the encoder n_heads: the number of heads in the multi-head attention layers pf_dim: the dimension of the feedforward network model dropout: the dropout value devi... | stack_v2_sparse_classes_10k_train_006792 | 10,223 | permissive | [
{
"docstring": "Initialize model with params.",
"name": "__init__",
"signature": "def __init__(self, hid_dim, n_heads, pf_dim, dropout)"
},
{
"docstring": "Run a forward pass of model over the data.",
"name": "forward",
"signature": "def forward(self, src, src_mask)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001780 | Implement the Python class `TransformerEncoderLayer` described below.
Class description:
TransformerEncoderLayer is made up of self-attn and feedforward network. Args: hid_dim: the hidden size of the encoder n_heads: the number of heads in the multi-head attention layers pf_dim: the dimension of the feedforward networ... | Implement the Python class `TransformerEncoderLayer` described below.
Class description:
TransformerEncoderLayer is made up of self-attn and feedforward network. Args: hid_dim: the hidden size of the encoder n_heads: the number of heads in the multi-head attention layers pf_dim: the dimension of the feedforward networ... | 9cdbf270487751a0ad6862b2fea2ccc0e23a0b67 | <|skeleton|>
class TransformerEncoderLayer:
"""TransformerEncoderLayer is made up of self-attn and feedforward network. Args: hid_dim: the hidden size of the encoder n_heads: the number of heads in the multi-head attention layers pf_dim: the dimension of the feedforward network model dropout: the dropout value devi... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TransformerEncoderLayer:
"""TransformerEncoderLayer is made up of self-attn and feedforward network. Args: hid_dim: the hidden size of the encoder n_heads: the number of heads in the multi-head attention layers pf_dim: the dimension of the feedforward network model dropout: the dropout value device: the devic... | the_stack_v2_python_sparse | caspr/models/transformer.py | microsoft/CASPR | train | 29 |
abfe7c28341650c579e6785b774e3c6cd38c3d30 | [
"if not str_1 and (not str_2):\n return 0\nresult = JaroWinklerDistance.matches(str_1, str_2)\nm = result[0]\nif not m:\n return 0\nif not p:\n p = JaroWinklerDistance.P\nj = (m / len(str_1) + m / len(str_2) + (m - result[1]) / m) / 3\nreturn j + min(p, JaroWinklerDistance.MAX_P) * result[2] * (1 - j)",
... | <|body_start_0|>
if not str_1 and (not str_2):
return 0
result = JaroWinklerDistance.matches(str_1, str_2)
m = result[0]
if not m:
return 0
if not p:
p = JaroWinklerDistance.P
j = (m / len(str_1) + m / len(str_2) + (m - result[1]) / m) ... | JaroWinklerDistance | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JaroWinklerDistance:
def jaro_winkler_distance(str_1, str_2, p=None):
"""jaro-winkler 距离 Keyword arguments: str_1 -- 字符串1 str_2 -- 字符串2 Return: 匹配值"""
<|body_0|>
def jaro_distance(str_1, str_2):
"""jaro 距离 Keyword arguments: str_1 -- 字符串1 str_2 -- 字符串2 Return: 匹配值"""... | stack_v2_sparse_classes_10k_train_006793 | 3,407 | no_license | [
{
"docstring": "jaro-winkler 距离 Keyword arguments: str_1 -- 字符串1 str_2 -- 字符串2 Return: 匹配值",
"name": "jaro_winkler_distance",
"signature": "def jaro_winkler_distance(str_1, str_2, p=None)"
},
{
"docstring": "jaro 距离 Keyword arguments: str_1 -- 字符串1 str_2 -- 字符串2 Return: 匹配值",
"name": "jaro_d... | 3 | stack_v2_sparse_classes_30k_train_005182 | Implement the Python class `JaroWinklerDistance` described below.
Class description:
Implement the JaroWinklerDistance class.
Method signatures and docstrings:
- def jaro_winkler_distance(str_1, str_2, p=None): jaro-winkler 距离 Keyword arguments: str_1 -- 字符串1 str_2 -- 字符串2 Return: 匹配值
- def jaro_distance(str_1, str_2... | Implement the Python class `JaroWinklerDistance` described below.
Class description:
Implement the JaroWinklerDistance class.
Method signatures and docstrings:
- def jaro_winkler_distance(str_1, str_2, p=None): jaro-winkler 距离 Keyword arguments: str_1 -- 字符串1 str_2 -- 字符串2 Return: 匹配值
- def jaro_distance(str_1, str_2... | 6bd8b923dd052ee1aa7efc468c505277b9f2c24f | <|skeleton|>
class JaroWinklerDistance:
def jaro_winkler_distance(str_1, str_2, p=None):
"""jaro-winkler 距离 Keyword arguments: str_1 -- 字符串1 str_2 -- 字符串2 Return: 匹配值"""
<|body_0|>
def jaro_distance(str_1, str_2):
"""jaro 距离 Keyword arguments: str_1 -- 字符串1 str_2 -- 字符串2 Return: 匹配值"""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class JaroWinklerDistance:
def jaro_winkler_distance(str_1, str_2, p=None):
"""jaro-winkler 距离 Keyword arguments: str_1 -- 字符串1 str_2 -- 字符串2 Return: 匹配值"""
if not str_1 and (not str_2):
return 0
result = JaroWinklerDistance.matches(str_1, str_2)
m = result[0]
if ... | the_stack_v2_python_sparse | algorithms/similarity/jaro_winkler_distance.py | zh826256645/my-algorithm-exercises | train | 0 | |
e630b92501fa860ec161e7f1ffec1b2a22ecbdfa | [
"runScriptPath = os.path.join(VAR.CurProject.RootPath, 'project.txt')\nif os.path.exists(runScriptPath):\n with open(runScriptPath, 'r') as runScriptIter:\n for script in runScriptIter.readlines():\n script = script.strip()\n if script.startswith('script') and script.endswith('.py'):... | <|body_start_0|>
runScriptPath = os.path.join(VAR.CurProject.RootPath, 'project.txt')
if os.path.exists(runScriptPath):
with open(runScriptPath, 'r') as runScriptIter:
for script in runScriptIter.readlines():
script = script.strip()
if ... | CaseConfig | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CaseConfig:
def getScriptFromProjectSetting():
"""@summary:从project.txt中获取配置的脚本"""
<|body_0|>
def parseScriptConfig(scriptModule):
"""@summary:解析脚本配置文件 @param scriptModule:要解析的脚本"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
runScriptPath = os.pat... | stack_v2_sparse_classes_10k_train_006794 | 3,578 | no_license | [
{
"docstring": "@summary:从project.txt中获取配置的脚本",
"name": "getScriptFromProjectSetting",
"signature": "def getScriptFromProjectSetting()"
},
{
"docstring": "@summary:解析脚本配置文件 @param scriptModule:要解析的脚本",
"name": "parseScriptConfig",
"signature": "def parseScriptConfig(scriptModule)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004534 | Implement the Python class `CaseConfig` described below.
Class description:
Implement the CaseConfig class.
Method signatures and docstrings:
- def getScriptFromProjectSetting(): @summary:从project.txt中获取配置的脚本
- def parseScriptConfig(scriptModule): @summary:解析脚本配置文件 @param scriptModule:要解析的脚本 | Implement the Python class `CaseConfig` described below.
Class description:
Implement the CaseConfig class.
Method signatures and docstrings:
- def getScriptFromProjectSetting(): @summary:从project.txt中获取配置的脚本
- def parseScriptConfig(scriptModule): @summary:解析脚本配置文件 @param scriptModule:要解析的脚本
<|skeleton|>
class CaseC... | 8935e20a426638462cd1cc7bc048a16751287a2f | <|skeleton|>
class CaseConfig:
def getScriptFromProjectSetting():
"""@summary:从project.txt中获取配置的脚本"""
<|body_0|>
def parseScriptConfig(scriptModule):
"""@summary:解析脚本配置文件 @param scriptModule:要解析的脚本"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CaseConfig:
def getScriptFromProjectSetting():
"""@summary:从project.txt中获取配置的脚本"""
runScriptPath = os.path.join(VAR.CurProject.RootPath, 'project.txt')
if os.path.exists(runScriptPath):
with open(runScriptPath, 'r') as runScriptIter:
for script in runScriptI... | the_stack_v2_python_sparse | autotest/core/conf/CaseConfig.py | wanghaoplus/gatog | train | 0 | |
8d5f1ecbf42f6cc1a97ff8ceb7e70aef366b86c7 | [
"self.all_endpoints_reachable = all_endpoints_reachable\nself.auto_register_target = auto_register_target\nself.auto_registration = auto_registration\nself.bandwidth_limit = bandwidth_limit\nself.cluster_id = cluster_id\nself.cluster_incarnation_id = cluster_incarnation_id\nself.compression_enabled = compression_en... | <|body_start_0|>
self.all_endpoints_reachable = all_endpoints_reachable
self.auto_register_target = auto_register_target
self.auto_registration = auto_registration
self.bandwidth_limit = bandwidth_limit
self.cluster_id = cluster_id
self.cluster_incarnation_id = cluster_in... | Implementation of the 'RegisterRemoteCluster' model. Specifies the settings required for registering a remote Cluster on this local Cluster. Attributes: all_endpoints_reachable (bool): Specifies whether any endpoint (such as a Node) on the remote Cluster is reachable from this local Cluster. If true, a service running ... | RegisterRemoteCluster | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegisterRemoteCluster:
"""Implementation of the 'RegisterRemoteCluster' model. Specifies the settings required for registering a remote Cluster on this local Cluster. Attributes: all_endpoints_reachable (bool): Specifies whether any endpoint (such as a Node) on the remote Cluster is reachable fro... | stack_v2_sparse_classes_10k_train_006795 | 10,649 | permissive | [
{
"docstring": "Constructor for the RegisterRemoteCluster class",
"name": "__init__",
"signature": "def __init__(self, all_endpoints_reachable=None, auto_register_target=None, auto_registration=None, bandwidth_limit=None, cluster_id=None, cluster_incarnation_id=None, compression_enabled=None, descriptio... | 2 | stack_v2_sparse_classes_30k_train_006036 | Implement the Python class `RegisterRemoteCluster` described below.
Class description:
Implementation of the 'RegisterRemoteCluster' model. Specifies the settings required for registering a remote Cluster on this local Cluster. Attributes: all_endpoints_reachable (bool): Specifies whether any endpoint (such as a Node)... | Implement the Python class `RegisterRemoteCluster` described below.
Class description:
Implementation of the 'RegisterRemoteCluster' model. Specifies the settings required for registering a remote Cluster on this local Cluster. Attributes: all_endpoints_reachable (bool): Specifies whether any endpoint (such as a Node)... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class RegisterRemoteCluster:
"""Implementation of the 'RegisterRemoteCluster' model. Specifies the settings required for registering a remote Cluster on this local Cluster. Attributes: all_endpoints_reachable (bool): Specifies whether any endpoint (such as a Node) on the remote Cluster is reachable fro... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RegisterRemoteCluster:
"""Implementation of the 'RegisterRemoteCluster' model. Specifies the settings required for registering a remote Cluster on this local Cluster. Attributes: all_endpoints_reachable (bool): Specifies whether any endpoint (such as a Node) on the remote Cluster is reachable from this local ... | the_stack_v2_python_sparse | cohesity_management_sdk/models/register_remote_cluster.py | cohesity/management-sdk-python | train | 24 |
9df2b00dc22785519e83dd06293c9c9f4addeee8 | [
"self.current_md5 = dict()\nself.previous_md5 = dict()\nself.config_filename = dict()\nself.config_dir = None\nself.existing_config_hostnames = None",
"if not os.path.isdir(config.SETTINGS.main.configs_directory):\n os.mkdir(config.SETTINGS.main.configs_directory)\n LOGGER.debug('Configs directory created a... | <|body_start_0|>
self.current_md5 = dict()
self.previous_md5 = dict()
self.config_filename = dict()
self.config_dir = None
self.existing_config_hostnames = None
<|end_body_0|>
<|body_start_1|>
if not os.path.isdir(config.SETTINGS.main.configs_directory):
os.m... | GetConfig processor for the network_importer. | GetConfig | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetConfig:
"""GetConfig processor for the network_importer."""
def __init__(self) -> None:
"""Initialize the processor and ensure some variables are properly initialized."""
<|body_0|>
def task_started(self, task: Task) -> None:
"""Execute some house keeping item... | stack_v2_sparse_classes_10k_train_006796 | 5,878 | permissive | [
{
"docstring": "Initialize the processor and ensure some variables are properly initialized.",
"name": "__init__",
"signature": "def __init__(self) -> None"
},
{
"docstring": "Execute some house keeping item at the beginning at the execution. Before Update all the config file: - ensure that the ... | 5 | stack_v2_sparse_classes_30k_train_005831 | Implement the Python class `GetConfig` described below.
Class description:
GetConfig processor for the network_importer.
Method signatures and docstrings:
- def __init__(self) -> None: Initialize the processor and ensure some variables are properly initialized.
- def task_started(self, task: Task) -> None: Execute so... | Implement the Python class `GetConfig` described below.
Class description:
GetConfig processor for the network_importer.
Method signatures and docstrings:
- def __init__(self) -> None: Initialize the processor and ensure some variables are properly initialized.
- def task_started(self, task: Task) -> None: Execute so... | 1530eb838727b2b6fbec515b2d06d902e88f9b35 | <|skeleton|>
class GetConfig:
"""GetConfig processor for the network_importer."""
def __init__(self) -> None:
"""Initialize the processor and ensure some variables are properly initialized."""
<|body_0|>
def task_started(self, task: Task) -> None:
"""Execute some house keeping item... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GetConfig:
"""GetConfig processor for the network_importer."""
def __init__(self) -> None:
"""Initialize the processor and ensure some variables are properly initialized."""
self.current_md5 = dict()
self.previous_md5 = dict()
self.config_filename = dict()
self.con... | the_stack_v2_python_sparse | network_importer/processors/get_config.py | gladpark/network-importer | train | 0 |
94dd2a7b7dc645fb21bf709ff2f74110e7d14362 | [
"self._state = VoidPointer()\nresult = raw_cbc_lib.CBC_start_operation(block_cipher.get(), c_uint8_ptr(iv), c_size_t(len(iv)), self._state.address_of())\nif result:\n raise ValueError('Error %d while instantiating the CBC mode' % result)\nself._state = SmartPointer(self._state.get(), raw_cbc_lib.CBC_stop_operati... | <|body_start_0|>
self._state = VoidPointer()
result = raw_cbc_lib.CBC_start_operation(block_cipher.get(), c_uint8_ptr(iv), c_size_t(len(iv)), self._state.address_of())
if result:
raise ValueError('Error %d while instantiating the CBC mode' % result)
self._state = SmartPointer... | *Cipher-Block Chaining (CBC)*. Each of the ciphertext blocks depends on the current and all previous plaintext blocks. An Initialization Vector (*IV*) is required. See `NIST SP800-38A`_ , Section 6.2 . .. _`NIST SP800-38A` : http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf :undocumented: __init__ | CbcMode | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CbcMode:
"""*Cipher-Block Chaining (CBC)*. Each of the ciphertext blocks depends on the current and all previous plaintext blocks. An Initialization Vector (*IV*) is required. See `NIST SP800-38A`_ , Section 6.2 . .. _`NIST SP800-38A` : http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a... | stack_v2_sparse_classes_10k_train_006797 | 10,951 | permissive | [
{
"docstring": "Create a new block cipher, configured in CBC mode. :Parameters: block_cipher : C pointer A smart pointer to the low-level block cipher instance. iv : bytes/bytearray/memoryview The initialization vector to use for encryption or decryption. It is as long as the cipher block. **The IV must be unpr... | 3 | stack_v2_sparse_classes_30k_train_002571 | Implement the Python class `CbcMode` described below.
Class description:
*Cipher-Block Chaining (CBC)*. Each of the ciphertext blocks depends on the current and all previous plaintext blocks. An Initialization Vector (*IV*) is required. See `NIST SP800-38A`_ , Section 6.2 . .. _`NIST SP800-38A` : http://csrc.nist.gov/... | Implement the Python class `CbcMode` described below.
Class description:
*Cipher-Block Chaining (CBC)*. Each of the ciphertext blocks depends on the current and all previous plaintext blocks. An Initialization Vector (*IV*) is required. See `NIST SP800-38A`_ , Section 6.2 . .. _`NIST SP800-38A` : http://csrc.nist.gov/... | fa82044a2dc2f0f1f7454f5394e6d68fa923c289 | <|skeleton|>
class CbcMode:
"""*Cipher-Block Chaining (CBC)*. Each of the ciphertext blocks depends on the current and all previous plaintext blocks. An Initialization Vector (*IV*) is required. See `NIST SP800-38A`_ , Section 6.2 . .. _`NIST SP800-38A` : http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CbcMode:
"""*Cipher-Block Chaining (CBC)*. Each of the ciphertext blocks depends on the current and all previous plaintext blocks. An Initialization Vector (*IV*) is required. See `NIST SP800-38A`_ , Section 6.2 . .. _`NIST SP800-38A` : http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf :undocum... | the_stack_v2_python_sparse | venv/lib/python3.6/site-packages/Crypto/Cipher/_mode_cbc.py | masora1030/eigoyurusan | train | 11 |
46e1b6040e5c41d9cd5760ec9902fce4a5acda80 | [
"self.client = aff4.FACTORY.Open(self.client_id, token=self.token)\nself.system = str(self.client.Get(self.client.Schema.SYSTEM))\nself.os_version = str(self.client.Get(self.client.Schema.OS_VERSION))\nself.os_major_version = self.os_version.split('.')[0]\nif self.use_tsk:\n self.path_type = rdfvalue.PathSpec.Pa... | <|body_start_0|>
self.client = aff4.FACTORY.Open(self.client_id, token=self.token)
self.system = str(self.client.Get(self.client.Schema.SYSTEM))
self.os_version = str(self.client.Get(self.client.Schema.OS_VERSION))
self.os_major_version = self.os_version.split('.')[0]
if self.use... | Do the initial work for a Linux system investigation. This encapsulates the different platform specific modules. | LinSystemActivityInvestigation | [
"Apache-2.0",
"DOC"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinSystemActivityInvestigation:
"""Do the initial work for a Linux system investigation. This encapsulates the different platform specific modules."""
def Start(self):
"""Start."""
<|body_0|>
def FinishFlow(self, responses):
"""Complete anything we need to do for... | stack_v2_sparse_classes_10k_train_006798 | 10,734 | permissive | [
{
"docstring": "Start.",
"name": "Start",
"signature": "def Start(self)"
},
{
"docstring": "Complete anything we need to do for each flow finishing.",
"name": "FinishFlow",
"signature": "def FinishFlow(self, responses)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004487 | Implement the Python class `LinSystemActivityInvestigation` described below.
Class description:
Do the initial work for a Linux system investigation. This encapsulates the different platform specific modules.
Method signatures and docstrings:
- def Start(self): Start.
- def FinishFlow(self, responses): Complete anyth... | Implement the Python class `LinSystemActivityInvestigation` described below.
Class description:
Do the initial work for a Linux system investigation. This encapsulates the different platform specific modules.
Method signatures and docstrings:
- def Start(self): Start.
- def FinishFlow(self, responses): Complete anyth... | ba1648b97a76f844ffb8e1891cc9e2680f9b1c6e | <|skeleton|>
class LinSystemActivityInvestigation:
"""Do the initial work for a Linux system investigation. This encapsulates the different platform specific modules."""
def Start(self):
"""Start."""
<|body_0|>
def FinishFlow(self, responses):
"""Complete anything we need to do for... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LinSystemActivityInvestigation:
"""Do the initial work for a Linux system investigation. This encapsulates the different platform specific modules."""
def Start(self):
"""Start."""
self.client = aff4.FACTORY.Open(self.client_id, token=self.token)
self.system = str(self.client.Get(... | the_stack_v2_python_sparse | lib/flows/general/automation.py | defaultnamehere/grr | train | 3 |
410804580eedfb7a0f337e7c4304c6047c1b85c2 | [
"components = []\n\ndef dfs(node):\n if node is None:\n components.append('')\n else:\n components.append(str(node.val))\n dfs(node.left)\n dfs(node.right)\ndfs(root)\nreturn ','.join(components) + ','",
"if data == ',':\n return None\nself.index = 0\n\ndef dfs():\n if data... | <|body_start_0|>
components = []
def dfs(node):
if node is None:
components.append('')
else:
components.append(str(node.val))
dfs(node.left)
dfs(node.right)
dfs(root)
return ','.join(components) + ',... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_10k_train_006799 | 1,917 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_005746 | 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:... | 488d93280d45ea686d30b0928e96aa5ed5498e6b | <|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_10k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
components = []
def dfs(node):
if node is None:
components.append('')
else:
components.append(str(node.val))
... | the_stack_v2_python_sparse | leetcode/lc297.py | JasonXJ/algorithms | train | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.