blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7678f4c421ff69dd93275c0a0215d12d27df056e | [
"try:\n username = self.request.META['persistent-id']\nexcept KeyError:\n username = self.request.META['persistent_id']\ntry:\n JenkinsUser.objects.get(username=username)\n messages.error(request, 'User already registered')\n return bad_request(request, None, template_name=LOGIN_TEMPLATE)\nexcept Jen... | <|body_start_0|>
try:
username = self.request.META['persistent-id']
except KeyError:
username = self.request.META['persistent_id']
try:
JenkinsUser.objects.get(username=username)
messages.error(request, 'User already registered')
return... | This must be protected by shibboleth. Create a local account to associate with the shibboleth | ShibbolethUserRegistration | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShibbolethUserRegistration:
"""This must be protected by shibboleth. Create a local account to associate with the shibboleth"""
def get(self, request, *args, **kwargs):
"""Check that the persistent-id has not already been registered, before providing the form."""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_015300 | 21,511 | permissive | [
{
"docstring": "Check that the persistent-id has not already been registered, before providing the form.",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "Override the method from RegistrationView. Create a new user. Based on code from RegistrationView.re... | 2 | stack_v2_sparse_classes_30k_test_000411 | Implement the Python class `ShibbolethUserRegistration` described below.
Class description:
This must be protected by shibboleth. Create a local account to associate with the shibboleth
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Check that the persistent-id has not already been regis... | Implement the Python class `ShibbolethUserRegistration` described below.
Class description:
This must be protected by shibboleth. Create a local account to associate with the shibboleth
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Check that the persistent-id has not already been regis... | 598b3bc10b72b7b277510cf40e1a4bc56b07452a | <|skeleton|>
class ShibbolethUserRegistration:
"""This must be protected by shibboleth. Create a local account to associate with the shibboleth"""
def get(self, request, *args, **kwargs):
"""Check that the persistent-id has not already been registered, before providing the form."""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ShibbolethUserRegistration:
"""This must be protected by shibboleth. Create a local account to associate with the shibboleth"""
def get(self, request, *args, **kwargs):
"""Check that the persistent-id has not already been registered, before providing the form."""
try:
username... | the_stack_v2_python_sparse | jenkins_auth/views.py | antony-wilson/jenkins_auth | train | 0 |
ca40897235522383732a00a74b42a86d223d6390 | [
"if len(x) != len(y):\n raise ValueError('Input x and y must have equal length')\nself.sorted_collection = SortedCollection(zip(x, y), key=lambda e: e[0])\nself.name = name",
"item = None\ntry:\n item = self.sorted_collection.find(x)\nexcept ValueError:\n pass\nif exact or item:\n return item\nelse:\n... | <|body_start_0|>
if len(x) != len(y):
raise ValueError('Input x and y must have equal length')
self.sorted_collection = SortedCollection(zip(x, y), key=lambda e: e[0])
self.name = name
<|end_body_0|>
<|body_start_1|>
item = None
try:
item = self.sorted_co... | Lookup | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Lookup:
def __init__(self, x, y, name):
""":param x: :type x: list :param y: :type y: list :param name: :type name: str"""
<|body_0|>
def lookup(self, x, exact=False):
"""Find the item (x, value) :param x: :param exact: :return: when approximate match is enabled if t... | stack_v2_sparse_classes_36k_train_015301 | 9,313 | no_license | [
{
"docstring": ":param x: :type x: list :param y: :type y: list :param name: :type name: str",
"name": "__init__",
"signature": "def __init__(self, x, y, name)"
},
{
"docstring": "Find the item (x, value) :param x: :param exact: :return: when approximate match is enabled if the item is present, ... | 2 | stack_v2_sparse_classes_30k_train_009391 | Implement the Python class `Lookup` described below.
Class description:
Implement the Lookup class.
Method signatures and docstrings:
- def __init__(self, x, y, name): :param x: :type x: list :param y: :type y: list :param name: :type name: str
- def lookup(self, x, exact=False): Find the item (x, value) :param x: :p... | Implement the Python class `Lookup` described below.
Class description:
Implement the Lookup class.
Method signatures and docstrings:
- def __init__(self, x, y, name): :param x: :type x: list :param y: :type y: list :param name: :type name: str
- def lookup(self, x, exact=False): Find the item (x, value) :param x: :p... | e0b472286f2b628c24f12aef19cfaf8f2ee0389e | <|skeleton|>
class Lookup:
def __init__(self, x, y, name):
""":param x: :type x: list :param y: :type y: list :param name: :type name: str"""
<|body_0|>
def lookup(self, x, exact=False):
"""Find the item (x, value) :param x: :param exact: :return: when approximate match is enabled if t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Lookup:
def __init__(self, x, y, name):
""":param x: :type x: list :param y: :type y: list :param name: :type name: str"""
if len(x) != len(y):
raise ValueError('Input x and y must have equal length')
self.sorted_collection = SortedCollection(zip(x, y), key=lambda e: e[0])
... | the_stack_v2_python_sparse | SWIFT/scripts/services/data_service.py | xys234/Work | train | 0 | |
3ff33e29a6b727c15d1991a465e288c75749dbb6 | [
"self.regulator = regulator\nself.feeler = feeler\nself.generator = self.feeler\nself.collector = collectors.FeelCollector(feeler.get_names())\nself.export = self.collector.export",
"feeling = self.feeler.calculate(power)\nif self.regulator:\n feeling = self.regulator.regulate(feeling)\n if feeling is None:... | <|body_start_0|>
self.regulator = regulator
self.feeler = feeler
self.generator = self.feeler
self.collector = collectors.FeelCollector(feeler.get_names())
self.export = self.collector.export
<|end_body_0|>
<|body_start_1|>
feeling = self.feeler.calculate(power)
... | Provides a feeling processor. TODO | FeelProcessor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeelProcessor:
"""Provides a feeling processor. TODO"""
def __init__(self, feeler, regulator):
"""Constructor."""
<|body_0|>
def generate(self, timestamp, power):
"""Generator of feelings."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.reg... | stack_v2_sparse_classes_36k_train_015302 | 1,213 | no_license | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self, feeler, regulator)"
},
{
"docstring": "Generator of feelings.",
"name": "generate",
"signature": "def generate(self, timestamp, power)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016649 | Implement the Python class `FeelProcessor` described below.
Class description:
Provides a feeling processor. TODO
Method signatures and docstrings:
- def __init__(self, feeler, regulator): Constructor.
- def generate(self, timestamp, power): Generator of feelings. | Implement the Python class `FeelProcessor` described below.
Class description:
Provides a feeling processor. TODO
Method signatures and docstrings:
- def __init__(self, feeler, regulator): Constructor.
- def generate(self, timestamp, power): Generator of feelings.
<|skeleton|>
class FeelProcessor:
"""Provides a ... | 38cbb8d55cec730a03899692a37273f0817875eb | <|skeleton|>
class FeelProcessor:
"""Provides a feeling processor. TODO"""
def __init__(self, feeler, regulator):
"""Constructor."""
<|body_0|>
def generate(self, timestamp, power):
"""Generator of feelings."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FeelProcessor:
"""Provides a feeling processor. TODO"""
def __init__(self, feeler, regulator):
"""Constructor."""
self.regulator = regulator
self.feeler = feeler
self.generator = self.feeler
self.collector = collectors.FeelCollector(feeler.get_names())
self... | the_stack_v2_python_sparse | backend/engine/processors/feel.py | pdpino/muse-player | train | 0 |
3d44111898dad01053a9a72e2f8e4d158fcbf5d7 | [
"answer = await _duckduckgo(ctx, query='random name')\nanswer = answer.replace('(random)', '')\nawait ctx.send(answer)",
"query = f'find anagram for {phrase}'\nanswer = await _duckduckgo(ctx, query=query)\nif answer:\n await ctx.send(answer)\nelse:\n await ctx.send('No anagrams found. :<')"
] | <|body_start_0|>
answer = await _duckduckgo(ctx, query='random name')
answer = answer.replace('(random)', '')
await ctx.send(answer)
<|end_body_0|>
<|body_start_1|>
query = f'find anagram for {phrase}'
answer = await _duckduckgo(ctx, query=query)
if answer:
a... | Words | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Words:
async def rname(self, ctx):
"""Generate a random name."""
<|body_0|>
async def anagram(self, ctx, *, phrase: str):
"""Find possible anagrams of a phrase. * phrase = The message to find an anagram for."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_015303 | 4,354 | permissive | [
{
"docstring": "Generate a random name.",
"name": "rname",
"signature": "async def rname(self, ctx)"
},
{
"docstring": "Find possible anagrams of a phrase. * phrase = The message to find an anagram for.",
"name": "anagram",
"signature": "async def anagram(self, ctx, *, phrase: str)"
}
... | 2 | stack_v2_sparse_classes_30k_train_009741 | Implement the Python class `Words` described below.
Class description:
Implement the Words class.
Method signatures and docstrings:
- async def rname(self, ctx): Generate a random name.
- async def anagram(self, ctx, *, phrase: str): Find possible anagrams of a phrase. * phrase = The message to find an anagram for. | Implement the Python class `Words` described below.
Class description:
Implement the Words class.
Method signatures and docstrings:
- async def rname(self, ctx): Generate a random name.
- async def anagram(self, ctx, *, phrase: str): Find possible anagrams of a phrase. * phrase = The message to find an anagram for.
... | 3a456ad06814181d13d4aabefc151756c55444f4 | <|skeleton|>
class Words:
async def rname(self, ctx):
"""Generate a random name."""
<|body_0|>
async def anagram(self, ctx, *, phrase: str):
"""Find possible anagrams of a phrase. * phrase = The message to find an anagram for."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Words:
async def rname(self, ctx):
"""Generate a random name."""
answer = await _duckduckgo(ctx, query='random name')
answer = answer.replace('(random)', '')
await ctx.send(answer)
async def anagram(self, ctx, *, phrase: str):
"""Find possible anagrams of a phrase.... | the_stack_v2_python_sparse | cogs/ddg.py | sokcheng/Kitsuchan-NG | train | 1 | |
09933c8f95b2ecb9305df7e2f59cb44424a8e78d | [
"start_urls = []\ntry:\n thing = int(input('你想爬取琉璃神社的哪类数据?请选择输入[1、动画,2、漫画,3、游戏,4、小说,5、壁纸/文章,6、全部]中的一个数字:'))\n start_urls.append(self.start_urls[thing - 1])\nexcept Exception:\n start_urls = self.start_urls\nfor url in start_urls:\n yield scrapy.Request(url=url, callback=self.parse)",
"dataPath = os.pa... | <|body_start_0|>
start_urls = []
try:
thing = int(input('你想爬取琉璃神社的哪类数据?请选择输入[1、动画,2、漫画,3、游戏,4、小说,5、壁纸/文章,6、全部]中的一个数字:'))
start_urls.append(self.start_urls[thing - 1])
except Exception:
start_urls = self.start_urls
for url in start_urls:
yie... | GlazedshrineSpider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GlazedshrineSpider:
def start_requests(self):
"""在第一个请求开始之前,让用户选择要爬取的内容 :return:start_urls"""
<|body_0|>
def parse_page(self, response):
"""解析分页内的数据,即依据分页url解析帖子 :param response:响应文件 :return:item's url 和url"""
<|body_1|>
def parse_rsc(self, response):
... | stack_v2_sparse_classes_36k_train_015304 | 7,190 | no_license | [
{
"docstring": "在第一个请求开始之前,让用户选择要爬取的内容 :return:start_urls",
"name": "start_requests",
"signature": "def start_requests(self)"
},
{
"docstring": "解析分页内的数据,即依据分页url解析帖子 :param response:响应文件 :return:item's url 和url",
"name": "parse_page",
"signature": "def parse_page(self, response)"
},
... | 3 | stack_v2_sparse_classes_30k_train_004238 | Implement the Python class `GlazedshrineSpider` described below.
Class description:
Implement the GlazedshrineSpider class.
Method signatures and docstrings:
- def start_requests(self): 在第一个请求开始之前,让用户选择要爬取的内容 :return:start_urls
- def parse_page(self, response): 解析分页内的数据,即依据分页url解析帖子 :param response:响应文件 :return:item'... | Implement the Python class `GlazedshrineSpider` described below.
Class description:
Implement the GlazedshrineSpider class.
Method signatures and docstrings:
- def start_requests(self): 在第一个请求开始之前,让用户选择要爬取的内容 :return:start_urls
- def parse_page(self, response): 解析分页内的数据,即依据分页url解析帖子 :param response:响应文件 :return:item'... | 12963cccabcd3d51d66f94711c71f8908a16f281 | <|skeleton|>
class GlazedshrineSpider:
def start_requests(self):
"""在第一个请求开始之前,让用户选择要爬取的内容 :return:start_urls"""
<|body_0|>
def parse_page(self, response):
"""解析分页内的数据,即依据分页url解析帖子 :param response:响应文件 :return:item's url 和url"""
<|body_1|>
def parse_rsc(self, response):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GlazedshrineSpider:
def start_requests(self):
"""在第一个请求开始之前,让用户选择要爬取的内容 :return:start_urls"""
start_urls = []
try:
thing = int(input('你想爬取琉璃神社的哪类数据?请选择输入[1、动画,2、漫画,3、游戏,4、小说,5、壁纸/文章,6、全部]中的一个数字:'))
start_urls.append(self.start_urls[thing - 1])
except Exc... | the_stack_v2_python_sparse | 06Shrine/Glazed_Shrine/Glazed_Shrine/spiders/GlazedShrine.py | ABBOOT/Scrapy_BackUp | train | 0 | |
0e3cf994647639950a90ba77d55f474b43a9231e | [
"if self.year_id and self.date_start and self.date_stop:\n if self.year_id.date_stop < self.date_stop or self.year_id.date_stop < self.date_start or self.year_id.date_start > self.date_start or (self.year_id.date_start > self.date_stop):\n raise ValidationError(_('Some of the months periods overlap or is ... | <|body_start_0|>
if self.year_id and self.date_start and self.date_stop:
if self.year_id.date_stop < self.date_stop or self.year_id.date_stop < self.date_start or self.year_id.date_start > self.date_start or (self.year_id.date_start > self.date_stop):
raise ValidationError(_('Some of... | Defining a month of an academic year. | AcademicMonth | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AcademicMonth:
"""Defining a month of an academic year."""
def _check_year_limit(self):
"""Method to check year limit"""
<|body_0|>
def check_months(self):
"""Method to check duration of date"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if se... | stack_v2_sparse_classes_36k_train_015305 | 38,006 | no_license | [
{
"docstring": "Method to check year limit",
"name": "_check_year_limit",
"signature": "def _check_year_limit(self)"
},
{
"docstring": "Method to check duration of date",
"name": "check_months",
"signature": "def check_months(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016485 | Implement the Python class `AcademicMonth` described below.
Class description:
Defining a month of an academic year.
Method signatures and docstrings:
- def _check_year_limit(self): Method to check year limit
- def check_months(self): Method to check duration of date | Implement the Python class `AcademicMonth` described below.
Class description:
Defining a month of an academic year.
Method signatures and docstrings:
- def _check_year_limit(self): Method to check year limit
- def check_months(self): Method to check duration of date
<|skeleton|>
class AcademicMonth:
"""Defining... | 6a9793f3a15da9eed40bf840b1d9a46457c5fd55 | <|skeleton|>
class AcademicMonth:
"""Defining a month of an academic year."""
def _check_year_limit(self):
"""Method to check year limit"""
<|body_0|>
def check_months(self):
"""Method to check duration of date"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AcademicMonth:
"""Defining a month of an academic year."""
def _check_year_limit(self):
"""Method to check year limit"""
if self.year_id and self.date_start and self.date_stop:
if self.year_id.date_stop < self.date_stop or self.year_id.date_stop < self.date_start or self.year_... | the_stack_v2_python_sparse | school/models/school.py | JayVora-SerpentCS/OdooEduERP | train | 121 |
426fc61ad9c6c50eedc5e13990a2950b6aa2fd8a | [
"self.Account: Optional[Account] = None\nself.StartTimeUtc: datetime = datetime.min\nself.EndTimeUtc: datetime = datetime.min\nself.Host: Optional[Host] = None\nself.SessionId: str = ''\nsuper().__init__(src_entity=src_entity, **kwargs)\nif src_event is not None:\n if 'TimeCreatedUtc' in src_event:\n self... | <|body_start_0|>
self.Account: Optional[Account] = None
self.StartTimeUtc: datetime = datetime.min
self.EndTimeUtc: datetime = datetime.min
self.Host: Optional[Host] = None
self.SessionId: str = ''
super().__init__(src_entity=src_entity, **kwargs)
if src_event is ... | HostLogonSession Entity class. Attributes ---------- Account : Account HostLogonSession Account StartTimeUtc : datetime HostLogonSession StartTimeUtc EndTimeUtc : datetime HostLogonSession EndTimeUtc Host : Host HostLogonSession Host SessionId : str HostLogonSession SessionId | HostLogonSession | [
"LicenseRef-scancode-generic-cla",
"LGPL-3.0-only",
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown",
"ISC",
"LGPL-2.0-or-later",
"PSF-2.0",
"Apache-2.0",
"BSD-2-Clause",
"LGPL-2.1-only",
"Unlicense",
"Python-2.0",
"LicenseRef-scancode-python-cwi",
"MIT",
"LGPL-2.1-or-later",
"GPL-2.... | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HostLogonSession:
"""HostLogonSession Entity class. Attributes ---------- Account : Account HostLogonSession Account StartTimeUtc : datetime HostLogonSession StartTimeUtc EndTimeUtc : datetime HostLogonSession EndTimeUtc Host : Host HostLogonSession Host SessionId : str HostLogonSession SessionId... | stack_v2_sparse_classes_36k_train_015306 | 3,178 | permissive | [
{
"docstring": "Create a new instance of the entity type. Parameters ---------- src_entity : Mapping[str, Any], optional Create entity from existing entity or other mapping object that implements entity properties. (the default is None) src_event : Mapping[str, Any], optional Create entity from event properties... | 2 | stack_v2_sparse_classes_30k_train_002077 | Implement the Python class `HostLogonSession` described below.
Class description:
HostLogonSession Entity class. Attributes ---------- Account : Account HostLogonSession Account StartTimeUtc : datetime HostLogonSession StartTimeUtc EndTimeUtc : datetime HostLogonSession EndTimeUtc Host : Host HostLogonSession Host Ses... | Implement the Python class `HostLogonSession` described below.
Class description:
HostLogonSession Entity class. Attributes ---------- Account : Account HostLogonSession Account StartTimeUtc : datetime HostLogonSession StartTimeUtc EndTimeUtc : datetime HostLogonSession EndTimeUtc Host : Host HostLogonSession Host Ses... | 44b1a390510f9be2772ec62cb95d0fc67dfc234b | <|skeleton|>
class HostLogonSession:
"""HostLogonSession Entity class. Attributes ---------- Account : Account HostLogonSession Account StartTimeUtc : datetime HostLogonSession StartTimeUtc EndTimeUtc : datetime HostLogonSession EndTimeUtc Host : Host HostLogonSession Host SessionId : str HostLogonSession SessionId... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HostLogonSession:
"""HostLogonSession Entity class. Attributes ---------- Account : Account HostLogonSession Account StartTimeUtc : datetime HostLogonSession StartTimeUtc EndTimeUtc : datetime HostLogonSession EndTimeUtc Host : Host HostLogonSession Host SessionId : str HostLogonSession SessionId"""
def ... | the_stack_v2_python_sparse | msticpy/datamodel/entities/host_logon_session.py | RiskIQ/msticpy | train | 1 |
c8d901048491bd08db19abb324e923c5eb7bd445 | [
"prog = None\nvs_source = self._load_shader('vertex', self.meta.vertex_shader)\ngeo_source = self._load_shader('geometry', self.meta.geometry_shader)\nfs_source = self._load_shader('fragment', self.meta.fragment_shader)\ntc_source = self._load_shader('tess_control', self.meta.tess_control_shader)\nte_source = self.... | <|body_start_0|>
prog = None
vs_source = self._load_shader('vertex', self.meta.vertex_shader)
geo_source = self._load_shader('geometry', self.meta.geometry_shader)
fs_source = self._load_shader('fragment', self.meta.fragment_shader)
tc_source = self._load_shader('tess_control', s... | Loader | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Loader:
def load(self) -> Union[moderngl.Program, moderngl.ComputeShader, program.ReloadableProgram]:
"""Loads a shader program were each shader is a separate file. This detected and dictated by the ``kind`` in the ``ProgramDescription``. Returns: moderngl.Program: The Program instance""... | stack_v2_sparse_classes_36k_train_015307 | 3,339 | permissive | [
{
"docstring": "Loads a shader program were each shader is a separate file. This detected and dictated by the ``kind`` in the ``ProgramDescription``. Returns: moderngl.Program: The Program instance",
"name": "load",
"signature": "def load(self) -> Union[moderngl.Program, moderngl.ComputeShader, program.... | 3 | null | Implement the Python class `Loader` described below.
Class description:
Implement the Loader class.
Method signatures and docstrings:
- def load(self) -> Union[moderngl.Program, moderngl.ComputeShader, program.ReloadableProgram]: Loads a shader program were each shader is a separate file. This detected and dictated b... | Implement the Python class `Loader` described below.
Class description:
Implement the Loader class.
Method signatures and docstrings:
- def load(self) -> Union[moderngl.Program, moderngl.ComputeShader, program.ReloadableProgram]: Loads a shader program were each shader is a separate file. This detected and dictated b... | 200f2b9ea8b350b0ac9bb6a2d24310c0d8227794 | <|skeleton|>
class Loader:
def load(self) -> Union[moderngl.Program, moderngl.ComputeShader, program.ReloadableProgram]:
"""Loads a shader program were each shader is a separate file. This detected and dictated by the ``kind`` in the ``ProgramDescription``. Returns: moderngl.Program: The Program instance""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Loader:
def load(self) -> Union[moderngl.Program, moderngl.ComputeShader, program.ReloadableProgram]:
"""Loads a shader program were each shader is a separate file. This detected and dictated by the ``kind`` in the ``ProgramDescription``. Returns: moderngl.Program: The Program instance"""
prog... | the_stack_v2_python_sparse | moderngl_window/loaders/program/separate.py | moderngl/moderngl-window | train | 205 | |
1d81bd50d358bfc8df9166e6e4c7e7b911765f20 | [
"super(LstmClassifier, self).__init__()\nself.hparams = hparams\nself.weights = weights\nself.embedding = nn.Embedding(hparams['vocab_size'], hparams['emb_dim'])\nif weights:\n self.embedding.weight = nn.Parameter(weights['glove'], requires_grad=False)\nself.lstm = nn.LSTM(hparams['emb_dim'], hparams['hidden_dim... | <|body_start_0|>
super(LstmClassifier, self).__init__()
self.hparams = hparams
self.weights = weights
self.embedding = nn.Embedding(hparams['vocab_size'], hparams['emb_dim'])
if weights:
self.embedding.weight = nn.Parameter(weights['glove'], requires_grad=False)
... | LstmClassifier | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LstmClassifier:
def __init__(self, hparams, weights=None):
"""LSTM RNN Classifier Args: hparams : dictionary of hyperparameters"""
<|body_0|>
def forward(self, sequence, batch_size=None, get_hidden=False):
"""Forward Operation. Args: sequence : list of indices based ... | stack_v2_sparse_classes_36k_train_015308 | 2,171 | no_license | [
{
"docstring": "LSTM RNN Classifier Args: hparams : dictionary of hyperparameters",
"name": "__init__",
"signature": "def __init__(self, hparams, weights=None)"
},
{
"docstring": "Forward Operation. Args: sequence : list of indices based off a sentence",
"name": "forward",
"signature": "... | 2 | stack_v2_sparse_classes_30k_train_012654 | Implement the Python class `LstmClassifier` described below.
Class description:
Implement the LstmClassifier class.
Method signatures and docstrings:
- def __init__(self, hparams, weights=None): LSTM RNN Classifier Args: hparams : dictionary of hyperparameters
- def forward(self, sequence, batch_size=None, get_hidden... | Implement the Python class `LstmClassifier` described below.
Class description:
Implement the LstmClassifier class.
Method signatures and docstrings:
- def __init__(self, hparams, weights=None): LSTM RNN Classifier Args: hparams : dictionary of hyperparameters
- def forward(self, sequence, batch_size=None, get_hidden... | 13a3eec0da8fe0e0b49cba54f8ce3bdf8824f41d | <|skeleton|>
class LstmClassifier:
def __init__(self, hparams, weights=None):
"""LSTM RNN Classifier Args: hparams : dictionary of hyperparameters"""
<|body_0|>
def forward(self, sequence, batch_size=None, get_hidden=False):
"""Forward Operation. Args: sequence : list of indices based ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LstmClassifier:
def __init__(self, hparams, weights=None):
"""LSTM RNN Classifier Args: hparams : dictionary of hyperparameters"""
super(LstmClassifier, self).__init__()
self.hparams = hparams
self.weights = weights
self.embedding = nn.Embedding(hparams['vocab_size'], h... | the_stack_v2_python_sparse | srmnlp/reduce/lstm.py | qinghecode/SRM-NLP-Workshop-2019 | train | 0 | |
25256e9179a4d95e69f635054e44a897a129cf00 | [
"def dfs(cur: 'TrieNode') -> str:\n res = []\n for key, next in cur.children.items():\n res.append(key)\n res.append(dfs(next))\n return f\"<{''.join(res)}>\"\nreturn dfs(root)",
"def dfs(cur: str) -> 'TrieNode':\n res = TrieNode()\n depth = 0\n key, child = ('', [])\n for char ... | <|body_start_0|>
def dfs(cur: 'TrieNode') -> str:
res = []
for key, next in cur.children.items():
res.append(key)
res.append(dfs(next))
return f"<{''.join(res)}>"
return dfs(root)
<|end_body_0|>
<|body_start_1|>
def dfs(cur: st... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def serialize(self, root: 'TrieNode') -> str:
"""序列化trie"""
<|body_0|>
def deserialize(self, data: str) -> 'TrieNode':
"""反序列化trie"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def dfs(cur: 'TrieNode') -> str:
res = []
... | stack_v2_sparse_classes_36k_train_015309 | 1,640 | no_license | [
{
"docstring": "序列化trie",
"name": "serialize",
"signature": "def serialize(self, root: 'TrieNode') -> str"
},
{
"docstring": "反序列化trie",
"name": "deserialize",
"signature": "def deserialize(self, data: str) -> 'TrieNode'"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def serialize(self, root: 'TrieNode') -> str: 序列化trie
- def deserialize(self, data: str) -> 'TrieNode': 反序列化trie | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def serialize(self, root: 'TrieNode') -> str: 序列化trie
- def deserialize(self, data: str) -> 'TrieNode': 反序列化trie
<|skeleton|>
class Solution:
def serialize(self, root: 'Tri... | 7e79e26bb8f641868561b186e34c1127ed63c9e0 | <|skeleton|>
class Solution:
def serialize(self, root: 'TrieNode') -> str:
"""序列化trie"""
<|body_0|>
def deserialize(self, data: str) -> 'TrieNode':
"""反序列化trie"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def serialize(self, root: 'TrieNode') -> str:
"""序列化trie"""
def dfs(cur: 'TrieNode') -> str:
res = []
for key, next in cur.children.items():
res.append(key)
res.append(dfs(next))
return f"<{''.join(res)}>"
re... | the_stack_v2_python_sparse | 23_设计类/lintcode系统设计/527.序列化Trie.py | 981377660LMT/algorithm-study | train | 225 | |
231b69d2a66db98b83efcba1bceeb76c15ed2f41 | [
"def traverse(root, tmp):\n if not root:\n tmp.append(float('inf'))\n return 0\n tmp.append(root.val)\n traverse(root.left, tmp)\n traverse(root.right, tmp)\ntmp1 = []\ntmp2 = []\ntraverse(p, tmp1)\ntraverse(q, tmp2)\nif tmp1 == tmp2:\n return True\nelse:\n return False",
"if not p... | <|body_start_0|>
def traverse(root, tmp):
if not root:
tmp.append(float('inf'))
return 0
tmp.append(root.val)
traverse(root.left, tmp)
traverse(root.right, tmp)
tmp1 = []
tmp2 = []
traverse(p, tmp1)
t... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isSameTree(self, p, q):
""":type p: TreeNode :type q: TreeNode :rtype: bool"""
<|body_0|>
def isSameTree0(self, p, q):
""":type p: TreeNode :type q: TreeNode :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def traverse(roo... | stack_v2_sparse_classes_36k_train_015310 | 1,125 | no_license | [
{
"docstring": ":type p: TreeNode :type q: TreeNode :rtype: bool",
"name": "isSameTree",
"signature": "def isSameTree(self, p, q)"
},
{
"docstring": ":type p: TreeNode :type q: TreeNode :rtype: bool",
"name": "isSameTree0",
"signature": "def isSameTree0(self, p, q)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012247 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSameTree(self, p, q): :type p: TreeNode :type q: TreeNode :rtype: bool
- def isSameTree0(self, p, q): :type p: TreeNode :type q: TreeNode :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSameTree(self, p, q): :type p: TreeNode :type q: TreeNode :rtype: bool
- def isSameTree0(self, p, q): :type p: TreeNode :type q: TreeNode :rtype: bool
<|skeleton|>
class S... | 9e49b2c6003b957276737005d4aaac276b44d251 | <|skeleton|>
class Solution:
def isSameTree(self, p, q):
""":type p: TreeNode :type q: TreeNode :rtype: bool"""
<|body_0|>
def isSameTree0(self, p, q):
""":type p: TreeNode :type q: TreeNode :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isSameTree(self, p, q):
""":type p: TreeNode :type q: TreeNode :rtype: bool"""
def traverse(root, tmp):
if not root:
tmp.append(float('inf'))
return 0
tmp.append(root.val)
traverse(root.left, tmp)
tra... | the_stack_v2_python_sparse | PythonCode/src/0100_Same_Tree.py | oneyuan/CodeforFun | train | 0 | |
c97c41cbe15696a5bc7864d1b61b8adaadb73416 | [
"img = Image.fromarray(np.zeros((750, 800, 3), dtype=np.uint8) + 255)\nself.new_data = []\nfor i in range(len(real_data)):\n self.new_data.append([int(real_data[i][0]), int(800 - real_data[i][1] * 2) - 200, i])\nDC = Image.fromarray(cv.resize(cv.imread('icon/DC.png'), (45, 30)))\nsensor = Image.fromarray(cv.resi... | <|body_start_0|>
img = Image.fromarray(np.zeros((750, 800, 3), dtype=np.uint8) + 255)
self.new_data = []
for i in range(len(real_data)):
self.new_data.append([int(real_data[i][0]), int(800 - real_data[i][1] * 2) - 200, i])
DC = Image.fromarray(cv.resize(cv.imread('icon/DC.png... | visulize | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class visulize:
def base_map(self, real_data, name):
"""可视化基本地图,将原来的点放大两倍,左下角为坐标原点,左->右为x轴,右->左为y轴 将原来的点除以5,放缩一下基本像素点为5KM"""
<|body_0|>
def arrow_map(self, base_map, path, info):
"""TODO:后面增加到4辆车,应该会有4个路径,格式应该在path里面放四个列表"""
<|body_1|>
<|end_skeleton|>
<|body_sta... | stack_v2_sparse_classes_36k_train_015311 | 3,356 | no_license | [
{
"docstring": "可视化基本地图,将原来的点放大两倍,左下角为坐标原点,左->右为x轴,右->左为y轴 将原来的点除以5,放缩一下基本像素点为5KM",
"name": "base_map",
"signature": "def base_map(self, real_data, name)"
},
{
"docstring": "TODO:后面增加到4辆车,应该会有4个路径,格式应该在path里面放四个列表",
"name": "arrow_map",
"signature": "def arrow_map(self, base_map, path, i... | 2 | stack_v2_sparse_classes_30k_train_017302 | Implement the Python class `visulize` described below.
Class description:
Implement the visulize class.
Method signatures and docstrings:
- def base_map(self, real_data, name): 可视化基本地图,将原来的点放大两倍,左下角为坐标原点,左->右为x轴,右->左为y轴 将原来的点除以5,放缩一下基本像素点为5KM
- def arrow_map(self, base_map, path, info): TODO:后面增加到4辆车,应该会有4个路径,格式应该在pa... | Implement the Python class `visulize` described below.
Class description:
Implement the visulize class.
Method signatures and docstrings:
- def base_map(self, real_data, name): 可视化基本地图,将原来的点放大两倍,左下角为坐标原点,左->右为x轴,右->左为y轴 将原来的点除以5,放缩一下基本像素点为5KM
- def arrow_map(self, base_map, path, info): TODO:后面增加到4辆车,应该会有4个路径,格式应该在pa... | 98d16d528e6eccee2ba4beb91ceca3eb61ca6d52 | <|skeleton|>
class visulize:
def base_map(self, real_data, name):
"""可视化基本地图,将原来的点放大两倍,左下角为坐标原点,左->右为x轴,右->左为y轴 将原来的点除以5,放缩一下基本像素点为5KM"""
<|body_0|>
def arrow_map(self, base_map, path, info):
"""TODO:后面增加到4辆车,应该会有4个路径,格式应该在path里面放四个列表"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class visulize:
def base_map(self, real_data, name):
"""可视化基本地图,将原来的点放大两倍,左下角为坐标原点,左->右为x轴,右->左为y轴 将原来的点除以5,放缩一下基本像素点为5KM"""
img = Image.fromarray(np.zeros((750, 800, 3), dtype=np.uint8) + 255)
self.new_data = []
for i in range(len(real_data)):
self.new_data.append([int(r... | the_stack_v2_python_sparse | Model_2/libs/visulize.py | bevarb/XIAO-SAI | train | 0 | |
e87a8683d4300f34018575e8d42abaf0fb780b5c | [
"self._model = model\nself.path = path\nself.external_data_path = external_data_path\nself.size_threshold = size_threshold\nself.all_tensors_to_one_file = all_tensors_to_one_file",
"model, _ = util.invoke_if_callable(self._model)\nG_LOGGER.info(f'Saving ONNX model to: {self.path}')\nif self.external_data_path is ... | <|body_start_0|>
self._model = model
self.path = path
self.external_data_path = external_data_path
self.size_threshold = size_threshold
self.all_tensors_to_one_file = all_tensors_to_one_file
<|end_body_0|>
<|body_start_1|>
model, _ = util.invoke_if_callable(self._model)
... | Functor that saves an ONNX model to the specified path. | SaveOnnx | [
"Apache-2.0",
"BSD-3-Clause",
"MIT",
"ISC",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SaveOnnx:
"""Functor that saves an ONNX model to the specified path."""
def __init__(self, model, path, external_data_path=None, size_threshold=None, all_tensors_to_one_file=None):
"""Saves an ONNX model to the specified path. Args: model (Union[onnx.ModelProto, Callable() -> onnx.Mo... | stack_v2_sparse_classes_36k_train_015312 | 37,448 | permissive | [
{
"docstring": "Saves an ONNX model to the specified path. Args: model (Union[onnx.ModelProto, Callable() -> onnx.ModelProto]): An ONNX model or a callable that returns one. path (str): Path at which to write the ONNX model. external_data_path (str): Path to save external data. This is always a relative path; e... | 2 | stack_v2_sparse_classes_30k_train_014934 | Implement the Python class `SaveOnnx` described below.
Class description:
Functor that saves an ONNX model to the specified path.
Method signatures and docstrings:
- def __init__(self, model, path, external_data_path=None, size_threshold=None, all_tensors_to_one_file=None): Saves an ONNX model to the specified path. ... | Implement the Python class `SaveOnnx` described below.
Class description:
Functor that saves an ONNX model to the specified path.
Method signatures and docstrings:
- def __init__(self, model, path, external_data_path=None, size_threshold=None, all_tensors_to_one_file=None): Saves an ONNX model to the specified path. ... | a167852705d74bcc619d8fad0af4b9e4d84472fc | <|skeleton|>
class SaveOnnx:
"""Functor that saves an ONNX model to the specified path."""
def __init__(self, model, path, external_data_path=None, size_threshold=None, all_tensors_to_one_file=None):
"""Saves an ONNX model to the specified path. Args: model (Union[onnx.ModelProto, Callable() -> onnx.Mo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SaveOnnx:
"""Functor that saves an ONNX model to the specified path."""
def __init__(self, model, path, external_data_path=None, size_threshold=None, all_tensors_to_one_file=None):
"""Saves an ONNX model to the specified path. Args: model (Union[onnx.ModelProto, Callable() -> onnx.ModelProto]): A... | the_stack_v2_python_sparse | tools/Polygraphy/polygraphy/backend/onnx/loader.py | NVIDIA/TensorRT | train | 8,026 |
42305a3a50c3af039dce76843791a38f88c54719 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')"
] | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Proto file describing the FeedMapping service. Service to manage feed mappings. | FeedMappingServiceServicer | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeedMappingServiceServicer:
"""Proto file describing the FeedMapping service. Service to manage feed mappings."""
def GetFeedMapping(self, request, context):
"""Returns the requested feed mapping in full detail."""
<|body_0|>
def MutateFeedMappings(self, request, context... | stack_v2_sparse_classes_36k_train_015313 | 3,358 | permissive | [
{
"docstring": "Returns the requested feed mapping in full detail.",
"name": "GetFeedMapping",
"signature": "def GetFeedMapping(self, request, context)"
},
{
"docstring": "Creates or removes feed mappings. Operation statuses are returned.",
"name": "MutateFeedMappings",
"signature": "def... | 2 | stack_v2_sparse_classes_30k_train_014689 | Implement the Python class `FeedMappingServiceServicer` described below.
Class description:
Proto file describing the FeedMapping service. Service to manage feed mappings.
Method signatures and docstrings:
- def GetFeedMapping(self, request, context): Returns the requested feed mapping in full detail.
- def MutateFee... | Implement the Python class `FeedMappingServiceServicer` described below.
Class description:
Proto file describing the FeedMapping service. Service to manage feed mappings.
Method signatures and docstrings:
- def GetFeedMapping(self, request, context): Returns the requested feed mapping in full detail.
- def MutateFee... | 0fc8a7dbf31d9e8e2a4364df93bec5f6b7edd50a | <|skeleton|>
class FeedMappingServiceServicer:
"""Proto file describing the FeedMapping service. Service to manage feed mappings."""
def GetFeedMapping(self, request, context):
"""Returns the requested feed mapping in full detail."""
<|body_0|>
def MutateFeedMappings(self, request, context... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FeedMappingServiceServicer:
"""Proto file describing the FeedMapping service. Service to manage feed mappings."""
def GetFeedMapping(self, request, context):
"""Returns the requested feed mapping in full detail."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_detail... | the_stack_v2_python_sparse | google/ads/google_ads/v2/proto/services/feed_mapping_service_pb2_grpc.py | juanmacugat/google-ads-python | train | 1 |
df1d79e837958e3fdd1db3db4202e775a9a5fabf | [
"super(CWS, self).__init__()\nif model_path is None:\n model_path = model_urls['cws']\nself.load(model_path, device)",
"if not hasattr(self, 'pipeline'):\n raise ValueError('You have to load model first.')\nsentence_list = []\nif isinstance(content, str):\n sentence_list.append(content)\nelif isinstance(... | <|body_start_0|>
super(CWS, self).__init__()
if model_path is None:
model_path = model_urls['cws']
self.load(model_path, device)
<|end_body_0|>
<|body_start_1|>
if not hasattr(self, 'pipeline'):
raise ValueError('You have to load model first.')
sentence_l... | CWS | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CWS:
def __init__(self, model_path=None, device='cpu'):
"""中文分词高级接口。 :param model_path: 当model_path为None,使用默认位置的model。如果默认位置不存在,则自动下载模型 :param device: str,可以为'cpu', 'cuda'或'cuda:0'等。会将模型load到相应device进行推断。"""
<|body_0|>
def predict(self, content):
"""分词接口。 :param cont... | stack_v2_sparse_classes_36k_train_015314 | 11,931 | permissive | [
{
"docstring": "中文分词高级接口。 :param model_path: 当model_path为None,使用默认位置的model。如果默认位置不存在,则自动下载模型 :param device: str,可以为'cpu', 'cuda'或'cuda:0'等。会将模型load到相应device进行推断。",
"name": "__init__",
"signature": "def __init__(self, model_path=None, device='cpu')"
},
{
"docstring": "分词接口。 :param content: str或Li... | 3 | stack_v2_sparse_classes_30k_train_020531 | Implement the Python class `CWS` described below.
Class description:
Implement the CWS class.
Method signatures and docstrings:
- def __init__(self, model_path=None, device='cpu'): 中文分词高级接口。 :param model_path: 当model_path为None,使用默认位置的model。如果默认位置不存在,则自动下载模型 :param device: str,可以为'cpu', 'cuda'或'cuda:0'等。会将模型load到相应dev... | Implement the Python class `CWS` described below.
Class description:
Implement the CWS class.
Method signatures and docstrings:
- def __init__(self, model_path=None, device='cpu'): 中文分词高级接口。 :param model_path: 当model_path为None,使用默认位置的model。如果默认位置不存在,则自动下载模型 :param device: str,可以为'cpu', 'cuda'或'cuda:0'等。会将模型load到相应dev... | 209e0aec44eb100ad5c30c75b84d28711e2968f5 | <|skeleton|>
class CWS:
def __init__(self, model_path=None, device='cpu'):
"""中文分词高级接口。 :param model_path: 当model_path为None,使用默认位置的model。如果默认位置不存在,则自动下载模型 :param device: str,可以为'cpu', 'cuda'或'cuda:0'等。会将模型load到相应device进行推断。"""
<|body_0|>
def predict(self, content):
"""分词接口。 :param cont... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CWS:
def __init__(self, model_path=None, device='cpu'):
"""中文分词高级接口。 :param model_path: 当model_path为None,使用默认位置的model。如果默认位置不存在,则自动下载模型 :param device: str,可以为'cpu', 'cuda'或'cuda:0'等。会将模型load到相应device进行推断。"""
super(CWS, self).__init__()
if model_path is None:
model_path = mo... | the_stack_v2_python_sparse | fastNLP/api/api.py | huziye/fastNLP_fork | train | 4 | |
d52725004c81e07c897824281529fb6dc8978fd4 | [
"self.model = model\nself.data = data\nself.qgrid_sz = self.model.qgrid_size\nself.dn = self.model.dn\nself._gfa = None\nself.npeaks = 5\nself._peak_values = None\nself._peak_indices = None",
"values = self.data * self.model.filter\nSq = np.zeros((self.qgrid_sz, self.qgrid_sz, self.qgrid_sz))\nfor i in range(len(... | <|body_start_0|>
self.model = model
self.data = data
self.qgrid_sz = self.model.qgrid_size
self.dn = self.model.dn
self._gfa = None
self.npeaks = 5
self._peak_values = None
self._peak_indices = None
<|end_body_0|>
<|body_start_1|>
values = self.da... | DiffusionSpectrumFit | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DiffusionSpectrumFit:
def __init__(self, model, data):
"""Calculates PDF and ODF and other properties for a single voxel Parameters ---------- model : object, DiffusionSpectrumModel data : 1d ndarray, signal values"""
<|body_0|>
def pdf(self, normalized=True):
"""App... | stack_v2_sparse_classes_36k_train_015315 | 21,859 | permissive | [
{
"docstring": "Calculates PDF and ODF and other properties for a single voxel Parameters ---------- model : object, DiffusionSpectrumModel data : 1d ndarray, signal values",
"name": "__init__",
"signature": "def __init__(self, model, data)"
},
{
"docstring": "Applies the 3D FFT in the q-space g... | 6 | null | Implement the Python class `DiffusionSpectrumFit` described below.
Class description:
Implement the DiffusionSpectrumFit class.
Method signatures and docstrings:
- def __init__(self, model, data): Calculates PDF and ODF and other properties for a single voxel Parameters ---------- model : object, DiffusionSpectrumMod... | Implement the Python class `DiffusionSpectrumFit` described below.
Class description:
Implement the DiffusionSpectrumFit class.
Method signatures and docstrings:
- def __init__(self, model, data): Calculates PDF and ODF and other properties for a single voxel Parameters ---------- model : object, DiffusionSpectrumMod... | 3c3acc55de8ba741e673063378e6cbaf10b64c7a | <|skeleton|>
class DiffusionSpectrumFit:
def __init__(self, model, data):
"""Calculates PDF and ODF and other properties for a single voxel Parameters ---------- model : object, DiffusionSpectrumModel data : 1d ndarray, signal values"""
<|body_0|>
def pdf(self, normalized=True):
"""App... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DiffusionSpectrumFit:
def __init__(self, model, data):
"""Calculates PDF and ODF and other properties for a single voxel Parameters ---------- model : object, DiffusionSpectrumModel data : 1d ndarray, signal values"""
self.model = model
self.data = data
self.qgrid_sz = self.mod... | the_stack_v2_python_sparse | env/lib/python3.6/site-packages/dipy/reconst/dsi.py | Raniac/NEURO-LEARN | train | 9 | |
b6a22bbc93ed7230e59269637a75b0a0a3282fae | [
"if mode == Mode.PLAYER:\n return True\nreturn False",
"if mode == Mode.RANDOM_AI or mode == Mode.AI_WITHOUT_FLAGS or mode == Mode.AI_WITH_FLAGS or (mode == Mode.AI_WITH_FLAGS2):\n return True\nreturn False"
] | <|body_start_0|>
if mode == Mode.PLAYER:
return True
return False
<|end_body_0|>
<|body_start_1|>
if mode == Mode.RANDOM_AI or mode == Mode.AI_WITHOUT_FLAGS or mode == Mode.AI_WITH_FLAGS or (mode == Mode.AI_WITH_FLAGS2):
return True
return False
<|end_body_1|>
| Mode | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Mode:
def is_player_mode(cls, mode):
"""Allow to know if a mode is a player mode or not. :mode: The mode. :return: True if the mode is a player mode, False otherwise."""
<|body_0|>
def is_ai_mode(cls, mode):
"""Allow to know if a mode is an artificial intelligence mo... | stack_v2_sparse_classes_36k_train_015316 | 5,674 | no_license | [
{
"docstring": "Allow to know if a mode is a player mode or not. :mode: The mode. :return: True if the mode is a player mode, False otherwise.",
"name": "is_player_mode",
"signature": "def is_player_mode(cls, mode)"
},
{
"docstring": "Allow to know if a mode is an artificial intelligence mode or... | 2 | stack_v2_sparse_classes_30k_test_000729 | Implement the Python class `Mode` described below.
Class description:
Implement the Mode class.
Method signatures and docstrings:
- def is_player_mode(cls, mode): Allow to know if a mode is a player mode or not. :mode: The mode. :return: True if the mode is a player mode, False otherwise.
- def is_ai_mode(cls, mode):... | Implement the Python class `Mode` described below.
Class description:
Implement the Mode class.
Method signatures and docstrings:
- def is_player_mode(cls, mode): Allow to know if a mode is a player mode or not. :mode: The mode. :return: True if the mode is a player mode, False otherwise.
- def is_ai_mode(cls, mode):... | e4601fbdd9f7cfdef6774f26c2850ec8cf3c562e | <|skeleton|>
class Mode:
def is_player_mode(cls, mode):
"""Allow to know if a mode is a player mode or not. :mode: The mode. :return: True if the mode is a player mode, False otherwise."""
<|body_0|>
def is_ai_mode(cls, mode):
"""Allow to know if a mode is an artificial intelligence mo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Mode:
def is_player_mode(cls, mode):
"""Allow to know if a mode is a player mode or not. :mode: The mode. :return: True if the mode is a player mode, False otherwise."""
if mode == Mode.PLAYER:
return True
return False
def is_ai_mode(cls, mode):
"""Allow to kno... | the_stack_v2_python_sparse | source/main.py | roundsace/Minesweeper_deep_learning | train | 0 | |
62d2f7969ba78e521bfaf16d824cbe7ef3aaf82c | [
"remote_conn_pre: SSHClient\nif not self.use_keys:\n remote_conn_pre = SSHClient_noauth()\nelse:\n remote_conn_pre = SSHClient()\nif self.system_host_keys:\n remote_conn_pre.load_system_host_keys()\nif self.alt_host_keys and path.isfile(self.alt_key_file):\n remote_conn_pre.load_host_keys(self.alt_key_f... | <|body_start_0|>
remote_conn_pre: SSHClient
if not self.use_keys:
remote_conn_pre = SSHClient_noauth()
else:
remote_conn_pre = SSHClient()
if self.system_host_keys:
remote_conn_pre.load_system_host_keys()
if self.alt_host_keys and path.isfile(s... | Dell PowerConnect Driver. To make it work, we have to override the SSHClient _auth method. If we use login/password, the ssh server use the (none) auth mechanism. | DellPowerConnectSSH | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DellPowerConnectSSH:
"""Dell PowerConnect Driver. To make it work, we have to override the SSHClient _auth method. If we use login/password, the ssh server use the (none) auth mechanism."""
def _build_ssh_client(self) -> SSHClient:
"""Prepare for Paramiko SSH connection. See base_con... | stack_v2_sparse_classes_36k_train_015317 | 4,030 | permissive | [
{
"docstring": "Prepare for Paramiko SSH connection. See base_connection.py file for any updates.",
"name": "_build_ssh_client",
"signature": "def _build_ssh_client(self) -> SSHClient"
},
{
"docstring": "Powerconnect presents with the following on login User Name: Password: ****",
"name": "s... | 2 | null | Implement the Python class `DellPowerConnectSSH` described below.
Class description:
Dell PowerConnect Driver. To make it work, we have to override the SSHClient _auth method. If we use login/password, the ssh server use the (none) auth mechanism.
Method signatures and docstrings:
- def _build_ssh_client(self) -> SSH... | Implement the Python class `DellPowerConnectSSH` described below.
Class description:
Dell PowerConnect Driver. To make it work, we have to override the SSHClient _auth method. If we use login/password, the ssh server use the (none) auth mechanism.
Method signatures and docstrings:
- def _build_ssh_client(self) -> SSH... | 2e56b40ec639da130471c59dd1f3c93983471e41 | <|skeleton|>
class DellPowerConnectSSH:
"""Dell PowerConnect Driver. To make it work, we have to override the SSHClient _auth method. If we use login/password, the ssh server use the (none) auth mechanism."""
def _build_ssh_client(self) -> SSHClient:
"""Prepare for Paramiko SSH connection. See base_con... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DellPowerConnectSSH:
"""Dell PowerConnect Driver. To make it work, we have to override the SSHClient _auth method. If we use login/password, the ssh server use the (none) auth mechanism."""
def _build_ssh_client(self) -> SSHClient:
"""Prepare for Paramiko SSH connection. See base_connection.py fi... | the_stack_v2_python_sparse | netmiko/dell/dell_powerconnect.py | ktbyers/netmiko | train | 3,397 |
fe7bebdc215b8061924b5c3bdbab7754ce924636 | [
"super().__init__(term=AuthenticationProofPurpose.term, date=date, max_timestamp_delta=max_timestamp_delta)\nself.challenge = challenge\nself.domain = domain",
"try:\n if proof.get('challenge') != self.challenge:\n raise LinkedDataProofException(f\"The challenge is not as expected; challenge={proof.get(... | <|body_start_0|>
super().__init__(term=AuthenticationProofPurpose.term, date=date, max_timestamp_delta=max_timestamp_delta)
self.challenge = challenge
self.domain = domain
<|end_body_0|>
<|body_start_1|>
try:
if proof.get('challenge') != self.challenge:
raise... | Authentication proof purpose. | AuthenticationProofPurpose | [
"LicenseRef-scancode-dco-1.1",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuthenticationProofPurpose:
"""Authentication proof purpose."""
def __init__(self, *, challenge: str, domain: str=None, date: datetime=None, max_timestamp_delta: timedelta=None):
"""Initialize new AuthenticationProofPurpose instance."""
<|body_0|>
def validate(self, *, p... | stack_v2_sparse_classes_36k_train_015318 | 2,805 | permissive | [
{
"docstring": "Initialize new AuthenticationProofPurpose instance.",
"name": "__init__",
"signature": "def __init__(self, *, challenge: str, domain: str=None, date: datetime=None, max_timestamp_delta: timedelta=None)"
},
{
"docstring": "Validate whether challenge and domain are valid.",
"na... | 4 | null | Implement the Python class `AuthenticationProofPurpose` described below.
Class description:
Authentication proof purpose.
Method signatures and docstrings:
- def __init__(self, *, challenge: str, domain: str=None, date: datetime=None, max_timestamp_delta: timedelta=None): Initialize new AuthenticationProofPurpose ins... | Implement the Python class `AuthenticationProofPurpose` described below.
Class description:
Authentication proof purpose.
Method signatures and docstrings:
- def __init__(self, *, challenge: str, domain: str=None, date: datetime=None, max_timestamp_delta: timedelta=None): Initialize new AuthenticationProofPurpose ins... | 39cac36d8937ce84a9307ce100aaefb8bc05ec04 | <|skeleton|>
class AuthenticationProofPurpose:
"""Authentication proof purpose."""
def __init__(self, *, challenge: str, domain: str=None, date: datetime=None, max_timestamp_delta: timedelta=None):
"""Initialize new AuthenticationProofPurpose instance."""
<|body_0|>
def validate(self, *, p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AuthenticationProofPurpose:
"""Authentication proof purpose."""
def __init__(self, *, challenge: str, domain: str=None, date: datetime=None, max_timestamp_delta: timedelta=None):
"""Initialize new AuthenticationProofPurpose instance."""
super().__init__(term=AuthenticationProofPurpose.ter... | the_stack_v2_python_sparse | aries_cloudagent/vc/ld_proofs/purposes/authentication_proof_purpose.py | hyperledger/aries-cloudagent-python | train | 370 |
f0364dc0b2b690913cdd4e02c100e26e3b54cb4f | [
"super().__init__(env)\nself.num_envs = getattr(env, 'num_envs', 1)\nself.t0 = time.perf_counter()\nself.episode_count = 0\nself.episode_returns: Optional[np.ndarray] = None\nself.episode_lengths: Optional[np.ndarray] = None\nself.return_queue = deque(maxlen=deque_size)\nself.length_queue = deque(maxlen=deque_size)... | <|body_start_0|>
super().__init__(env)
self.num_envs = getattr(env, 'num_envs', 1)
self.t0 = time.perf_counter()
self.episode_count = 0
self.episode_returns: Optional[np.ndarray] = None
self.episode_lengths: Optional[np.ndarray] = None
self.return_queue = deque(ma... | This wrapper will keep track of cumulative rewards and episode lengths. At the end of an episode, the statistics of the episode will be added to ``info`` using the key ``episode``. If using a vectorized environment also the key ``_episode`` is used which indicates whether the env at the respective index has the episode... | RecordEpisodeStatistics | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RecordEpisodeStatistics:
"""This wrapper will keep track of cumulative rewards and episode lengths. At the end of an episode, the statistics of the episode will be added to ``info`` using the key ``episode``. If using a vectorized environment also the key ``_episode`` is used which indicates whet... | stack_v2_sparse_classes_36k_train_015319 | 5,650 | permissive | [
{
"docstring": "This wrapper will keep track of cumulative rewards and episode lengths. Args: env (Env): The environment to apply the wrapper deque_size: The size of the buffers :attr:`return_queue` and :attr:`length_queue`",
"name": "__init__",
"signature": "def __init__(self, env: gym.Env, deque_size:... | 3 | stack_v2_sparse_classes_30k_test_000637 | Implement the Python class `RecordEpisodeStatistics` described below.
Class description:
This wrapper will keep track of cumulative rewards and episode lengths. At the end of an episode, the statistics of the episode will be added to ``info`` using the key ``episode``. If using a vectorized environment also the key ``... | Implement the Python class `RecordEpisodeStatistics` described below.
Class description:
This wrapper will keep track of cumulative rewards and episode lengths. At the end of an episode, the statistics of the episode will be added to ``info`` using the key ``episode``. If using a vectorized environment also the key ``... | 53d784eafed28d31ec41c36ebd9eee14b0dc6d41 | <|skeleton|>
class RecordEpisodeStatistics:
"""This wrapper will keep track of cumulative rewards and episode lengths. At the end of an episode, the statistics of the episode will be added to ``info`` using the key ``episode``. If using a vectorized environment also the key ``_episode`` is used which indicates whet... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RecordEpisodeStatistics:
"""This wrapper will keep track of cumulative rewards and episode lengths. At the end of an episode, the statistics of the episode will be added to ``info`` using the key ``episode``. If using a vectorized environment also the key ``_episode`` is used which indicates whether the env a... | the_stack_v2_python_sparse | gym/wrappers/record_episode_statistics.py | thomascherickal/gym | train | 2 |
1ef333f8b0c9749f64f2b17ccfcd2fa3e3255666 | [
"object.__setattr__(self, 'flag_value_map', self._create_flag_value_map(flags_in_scope))\nobject.__setattr__(self, 'namespace', namespace)\nobject.__setattr__(self, 'passthrough_args', passthrough_args)\nobject.__setattr__(self, 'allow_unknown_flags', allow_unknown_flags)",
"flag_value_map: DefaultDict[str, list[... | <|body_start_0|>
object.__setattr__(self, 'flag_value_map', self._create_flag_value_map(flags_in_scope))
object.__setattr__(self, 'namespace', namespace)
object.__setattr__(self, 'passthrough_args', passthrough_args)
object.__setattr__(self, 'allow_unknown_flags', allow_unknown_flags)
<|... | ParseArgsRequest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParseArgsRequest:
def __init__(self, flags_in_scope: Iterable[str], namespace: OptionValueContainerBuilder, passthrough_args: list[str], allow_unknown_flags: bool) -> None:
""":param flags_in_scope: Iterable of arg strings to parse into flag values. :param namespace: The object to regist... | stack_v2_sparse_classes_36k_train_015320 | 32,099 | permissive | [
{
"docstring": ":param flags_in_scope: Iterable of arg strings to parse into flag values. :param namespace: The object to register the flag values on",
"name": "__init__",
"signature": "def __init__(self, flags_in_scope: Iterable[str], namespace: OptionValueContainerBuilder, passthrough_args: list[str],... | 2 | stack_v2_sparse_classes_30k_train_006587 | Implement the Python class `ParseArgsRequest` described below.
Class description:
Implement the ParseArgsRequest class.
Method signatures and docstrings:
- def __init__(self, flags_in_scope: Iterable[str], namespace: OptionValueContainerBuilder, passthrough_args: list[str], allow_unknown_flags: bool) -> None: :param ... | Implement the Python class `ParseArgsRequest` described below.
Class description:
Implement the ParseArgsRequest class.
Method signatures and docstrings:
- def __init__(self, flags_in_scope: Iterable[str], namespace: OptionValueContainerBuilder, passthrough_args: list[str], allow_unknown_flags: bool) -> None: :param ... | 98cbda8545f0d58c586ed2daa76fefd729d5e0d5 | <|skeleton|>
class ParseArgsRequest:
def __init__(self, flags_in_scope: Iterable[str], namespace: OptionValueContainerBuilder, passthrough_args: list[str], allow_unknown_flags: bool) -> None:
""":param flags_in_scope: Iterable of arg strings to parse into flag values. :param namespace: The object to regist... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ParseArgsRequest:
def __init__(self, flags_in_scope: Iterable[str], namespace: OptionValueContainerBuilder, passthrough_args: list[str], allow_unknown_flags: bool) -> None:
""":param flags_in_scope: Iterable of arg strings to parse into flag values. :param namespace: The object to register the flag va... | the_stack_v2_python_sparse | src/python/pants/option/parser.py | pantsbuild/pants | train | 2,708 | |
a480ad464aea30988c8a51549a3045fd0776d2b1 | [
"starts = [0] * len(arrays)\nwhile True:\n batches = []\n for i, array in enumerate(arrays):\n start = starts[i]\n stop = start + batch_size\n diff = stop - array.shape[0]\n if diff <= 0:\n batch = array[start:stop]\n starts[i] += batch_size\n else:\n ... | <|body_start_0|>
starts = [0] * len(arrays)
while True:
batches = []
for i, array in enumerate(arrays):
start = starts[i]
stop = start + batch_size
diff = stop - array.shape[0]
if diff <= 0:
batch... | This class has no constructor. All its methods are static. It contains functions that arise in other, more specific ModelMaker classes. | ModelMaker | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModelMaker:
"""This class has no constructor. All its methods are static. It contains functions that arise in other, more specific ModelMaker classes."""
def batch_gen(arrays, batch_size):
"""(This generator function was copied from Edward Tutorials) If arrays =[array0, array1, ...],... | stack_v2_sparse_classes_36k_train_015321 | 2,607 | permissive | [
{
"docstring": "(This generator function was copied from Edward Tutorials) If arrays =[array0, array1, ...], it returns a list of batches, batches = [ batch0, batch1, ...], one batch for each array in `arrays'. batch0 is a subarray of array0 with dimension along axis=0 equal to batch_size. Parameters ----------... | 2 | null | Implement the Python class `ModelMaker` described below.
Class description:
This class has no constructor. All its methods are static. It contains functions that arise in other, more specific ModelMaker classes.
Method signatures and docstrings:
- def batch_gen(arrays, batch_size): (This generator function was copied... | Implement the Python class `ModelMaker` described below.
Class description:
This class has no constructor. All its methods are static. It contains functions that arise in other, more specific ModelMaker classes.
Method signatures and docstrings:
- def batch_gen(arrays, batch_size): (This generator function was copied... | 5b4a3055ea14c2ee9c80c339f759fe2b9c8c51e2 | <|skeleton|>
class ModelMaker:
"""This class has no constructor. All its methods are static. It contains functions that arise in other, more specific ModelMaker classes."""
def batch_gen(arrays, batch_size):
"""(This generator function was copied from Edward Tutorials) If arrays =[array0, array1, ...],... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ModelMaker:
"""This class has no constructor. All its methods are static. It contains functions that arise in other, more specific ModelMaker classes."""
def batch_gen(arrays, batch_size):
"""(This generator function was copied from Edward Tutorials) If arrays =[array0, array1, ...], it returns a... | the_stack_v2_python_sparse | jupyter-notebooks/inference_via_ext_software/ModelMaker.py | artiste-qb-net/quantum-fog | train | 95 |
8b5dd1b0248264c7893ba4650b12206b71422863 | [
"if not nums:\n return 0\ndp = [1] * len(nums)\nfor i in range(1, len(nums)):\n for j in range(i):\n if nums[j] < nums[i]:\n dp[i] = max(dp[i], dp[j] + 1)\nreturn max(dp)",
"if not nums:\n return 0\nends = [nums[0]]\nr = 0\nfor i in range(1, len(nums)):\n left = 0\n right = len(en... | <|body_start_0|>
if not nums:
return 0
dp = [1] * len(nums)
for i in range(1, len(nums)):
for j in range(i):
if nums[j] < nums[i]:
dp[i] = max(dp[i], dp[j] + 1)
return max(dp)
<|end_body_0|>
<|body_start_1|>
if not nums... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lengthOfLIS(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def lengthOfLIS2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not nums:
return 0
dp... | stack_v2_sparse_classes_36k_train_015322 | 2,631 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "lengthOfLIS",
"signature": "def lengthOfLIS(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "lengthOfLIS2",
"signature": "def lengthOfLIS2(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLIS(self, nums): :type nums: List[int] :rtype: int
- def lengthOfLIS2(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 lengthOfLIS(self, nums): :type nums: List[int] :rtype: int
- def lengthOfLIS2(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def lengthOfLI... | 604efd2c53c369fb262f42f7f7f31997ea4d029b | <|skeleton|>
class Solution:
def lengthOfLIS(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def lengthOfLIS2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def lengthOfLIS(self, nums):
""":type nums: List[int] :rtype: int"""
if not nums:
return 0
dp = [1] * len(nums)
for i in range(1, len(nums)):
for j in range(i):
if nums[j] < nums[i]:
dp[i] = max(dp[i], dp[j] ... | the_stack_v2_python_sparse | 300_Longest_Increasing_Subsequence.py | fxy1018/Leetcode | train | 1 | |
4a0521e733d7580ef3eba6519f3e26a369b68637 | [
"super().__init__(pooling_class, N, depth, laplacian_type, kernel_size, ratio)\nself.sequence_length = sequence_length\nself.encoder = EncoderTemporalConv(self.pooling_class.pooling, self.laps, self.sequence_length, self.kernel_size)\nself.decoder = Decoder(self.pooling_class.unpooling, self.laps, self.kernel_size)... | <|body_start_0|>
super().__init__(pooling_class, N, depth, laplacian_type, kernel_size, ratio)
self.sequence_length = sequence_length
self.encoder = EncoderTemporalConv(self.pooling_class.pooling, self.laps, self.sequence_length, self.kernel_size)
self.decoder = Decoder(self.pooling_clas... | Spherical GCNN Autoencoder with temporality by means of convolution over time. | SphericalUNetTemporalConv | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SphericalUNetTemporalConv:
"""Spherical GCNN Autoencoder with temporality by means of convolution over time."""
def __init__(self, pooling_class, N, depth, laplacian_type, sequence_length, kernel_size, ratio=1):
"""Initialization. Args: pooling_class (obj): One of three classes of po... | stack_v2_sparse_classes_36k_train_015323 | 41,403 | no_license | [
{
"docstring": "Initialization. Args: pooling_class (obj): One of three classes of pooling methods N (int): Number of pixels in the input image depth (int): The depth of the UNet, which is bounded by the N and the type of pooling sequence_length (int): The number of images used per sample kernel_size (int): che... | 2 | stack_v2_sparse_classes_30k_val_000089 | Implement the Python class `SphericalUNetTemporalConv` described below.
Class description:
Spherical GCNN Autoencoder with temporality by means of convolution over time.
Method signatures and docstrings:
- def __init__(self, pooling_class, N, depth, laplacian_type, sequence_length, kernel_size, ratio=1): Initializati... | Implement the Python class `SphericalUNetTemporalConv` described below.
Class description:
Spherical GCNN Autoencoder with temporality by means of convolution over time.
Method signatures and docstrings:
- def __init__(self, pooling_class, N, depth, laplacian_type, sequence_length, kernel_size, ratio=1): Initializati... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class SphericalUNetTemporalConv:
"""Spherical GCNN Autoencoder with temporality by means of convolution over time."""
def __init__(self, pooling_class, N, depth, laplacian_type, sequence_length, kernel_size, ratio=1):
"""Initialization. Args: pooling_class (obj): One of three classes of po... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SphericalUNetTemporalConv:
"""Spherical GCNN Autoencoder with temporality by means of convolution over time."""
def __init__(self, pooling_class, N, depth, laplacian_type, sequence_length, kernel_size, ratio=1):
"""Initialization. Args: pooling_class (obj): One of three classes of pooling methods... | the_stack_v2_python_sparse | generated/test_deepsphere_deepsphere_pytorch.py | jansel/pytorch-jit-paritybench | train | 35 |
5e94920ec3f7aece10243db2afd9ebc2db742f65 | [
"super(Resonator, self).__init__(*args, **kwargs)\nself.R_shunt = R_shunt\nself.frequency = frequency\nself.Q = Q\nself.Yokoya_X1 = Yokoya_X1\nself.Yokoya_X2 = Yokoya_X2\nself.Yokoya_Y1 = Yokoya_Y1\nself.Yokoya_Y2 = Yokoya_Y2\nself.switch_Z = switch_Z\nself.n_turns_wake = n_turns_wake",
"wake_kicks = []\nif self.... | <|body_start_0|>
super(Resonator, self).__init__(*args, **kwargs)
self.R_shunt = R_shunt
self.frequency = frequency
self.Q = Q
self.Yokoya_X1 = Yokoya_X1
self.Yokoya_X2 = Yokoya_X2
self.Yokoya_Y1 = Yokoya_Y1
self.Yokoya_Y2 = Yokoya_Y2
self.switch_Z... | Class to describe the wake functions originating from a resonator impedance. Alex Chao's resonator model (Eq. 2.82) is used as well as the definitions from HEADTAIL. | Resonator | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Resonator:
"""Class to describe the wake functions originating from a resonator impedance. Alex Chao's resonator model (Eq. 2.82) is used as well as the definitions from HEADTAIL."""
def __init__(self, R_shunt, frequency, Q, Yokoya_X1, Yokoya_Y1, Yokoya_X2, Yokoya_Y2, switch_Z, n_turns_wake=... | stack_v2_sparse_classes_36k_train_015324 | 28,906 | permissive | [
{
"docstring": "General constructor to create a Resonator WakeSource object describing the wake functions of a resonator impedance. Alex Chao's resonator model (Eq. 2.82) is used as well as definitions from HEADTAIL. Note that it is no longer allowed to pass a LIST of parameters to generate a number of resonato... | 4 | null | Implement the Python class `Resonator` described below.
Class description:
Class to describe the wake functions originating from a resonator impedance. Alex Chao's resonator model (Eq. 2.82) is used as well as the definitions from HEADTAIL.
Method signatures and docstrings:
- def __init__(self, R_shunt, frequency, Q,... | Implement the Python class `Resonator` described below.
Class description:
Class to describe the wake functions originating from a resonator impedance. Alex Chao's resonator model (Eq. 2.82) is used as well as the definitions from HEADTAIL.
Method signatures and docstrings:
- def __init__(self, R_shunt, frequency, Q,... | b238bf3fbea02fcfaf8795ee54cc0e3134de477a | <|skeleton|>
class Resonator:
"""Class to describe the wake functions originating from a resonator impedance. Alex Chao's resonator model (Eq. 2.82) is used as well as the definitions from HEADTAIL."""
def __init__(self, R_shunt, frequency, Q, Yokoya_X1, Yokoya_Y1, Yokoya_X2, Yokoya_Y2, switch_Z, n_turns_wake=... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Resonator:
"""Class to describe the wake functions originating from a resonator impedance. Alex Chao's resonator model (Eq. 2.82) is used as well as the definitions from HEADTAIL."""
def __init__(self, R_shunt, frequency, Q, Yokoya_X1, Yokoya_Y1, Yokoya_X2, Yokoya_Y2, switch_Z, n_turns_wake=1, *args, **k... | the_stack_v2_python_sparse | PyHEADTAIL/impedances/wakes.py | PyCOMPLETE/PyHEADTAIL | train | 39 |
364df21493dde84b88935efddd496f4e0c7c3fc9 | [
"super().__init__(**kwargs)\nself.attention = nn.MultiheadAttention(embed_dim=input_dim, num_heads=num_attention_heads, dropout=dropout)\nself.feedforward = nn.Sequential(nn.Linear(input_dim, hidden_dim), nn.ReLU(), nn.Linear(hidden_dim, input_dim))\nself.dropout = nn.Dropout(dropout)\nself.layer_norm_1 = nn.LayerN... | <|body_start_0|>
super().__init__(**kwargs)
self.attention = nn.MultiheadAttention(embed_dim=input_dim, num_heads=num_attention_heads, dropout=dropout)
self.feedforward = nn.Sequential(nn.Linear(input_dim, hidden_dim), nn.ReLU(), nn.Linear(hidden_dim, input_dim))
self.dropout = nn.Dropou... | TransformerDecoderLayer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransformerDecoderLayer:
def __init__(self, input_dim: int, num_attention_heads: int, hidden_dim: int, dropout: float, **kwargs) -> None:
"""Simple Transformer-Decoder block (no encoder at all). Arguments --------- input_dim : int Embedding dimension of inputs. num_attention_heads : int ... | stack_v2_sparse_classes_36k_train_015325 | 4,788 | no_license | [
{
"docstring": "Simple Transformer-Decoder block (no encoder at all). Arguments --------- input_dim : int Embedding dimension of inputs. num_attention_heads : int Number of attention heads to use. hidden_dim : int Dimension to use for decoded vectors dropout : float Float between 0.0 and 1.0, probability of dro... | 2 | stack_v2_sparse_classes_30k_train_004482 | Implement the Python class `TransformerDecoderLayer` described below.
Class description:
Implement the TransformerDecoderLayer class.
Method signatures and docstrings:
- def __init__(self, input_dim: int, num_attention_heads: int, hidden_dim: int, dropout: float, **kwargs) -> None: Simple Transformer-Decoder block (n... | Implement the Python class `TransformerDecoderLayer` described below.
Class description:
Implement the TransformerDecoderLayer class.
Method signatures and docstrings:
- def __init__(self, input_dim: int, num_attention_heads: int, hidden_dim: int, dropout: float, **kwargs) -> None: Simple Transformer-Decoder block (n... | e2ea428dd57fac86592a0883c15b1d9befdf1137 | <|skeleton|>
class TransformerDecoderLayer:
def __init__(self, input_dim: int, num_attention_heads: int, hidden_dim: int, dropout: float, **kwargs) -> None:
"""Simple Transformer-Decoder block (no encoder at all). Arguments --------- input_dim : int Embedding dimension of inputs. num_attention_heads : int ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TransformerDecoderLayer:
def __init__(self, input_dim: int, num_attention_heads: int, hidden_dim: int, dropout: float, **kwargs) -> None:
"""Simple Transformer-Decoder block (no encoder at all). Arguments --------- input_dim : int Embedding dimension of inputs. num_attention_heads : int Number of atte... | the_stack_v2_python_sparse | src/count/decoders/transformer_decoder.py | mamonalsalihy/Model_Distillation | train | 3 | |
22a154805b4573d46b8ca66397ca40cd28d8ff32 | [
"if len(digits) == 0:\n digits = [1]\nelif digits[-1] == 9:\n print('aaa')\n print(digits[:-1])\n digits = self.plusOne(digits[:-1])\n print('xxxxx')\n print(digits)\n digits.append(0)\nelse:\n digits[-1] += 1\nreturn digits",
"n = len(digits)\nif digits[-1] != 9:\n digits[-1] += 1\nels... | <|body_start_0|>
if len(digits) == 0:
digits = [1]
elif digits[-1] == 9:
print('aaa')
print(digits[:-1])
digits = self.plusOne(digits[:-1])
print('xxxxx')
print(digits)
digits.append(0)
else:
digits[-... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def plusOne(self, digits):
""":type digits: List[int] :rtype: List[int]"""
<|body_0|>
def plusOne2(self, digits):
""":type digits: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len(digits) == 0:
... | stack_v2_sparse_classes_36k_train_015326 | 2,031 | no_license | [
{
"docstring": ":type digits: List[int] :rtype: List[int]",
"name": "plusOne",
"signature": "def plusOne(self, digits)"
},
{
"docstring": ":type digits: List[int] :rtype: List[int]",
"name": "plusOne2",
"signature": "def plusOne2(self, digits)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004737 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def plusOne(self, digits): :type digits: List[int] :rtype: List[int]
- def plusOne2(self, digits): :type digits: List[int] :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def plusOne(self, digits): :type digits: List[int] :rtype: List[int]
- def plusOne2(self, digits): :type digits: List[int] :rtype: List[int]
<|skeleton|>
class Solution:
de... | f022677c042db3598003df1a320a70f0edc4f870 | <|skeleton|>
class Solution:
def plusOne(self, digits):
""":type digits: List[int] :rtype: List[int]"""
<|body_0|>
def plusOne2(self, digits):
""":type digits: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def plusOne(self, digits):
""":type digits: List[int] :rtype: List[int]"""
if len(digits) == 0:
digits = [1]
elif digits[-1] == 9:
print('aaa')
print(digits[:-1])
digits = self.plusOne(digits[:-1])
print('xxxxx')
... | the_stack_v2_python_sparse | ArrayDeal/jiayi.py | daisyzl/program-exercise-python | train | 0 | |
7ee1314c5b7a024d8d711f298c47a22e3eebe767 | [
"if verbose:\n print('SQL Database type %s verbose=%s' % (db_dict, verbose))\nsuper(SQLProgramsTable, self).__init__(db_dict, dbtype, verbose)\nself.connection = None",
"try:\n print('Database characteristics:')\n for key in self.db_dict:\n print('%s: %s' % key, self.db_dict[key])\nexcept ValueEr... | <|body_start_0|>
if verbose:
print('SQL Database type %s verbose=%s' % (db_dict, verbose))
super(SQLProgramsTable, self).__init__(db_dict, dbtype, verbose)
self.connection = None
<|end_body_0|>
<|body_start_1|>
try:
print('Database characteristics:')
... | " Table representing the Programs database table This table supports a single dictionary that contains the data when the table is intialized. | SQLProgramsTable | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SQLProgramsTable:
"""" Table representing the Programs database table This table supports a single dictionary that contains the data when the table is intialized."""
def __init__(self, db_dict, dbtype, verbose):
"""Pass through to SQL"""
<|body_0|>
def db_info(self):
... | stack_v2_sparse_classes_36k_train_015327 | 9,672 | permissive | [
{
"docstring": "Pass through to SQL",
"name": "__init__",
"signature": "def __init__(self, db_dict, dbtype, verbose)"
},
{
"docstring": "Display the db info and Return info on the database used as a dictionary.",
"name": "db_info",
"signature": "def db_info(self)"
}
] | 2 | null | Implement the Python class `SQLProgramsTable` described below.
Class description:
" Table representing the Programs database table This table supports a single dictionary that contains the data when the table is intialized.
Method signatures and docstrings:
- def __init__(self, db_dict, dbtype, verbose): Pass through... | Implement the Python class `SQLProgramsTable` described below.
Class description:
" Table representing the Programs database table This table supports a single dictionary that contains the data when the table is intialized.
Method signatures and docstrings:
- def __init__(self, db_dict, dbtype, verbose): Pass through... | 9c60b3489f02592bd9099b8719ca23ae43a9eaa5 | <|skeleton|>
class SQLProgramsTable:
"""" Table representing the Programs database table This table supports a single dictionary that contains the data when the table is intialized."""
def __init__(self, db_dict, dbtype, verbose):
"""Pass through to SQL"""
<|body_0|>
def db_info(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SQLProgramsTable:
"""" Table representing the Programs database table This table supports a single dictionary that contains the data when the table is intialized."""
def __init__(self, db_dict, dbtype, verbose):
"""Pass through to SQL"""
if verbose:
print('SQL Database type %s... | the_stack_v2_python_sparse | smipyping/_programstable.py | KSchopmeyer/smipyping | train | 0 |
1cc1487eb70f0cbeac5b58fa51dde279d08579ce | [
"MD = '100'\nops, cts = tu.splitMD(MD)\nassert ops == ['M']\nassert cts == [100]",
"MD = '48T42G8'\nops, cts = tu.splitMD(MD)\nassert ops == ['M', 'X', 'M', 'X', 'M']\nassert cts == [48, 1, 42, 1, 8]",
"MD = '56^ACG45'\nops, cts = tu.splitMD(MD)\nassert ops == ['M', 'D', 'M']\nassert cts == [56, 3, 45]",
"MD ... | <|body_start_0|>
MD = '100'
ops, cts = tu.splitMD(MD)
assert ops == ['M']
assert cts == [100]
<|end_body_0|>
<|body_start_1|>
MD = '48T42G8'
ops, cts = tu.splitMD(MD)
assert ops == ['M', 'X', 'M', 'X', 'M']
assert cts == [48, 1, 42, 1, 8]
<|end_body_1|>
... | TestSplitMD | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestSplitMD:
def test_splitMD(self):
"""Easy case- full match"""
<|body_0|>
def test_with_mismatches(self):
"""MD tag with mismatches in it"""
<|body_1|>
def test_with_deletion(self):
"""MD tag with deletions in it"""
<|body_2|>
def ... | stack_v2_sparse_classes_36k_train_015328 | 992 | permissive | [
{
"docstring": "Easy case- full match",
"name": "test_splitMD",
"signature": "def test_splitMD(self)"
},
{
"docstring": "MD tag with mismatches in it",
"name": "test_with_mismatches",
"signature": "def test_with_mismatches(self)"
},
{
"docstring": "MD tag with deletions in it",
... | 4 | stack_v2_sparse_classes_30k_train_020326 | Implement the Python class `TestSplitMD` described below.
Class description:
Implement the TestSplitMD class.
Method signatures and docstrings:
- def test_splitMD(self): Easy case- full match
- def test_with_mismatches(self): MD tag with mismatches in it
- def test_with_deletion(self): MD tag with deletions in it
- d... | Implement the Python class `TestSplitMD` described below.
Class description:
Implement the TestSplitMD class.
Method signatures and docstrings:
- def test_splitMD(self): Easy case- full match
- def test_with_mismatches(self): MD tag with mismatches in it
- def test_with_deletion(self): MD tag with deletions in it
- d... | 8014faed5f982e5e106ec05239e47d65878e76c3 | <|skeleton|>
class TestSplitMD:
def test_splitMD(self):
"""Easy case- full match"""
<|body_0|>
def test_with_mismatches(self):
"""MD tag with mismatches in it"""
<|body_1|>
def test_with_deletion(self):
"""MD tag with deletions in it"""
<|body_2|>
def ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestSplitMD:
def test_splitMD(self):
"""Easy case- full match"""
MD = '100'
ops, cts = tu.splitMD(MD)
assert ops == ['M']
assert cts == [100]
def test_with_mismatches(self):
"""MD tag with mismatches in it"""
MD = '48T42G8'
ops, cts = tu.spl... | the_stack_v2_python_sparse | testing_suite/test_splitMD.py | kopardev/TALON | train | 0 | |
0cb010fec95294db88560c917b9bb2ec7568225b | [
"form.instance.review = Review.objects.get(pk=self.kwargs['id'])\nform.instance.type = 'RV'\nreturn super().form_valid(form)",
"context = super().get_context_data(**kwargs)\ncontext['name'] = Review.objects.get(pk=self.kwargs['id']).title\nreturn context"
] | <|body_start_0|>
form.instance.review = Review.objects.get(pk=self.kwargs['id'])
form.instance.type = 'RV'
return super().form_valid(form)
<|end_body_0|>
<|body_start_1|>
context = super().get_context_data(**kwargs)
context['name'] = Review.objects.get(pk=self.kwargs['id']).titl... | Class based view for reporting reviews | ReviewReportForm | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReviewReportForm:
"""Class based view for reporting reviews"""
def form_valid(self, form):
"""Ensures hidden form values are filled"""
<|body_0|>
def get_context_data(self, **kwargs):
"""Passes item name to template"""
<|body_1|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_36k_train_015329 | 10,733 | permissive | [
{
"docstring": "Ensures hidden form values are filled",
"name": "form_valid",
"signature": "def form_valid(self, form)"
},
{
"docstring": "Passes item name to template",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014303 | Implement the Python class `ReviewReportForm` described below.
Class description:
Class based view for reporting reviews
Method signatures and docstrings:
- def form_valid(self, form): Ensures hidden form values are filled
- def get_context_data(self, **kwargs): Passes item name to template | Implement the Python class `ReviewReportForm` described below.
Class description:
Class based view for reporting reviews
Method signatures and docstrings:
- def form_valid(self, form): Ensures hidden form values are filled
- def get_context_data(self, **kwargs): Passes item name to template
<|skeleton|>
class Review... | 6bf8e75a1f279ac584daa4ee19927ffccaa67551 | <|skeleton|>
class ReviewReportForm:
"""Class based view for reporting reviews"""
def form_valid(self, form):
"""Ensures hidden form values are filled"""
<|body_0|>
def get_context_data(self, **kwargs):
"""Passes item name to template"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReviewReportForm:
"""Class based view for reporting reviews"""
def form_valid(self, form):
"""Ensures hidden form values are filled"""
form.instance.review = Review.objects.get(pk=self.kwargs['id'])
form.instance.type = 'RV'
return super().form_valid(form)
def get_con... | the_stack_v2_python_sparse | rameniaapp/views/report.py | awlane/ramenia | train | 0 |
6b8e9afda6c673b9aeedca8afce715a58fff43d0 | [
"data = {}\nwith open(fpath) as f:\n data = toml.load(f)\nnetwork = data.get(network_name, {})\nself.baseline = network.get('all', {}).get('default', {})\nspecific_general_data = network.get('all', {}).get(metadata.variant, {})\naddendum = network.get(framework, {})\naddendum_default = addendum.get('default', {}... | <|body_start_0|>
data = {}
with open(fpath) as f:
data = toml.load(f)
network = data.get(network_name, {})
self.baseline = network.get('all', {}).get('default', {})
specific_general_data = network.get('all', {}).get(metadata.variant, {})
addendum = network.get... | Loads a toml checkpoint file for comparing labels and inputs. | NNTomlCheckpoint | [
"MIT",
"BSD-3-Clause",
"Apache-2.0",
"ISC",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NNTomlCheckpoint:
"""Loads a toml checkpoint file for comparing labels and inputs."""
def __init__(self, fpath: str, framework: str, network_name: str, metadata: NetworkMetadata):
"""Loads the toml file for processing."""
<|body_0|>
def _iterate_data(self, slice: List[st... | stack_v2_sparse_classes_36k_train_015330 | 4,090 | permissive | [
{
"docstring": "Loads the toml file for processing.",
"name": "__init__",
"signature": "def __init__(self, fpath: str, framework: str, network_name: str, metadata: NetworkMetadata)"
},
{
"docstring": "Helper for child classes to iterate through a slice of data. Return: (Union[Dict[str, str], Lis... | 2 | stack_v2_sparse_classes_30k_train_000517 | Implement the Python class `NNTomlCheckpoint` described below.
Class description:
Loads a toml checkpoint file for comparing labels and inputs.
Method signatures and docstrings:
- def __init__(self, fpath: str, framework: str, network_name: str, metadata: NetworkMetadata): Loads the toml file for processing.
- def _i... | Implement the Python class `NNTomlCheckpoint` described below.
Class description:
Loads a toml checkpoint file for comparing labels and inputs.
Method signatures and docstrings:
- def __init__(self, fpath: str, framework: str, network_name: str, metadata: NetworkMetadata): Loads the toml file for processing.
- def _i... | 81438d602344c977ef3cab71bd04995c1834e51c | <|skeleton|>
class NNTomlCheckpoint:
"""Loads a toml checkpoint file for comparing labels and inputs."""
def __init__(self, fpath: str, framework: str, network_name: str, metadata: NetworkMetadata):
"""Loads the toml file for processing."""
<|body_0|>
def _iterate_data(self, slice: List[st... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NNTomlCheckpoint:
"""Loads a toml checkpoint file for comparing labels and inputs."""
def __init__(self, fpath: str, framework: str, network_name: str, metadata: NetworkMetadata):
"""Loads the toml file for processing."""
data = {}
with open(fpath) as f:
data = toml.lo... | the_stack_v2_python_sparse | tensorrt-basic-1.10-3rd-plugin/TensorRT-main/demo/HuggingFace/NNDF/checkpoints.py | jinmin527/learning-cuda-trt | train | 36 |
b984c0c9b056100691fa157f2d6e4fa50df8254b | [
"wb = load_workbook(project_path.case_path)\nst = wb['test_case']\nall_row = []\nfor i in range(2, st.max_row + 1):\n each_row = []\n for j in range(1, st.max_column - 1):\n res = st.cell(i, j).value\n each_row.append(res)\n all_row.append(each_row)\nwb.close()\nreturn all_row",
"wb = load_... | <|body_start_0|>
wb = load_workbook(project_path.case_path)
st = wb['test_case']
all_row = []
for i in range(2, st.max_row + 1):
each_row = []
for j in range(1, st.max_column - 1):
res = st.cell(i, j).value
each_row.append(res)
... | 从excel中测试数据,并且能够写回测试结果,要求有返回值 | DoExcel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DoExcel:
"""从excel中测试数据,并且能够写回测试结果,要求有返回值"""
def read_excel(self):
"""读取数据"""
<|body_0|>
def write_result(self, row, column, value):
"""写回测试结果"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
wb = load_workbook(project_path.case_path)
st ... | stack_v2_sparse_classes_36k_train_015331 | 2,817 | no_license | [
{
"docstring": "读取数据",
"name": "read_excel",
"signature": "def read_excel(self)"
},
{
"docstring": "写回测试结果",
"name": "write_result",
"signature": "def write_result(self, row, column, value)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010654 | Implement the Python class `DoExcel` described below.
Class description:
从excel中测试数据,并且能够写回测试结果,要求有返回值
Method signatures and docstrings:
- def read_excel(self): 读取数据
- def write_result(self, row, column, value): 写回测试结果 | Implement the Python class `DoExcel` described below.
Class description:
从excel中测试数据,并且能够写回测试结果,要求有返回值
Method signatures and docstrings:
- def read_excel(self): 读取数据
- def write_result(self, row, column, value): 写回测试结果
<|skeleton|>
class DoExcel:
"""从excel中测试数据,并且能够写回测试结果,要求有返回值"""
def read_excel(self):
... | ca931cd49192ea07a8f8b3640e2a3513b6338288 | <|skeleton|>
class DoExcel:
"""从excel中测试数据,并且能够写回测试结果,要求有返回值"""
def read_excel(self):
"""读取数据"""
<|body_0|>
def write_result(self, row, column, value):
"""写回测试结果"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DoExcel:
"""从excel中测试数据,并且能够写回测试结果,要求有返回值"""
def read_excel(self):
"""读取数据"""
wb = load_workbook(project_path.case_path)
st = wb['test_case']
all_row = []
for i in range(2, st.max_row + 1):
each_row = []
for j in range(1, st.max_column - 1):... | the_stack_v2_python_sparse | API_Program/Task/API_01/common/request_excel.py | futurewujun/python_14_0402 | train | 0 |
0d4f7d61f4a35c62f973ef175267e9b3999931d0 | [
"self.caffe = Caffe.objects.create(name='kafo', city='Gliwice', street='Wieczorka', house_number='14', postal_code='44-100')\nself.filtry = Caffe.objects.create(name='filtry', city='Warszawa', street='Filry', house_number='14', postal_code='44-100')\nself.bakery = Company.objects.create(name='bakery', caffe=self.ca... | <|body_start_0|>
self.caffe = Caffe.objects.create(name='kafo', city='Gliwice', street='Wieczorka', house_number='14', postal_code='44-100')
self.filtry = Caffe.objects.create(name='filtry', city='Warszawa', street='Filry', house_number='14', postal_code='44-100')
self.bakery = Company.objects.c... | Company model tests. | CompanyModelTest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CompanyModelTest:
"""Company model tests."""
def setUp(self):
"""Test data setup."""
<|body_0|>
def test_name(self):
"""Check if name is unique across one caffe."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.caffe = Caffe.objects.create(n... | stack_v2_sparse_classes_36k_train_015332 | 8,665 | permissive | [
{
"docstring": "Test data setup.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Check if name is unique across one caffe.",
"name": "test_name",
"signature": "def test_name(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005208 | Implement the Python class `CompanyModelTest` described below.
Class description:
Company model tests.
Method signatures and docstrings:
- def setUp(self): Test data setup.
- def test_name(self): Check if name is unique across one caffe. | Implement the Python class `CompanyModelTest` described below.
Class description:
Company model tests.
Method signatures and docstrings:
- def setUp(self): Test data setup.
- def test_name(self): Check if name is unique across one caffe.
<|skeleton|>
class CompanyModelTest:
"""Company model tests."""
def se... | cdb7f5edb29255c7e874eaa6231621063210a8b0 | <|skeleton|>
class CompanyModelTest:
"""Company model tests."""
def setUp(self):
"""Test data setup."""
<|body_0|>
def test_name(self):
"""Check if name is unique across one caffe."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CompanyModelTest:
"""Company model tests."""
def setUp(self):
"""Test data setup."""
self.caffe = Caffe.objects.create(name='kafo', city='Gliwice', street='Wieczorka', house_number='14', postal_code='44-100')
self.filtry = Caffe.objects.create(name='filtry', city='Warszawa', stree... | the_stack_v2_python_sparse | caffe/cash/test_models.py | VirrageS/io-kawiarnie | train | 3 |
d3c487dd7eb8f96f8058bb4b1a7201e0abcfe2a2 | [
"self.car_width = car_width\nself.lidar_range = lidar_range\nself.max_turn_angle = max_turn_angle * math.pi / 180.0\nself.min_speed = min_speed\nself.max_speed = max_speed\nself.target_distance = target_dist\nif which_wall == 'left':\n self.wall = LEFT\nelif which_wall == 'right':\n self.wall = RIGHT\nelse:\n... | <|body_start_0|>
self.car_width = car_width
self.lidar_range = lidar_range
self.max_turn_angle = max_turn_angle * math.pi / 180.0
self.min_speed = min_speed
self.max_speed = max_speed
self.target_distance = target_dist
if which_wall == 'left':
self.wal... | WallFollowingControl | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WallFollowingControl:
def __init__(self, control_pub_name, car_width=0.5, lidar_range=10.0, max_turn_angle=34.0, min_speed=0.1, max_speed=3.0, target_dist=0.2, which_wall='left'):
""":param control_pub_name: :param car_width: :param lidar_range: :param max_turn_angle: :param min_speed: :... | stack_v2_sparse_classes_36k_train_015333 | 7,300 | permissive | [
{
"docstring": ":param control_pub_name: :param car_width: :param lidar_range: :param max_turn_angle: :param min_speed: :param max_speed: :param target_dist:",
"name": "__init__",
"signature": "def __init__(self, control_pub_name, car_width=0.5, lidar_range=10.0, max_turn_angle=34.0, min_speed=0.1, max_... | 5 | stack_v2_sparse_classes_30k_train_016773 | Implement the Python class `WallFollowingControl` described below.
Class description:
Implement the WallFollowingControl class.
Method signatures and docstrings:
- def __init__(self, control_pub_name, car_width=0.5, lidar_range=10.0, max_turn_angle=34.0, min_speed=0.1, max_speed=3.0, target_dist=0.2, which_wall='left... | Implement the Python class `WallFollowingControl` described below.
Class description:
Implement the WallFollowingControl class.
Method signatures and docstrings:
- def __init__(self, control_pub_name, car_width=0.5, lidar_range=10.0, max_turn_angle=34.0, min_speed=0.1, max_speed=3.0, target_dist=0.2, which_wall='left... | 0dfa40bda57bc8773e6e922dfb0abfe8c3851c8a | <|skeleton|>
class WallFollowingControl:
def __init__(self, control_pub_name, car_width=0.5, lidar_range=10.0, max_turn_angle=34.0, min_speed=0.1, max_speed=3.0, target_dist=0.2, which_wall='left'):
""":param control_pub_name: :param car_width: :param lidar_range: :param max_turn_angle: :param min_speed: :... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WallFollowingControl:
def __init__(self, control_pub_name, car_width=0.5, lidar_range=10.0, max_turn_angle=34.0, min_speed=0.1, max_speed=3.0, target_dist=0.2, which_wall='left'):
""":param control_pub_name: :param car_width: :param lidar_range: :param max_turn_angle: :param min_speed: :param max_spee... | the_stack_v2_python_sparse | src/race/scripts/wall_follower.py | ALatifG/Platooning-F1Tenth | train | 1 | |
288507987bd6e80c3c4efa7bc32b93630b4d901c | [
"assert len(input_string) > 0\nsuper().__init__(self.PROBLEM_NAME)\nself.input_string = input_string",
"print('Solving {} problem ...'.format(self.PROBLEM_NAME))\nif self.input_string == '':\n return True\nleft_index = 0\nright_index = len(self.input_string) - 1\nwhile left_index < right_index:\n while not ... | <|body_start_0|>
assert len(input_string) > 0
super().__init__(self.PROBLEM_NAME)
self.input_string = input_string
<|end_body_0|>
<|body_start_1|>
print('Solving {} problem ...'.format(self.PROBLEM_NAME))
if self.input_string == '':
return True
left_index = 0... | ValidPalindrome | ValidPalindrome | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ValidPalindrome:
"""ValidPalindrome"""
def __init__(self, input_string):
"""Valid Palindrome Args: input_string: input_string to be checked if it's a palindrome Returns: None Raises: None"""
<|body_0|>
def solve(self):
"""Solve the problem Note: O(n) works by ite... | stack_v2_sparse_classes_36k_train_015334 | 2,499 | no_license | [
{
"docstring": "Valid Palindrome Args: input_string: input_string to be checked if it's a palindrome Returns: None Raises: None",
"name": "__init__",
"signature": "def __init__(self, input_string)"
},
{
"docstring": "Solve the problem Note: O(n) works by iterating from left and right sides of th... | 3 | null | Implement the Python class `ValidPalindrome` described below.
Class description:
ValidPalindrome
Method signatures and docstrings:
- def __init__(self, input_string): Valid Palindrome Args: input_string: input_string to be checked if it's a palindrome Returns: None Raises: None
- def solve(self): Solve the problem No... | Implement the Python class `ValidPalindrome` described below.
Class description:
ValidPalindrome
Method signatures and docstrings:
- def __init__(self, input_string): Valid Palindrome Args: input_string: input_string to be checked if it's a palindrome Returns: None Raises: None
- def solve(self): Solve the problem No... | 11f4d25cb211740514c119a60962d075a0817abd | <|skeleton|>
class ValidPalindrome:
"""ValidPalindrome"""
def __init__(self, input_string):
"""Valid Palindrome Args: input_string: input_string to be checked if it's a palindrome Returns: None Raises: None"""
<|body_0|>
def solve(self):
"""Solve the problem Note: O(n) works by ite... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ValidPalindrome:
"""ValidPalindrome"""
def __init__(self, input_string):
"""Valid Palindrome Args: input_string: input_string to be checked if it's a palindrome Returns: None Raises: None"""
assert len(input_string) > 0
super().__init__(self.PROBLEM_NAME)
self.input_string... | the_stack_v2_python_sparse | python/problems/string/valid_palindrome.py | santhosh-kumar/AlgorithmsAndDataStructures | train | 2 |
874dd371bffd0e9f338c22ecf963d9cb794a4d79 | [
"self.nb_dir = os.path.abspath(texinputs) if texinputs else ''\nself.ancestor_dirs = self.nb_dir.split('/')\nsuper().__init__(**kwargs)",
"if self.nb_dir:\n return applyJSONFilters([self.action], source)\nreturn source",
"if key == 'Image':\n attr, caption, [filename, typedef] = value\n if filename[:2]... | <|body_start_0|>
self.nb_dir = os.path.abspath(texinputs) if texinputs else ''
self.ancestor_dirs = self.nb_dir.split('/')
super().__init__(**kwargs)
<|end_body_0|>
<|body_start_1|>
if self.nb_dir:
return applyJSONFilters([self.action], source)
return source
<|end_bo... | A converter that handles relative path references. | ConvertExplicitlyRelativePaths | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConvertExplicitlyRelativePaths:
"""A converter that handles relative path references."""
def __init__(self, texinputs=None, **kwargs):
"""Initialize the converter."""
<|body_0|>
def __call__(self, source):
"""Invoke the converter."""
<|body_1|>
def a... | stack_v2_sparse_classes_36k_train_015335 | 2,786 | permissive | [
{
"docstring": "Initialize the converter.",
"name": "__init__",
"signature": "def __init__(self, texinputs=None, **kwargs)"
},
{
"docstring": "Invoke the converter.",
"name": "__call__",
"signature": "def __call__(self, source)"
},
{
"docstring": "Perform the action.",
"name"... | 3 | stack_v2_sparse_classes_30k_train_018782 | Implement the Python class `ConvertExplicitlyRelativePaths` described below.
Class description:
A converter that handles relative path references.
Method signatures and docstrings:
- def __init__(self, texinputs=None, **kwargs): Initialize the converter.
- def __call__(self, source): Invoke the converter.
- def actio... | Implement the Python class `ConvertExplicitlyRelativePaths` described below.
Class description:
A converter that handles relative path references.
Method signatures and docstrings:
- def __init__(self, texinputs=None, **kwargs): Initialize the converter.
- def __call__(self, source): Invoke the converter.
- def actio... | 51c6e0a7d40918366e2a68c5ea471fd2c65722cb | <|skeleton|>
class ConvertExplicitlyRelativePaths:
"""A converter that handles relative path references."""
def __init__(self, texinputs=None, **kwargs):
"""Initialize the converter."""
<|body_0|>
def __call__(self, source):
"""Invoke the converter."""
<|body_1|>
def a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConvertExplicitlyRelativePaths:
"""A converter that handles relative path references."""
def __init__(self, texinputs=None, **kwargs):
"""Initialize the converter."""
self.nb_dir = os.path.abspath(texinputs) if texinputs else ''
self.ancestor_dirs = self.nb_dir.split('/')
... | the_stack_v2_python_sparse | nbconvert/filters/pandoc.py | jupyter/nbconvert | train | 1,645 |
39a2e19da503c769bf2b63eb359b67ca82c94385 | [
"if N in memos:\n return memos[N]\nret = []\nfor l in range(1, N - 1, 2):\n for left in self.allPossibleFBT(l):\n for right in self.allPossibleFBT(N - l - 1):\n root = TreeNode(0)\n root.left = left\n root.right = right\n ret += [root]\nmemos[N] = ret\nreturn... | <|body_start_0|>
if N in memos:
return memos[N]
ret = []
for l in range(1, N - 1, 2):
for left in self.allPossibleFBT(l):
for right in self.allPossibleFBT(N - l - 1):
root = TreeNode(0)
root.left = left
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def allPossibleFBT(self, N: int, memos={1: [TreeNode(0)]}) -> List[TreeNode]:
"""Memoization Solution Time: 140ms (98.81%) Space: 16.5MB (42.86%)"""
<|body_0|>
def allPossibleFBT(self, N: int) -> List[TreeNode]:
"""Recursive Brute Force Time: 284ms (21.05%)... | stack_v2_sparse_classes_36k_train_015336 | 1,993 | no_license | [
{
"docstring": "Memoization Solution Time: 140ms (98.81%) Space: 16.5MB (42.86%)",
"name": "allPossibleFBT",
"signature": "def allPossibleFBT(self, N: int, memos={1: [TreeNode(0)]}) -> List[TreeNode]"
},
{
"docstring": "Recursive Brute Force Time: 284ms (21.05%) Space: 27.6MB (14.29%)",
"nam... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def allPossibleFBT(self, N: int, memos={1: [TreeNode(0)]}) -> List[TreeNode]: Memoization Solution Time: 140ms (98.81%) Space: 16.5MB (42.86%)
- def allPossibleFBT(self, N: int) ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def allPossibleFBT(self, N: int, memos={1: [TreeNode(0)]}) -> List[TreeNode]: Memoization Solution Time: 140ms (98.81%) Space: 16.5MB (42.86%)
- def allPossibleFBT(self, N: int) ... | 5a40f53602d3a5f4d5478ac6ea2b41f3272420db | <|skeleton|>
class Solution:
def allPossibleFBT(self, N: int, memos={1: [TreeNode(0)]}) -> List[TreeNode]:
"""Memoization Solution Time: 140ms (98.81%) Space: 16.5MB (42.86%)"""
<|body_0|>
def allPossibleFBT(self, N: int) -> List[TreeNode]:
"""Recursive Brute Force Time: 284ms (21.05%)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def allPossibleFBT(self, N: int, memos={1: [TreeNode(0)]}) -> List[TreeNode]:
"""Memoization Solution Time: 140ms (98.81%) Space: 16.5MB (42.86%)"""
if N in memos:
return memos[N]
ret = []
for l in range(1, N - 1, 2):
for left in self.allPossib... | the_stack_v2_python_sparse | coding-problems/leetcode/trees/all_possible_full_trees.py | BaoAdrian/interview-prep | train | 0 | |
1c9a166a28d50c82f455483927a39acb5575ebfb | [
"if not height:\n return 0\nlo = 0\nhi = len(height) - 1\nleft_max = 0\nright_max = 0\nret = 0\nwhile lo < hi:\n if height[lo] <= height[hi]:\n if height[lo] > left_max:\n left_max = height[lo]\n else:\n ret += left_max - height[lo]\n lo += 1\n else:\n if h... | <|body_start_0|>
if not height:
return 0
lo = 0
hi = len(height) - 1
left_max = 0
right_max = 0
ret = 0
while lo < hi:
if height[lo] <= height[hi]:
if height[lo] > left_max:
left_max = height[lo]
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def trap(self, height):
""":type height: List[int] :rtype: int"""
<|body_0|>
def trapPerformanceIssue(self, height):
""":type height: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not height:
return 0... | stack_v2_sparse_classes_36k_train_015337 | 1,457 | no_license | [
{
"docstring": ":type height: List[int] :rtype: int",
"name": "trap",
"signature": "def trap(self, height)"
},
{
"docstring": ":type height: List[int] :rtype: int",
"name": "trapPerformanceIssue",
"signature": "def trapPerformanceIssue(self, height)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004295 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def trap(self, height): :type height: List[int] :rtype: int
- def trapPerformanceIssue(self, height): :type height: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def trap(self, height): :type height: List[int] :rtype: int
- def trapPerformanceIssue(self, height): :type height: List[int] :rtype: int
<|skeleton|>
class Solution:
def t... | be2bf7c78aaf2628419be4a6ff34817dac719a57 | <|skeleton|>
class Solution:
def trap(self, height):
""":type height: List[int] :rtype: int"""
<|body_0|>
def trapPerformanceIssue(self, height):
""":type height: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def trap(self, height):
""":type height: List[int] :rtype: int"""
if not height:
return 0
lo = 0
hi = len(height) - 1
left_max = 0
right_max = 0
ret = 0
while lo < hi:
if height[lo] <= height[hi]:
... | the_stack_v2_python_sparse | Solutions/TrappingRainWater.py | sherld/LeetCodeForPython | train | 0 | |
e28aa78fd6a3e653cd88e47e8dc2131e748e875f | [
"self.key = int(key, 16).to_bytes(16, byteorder='little')\nself.max = bound\nself.byte_length = len(self.key) + ((bound - 1).bit_length() + 7) // 8",
"n_ = n if n else 1\nl = self.byte_length\ndk = hashlib.pbkdf2_hmac('sha1', self.key, s.encode(), 1, n_ * l)\nx = [int.from_bytes(dk[i * l:(i + 1) * l], byteorder='... | <|body_start_0|>
self.key = int(key, 16).to_bytes(16, byteorder='little')
self.max = bound
self.byte_length = len(self.key) + ((bound - 1).bit_length() + 7) // 8
<|end_body_0|>
<|body_start_1|>
n_ = n if n else 1
l = self.byte_length
dk = hashlib.pbkdf2_hmac('sha1', self... | A pseudorandom function (PRF) with 128-bit keys. A PRF is determined by a secret key and a public maximum. | PRF | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PRF:
"""A pseudorandom function (PRF) with 128-bit keys. A PRF is determined by a secret key and a public maximum."""
def __init__(self, key, bound):
"""Create a PRF determined by the given key and (upper) bound. The key is a hex string, whereas bound is a number. Output values will ... | stack_v2_sparse_classes_36k_train_015338 | 6,165 | no_license | [
{
"docstring": "Create a PRF determined by the given key and (upper) bound. The key is a hex string, whereas bound is a number. Output values will be in range(bound).",
"name": "__init__",
"signature": "def __init__(self, key, bound)"
},
{
"docstring": "Return a number or list of numbers in rang... | 2 | stack_v2_sparse_classes_30k_train_002369 | Implement the Python class `PRF` described below.
Class description:
A pseudorandom function (PRF) with 128-bit keys. A PRF is determined by a secret key and a public maximum.
Method signatures and docstrings:
- def __init__(self, key, bound): Create a PRF determined by the given key and (upper) bound. The key is a h... | Implement the Python class `PRF` described below.
Class description:
A pseudorandom function (PRF) with 128-bit keys. A PRF is determined by a secret key and a public maximum.
Method signatures and docstrings:
- def __init__(self, key, bound): Create a PRF determined by the given key and (upper) bound. The key is a h... | ae8e421fb840937ccd7c8d5c35a011e5eb2c63df | <|skeleton|>
class PRF:
"""A pseudorandom function (PRF) with 128-bit keys. A PRF is determined by a secret key and a public maximum."""
def __init__(self, key, bound):
"""Create a PRF determined by the given key and (upper) bound. The key is a hex string, whereas bound is a number. Output values will ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PRF:
"""A pseudorandom function (PRF) with 128-bit keys. A PRF is determined by a secret key and a public maximum."""
def __init__(self, key, bound):
"""Create a PRF determined by the given key and (upper) bound. The key is a hex string, whereas bound is a number. Output values will be in range(b... | the_stack_v2_python_sparse | device/mpyc/mpyc/thresha.py | Fluxmux/securefacematching | train | 4 |
67ad3ae70f17557bbd92e2ea1adb8e147696f328 | [
"if GraphMetadata.__instance is None:\n GraphMetadata(sqlContext)\nreturn GraphMetadata.__instance",
"if GraphMetadata.__instance is not None:\n raise Exception('This class is a singleton!')\nelse:\n import os\n vertices_path = os.getenv('META_VERTICES_PATH', 'timeseries/graph/metadata/vertices.csv')\... | <|body_start_0|>
if GraphMetadata.__instance is None:
GraphMetadata(sqlContext)
return GraphMetadata.__instance
<|end_body_0|>
<|body_start_1|>
if GraphMetadata.__instance is not None:
raise Exception('This class is a singleton!')
else:
import os
... | GraphMetadata | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GraphMetadata:
def getInstance(sqlContext):
"""Static access method."""
<|body_0|>
def __init__(self, sqlContext):
"""Virtually private constructor."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if GraphMetadata.__instance is None:
Gra... | stack_v2_sparse_classes_36k_train_015339 | 1,143 | no_license | [
{
"docstring": "Static access method.",
"name": "getInstance",
"signature": "def getInstance(sqlContext)"
},
{
"docstring": "Virtually private constructor.",
"name": "__init__",
"signature": "def __init__(self, sqlContext)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008119 | Implement the Python class `GraphMetadata` described below.
Class description:
Implement the GraphMetadata class.
Method signatures and docstrings:
- def getInstance(sqlContext): Static access method.
- def __init__(self, sqlContext): Virtually private constructor. | Implement the Python class `GraphMetadata` described below.
Class description:
Implement the GraphMetadata class.
Method signatures and docstrings:
- def getInstance(sqlContext): Static access method.
- def __init__(self, sqlContext): Virtually private constructor.
<|skeleton|>
class GraphMetadata:
def getInsta... | cb6f6ee826509e33afb1b5e2cbb01d27d9aad222 | <|skeleton|>
class GraphMetadata:
def getInstance(sqlContext):
"""Static access method."""
<|body_0|>
def __init__(self, sqlContext):
"""Virtually private constructor."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GraphMetadata:
def getInstance(sqlContext):
"""Static access method."""
if GraphMetadata.__instance is None:
GraphMetadata(sqlContext)
return GraphMetadata.__instance
def __init__(self, sqlContext):
"""Virtually private constructor."""
if GraphMetadata.... | the_stack_v2_python_sparse | nubespark/ts/metadata/graph_metadata.py | Aidan275/spark-iot-ts | train | 3 | |
c41d30eab0f767478cf32aa263c7a3335ca48226 | [
"tax_amount = 0\nself.tax_amount = tax_amount\nself.amount_with_tax = self.amount_without_tax + tax_amount",
"res = super(sale_anticipated_invoice, self).default_get(fields_list=fields_list)\nsale_id = self.env.context.get('active_id')\nif sale_id and self.env.context.get('active_model') == 'sale.order':\n res... | <|body_start_0|>
tax_amount = 0
self.tax_amount = tax_amount
self.amount_with_tax = self.amount_without_tax + tax_amount
<|end_body_0|>
<|body_start_1|>
res = super(sale_anticipated_invoice, self).default_get(fields_list=fields_list)
sale_id = self.env.context.get('active_id')
... | Wizard to create an anticipated invoice from the sale | sale_anticipated_invoice | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class sale_anticipated_invoice:
"""Wizard to create an anticipated invoice from the sale"""
def _compute_amount_with_tax(self):
"""Calcul du montant total avec les taxes"""
<|body_0|>
def default_get(self, fields_list):
"""Surcharge afin de récupérer la vente pour laqu... | stack_v2_sparse_classes_36k_train_015340 | 7,286 | no_license | [
{
"docstring": "Calcul du montant total avec les taxes",
"name": "_compute_amount_with_tax",
"signature": "def _compute_amount_with_tax(self)"
},
{
"docstring": "Surcharge afin de récupérer la vente pour laquelle on effectue la facture anticipée",
"name": "default_get",
"signature": "def... | 5 | stack_v2_sparse_classes_30k_train_016332 | Implement the Python class `sale_anticipated_invoice` described below.
Class description:
Wizard to create an anticipated invoice from the sale
Method signatures and docstrings:
- def _compute_amount_with_tax(self): Calcul du montant total avec les taxes
- def default_get(self, fields_list): Surcharge afin de récupér... | Implement the Python class `sale_anticipated_invoice` described below.
Class description:
Wizard to create an anticipated invoice from the sale
Method signatures and docstrings:
- def _compute_amount_with_tax(self): Calcul du montant total avec les taxes
- def default_get(self, fields_list): Surcharge afin de récupér... | eb394e1f79ba1995da2dcd81adfdd511c22caff9 | <|skeleton|>
class sale_anticipated_invoice:
"""Wizard to create an anticipated invoice from the sale"""
def _compute_amount_with_tax(self):
"""Calcul du montant total avec les taxes"""
<|body_0|>
def default_get(self, fields_list):
"""Surcharge afin de récupérer la vente pour laqu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class sale_anticipated_invoice:
"""Wizard to create an anticipated invoice from the sale"""
def _compute_amount_with_tax(self):
"""Calcul du montant total avec les taxes"""
tax_amount = 0
self.tax_amount = tax_amount
self.amount_with_tax = self.amount_without_tax + tax_amount
... | the_stack_v2_python_sparse | OpenPROD/openprod-addons/sale/wizard/anticipated_invoice.py | kazacube-mziouadi/ceci | train | 0 |
f472a1af2b8f11be35cdea9c0d5b20957e2c30ca | [
"self.rstep = float(rstep)\nself.gstep = float(gstep)\nself.bstep = float(bstep)\nself.red = 0.0\nself.green = 0.0\nself.blue = 0.0\nself.step = float(math.pi / 180)\nself.degree = 0.0",
"self.red += 256 * math.sin(self.degree * self.rstep)\nself.green += 256 * math.sin(self.degree * self.gstep)\nself.blue += 256... | <|body_start_0|>
self.rstep = float(rstep)
self.gstep = float(gstep)
self.bstep = float(bstep)
self.red = 0.0
self.green = 0.0
self.blue = 0.0
self.step = float(math.pi / 180)
self.degree = 0.0
<|end_body_0|>
<|body_start_1|>
self.red += 256 * mat... | Simple Class to give back gradient colors | ColorGradient | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ColorGradient:
"""Simple Class to give back gradient colors"""
def __init__(self, rstep, gstep, bstep):
"""(float) rstep - red color step width (float) gstep - green color step width (float) bstep - blue color step width"""
<|body_0|>
def get_color(self):
"""retu... | stack_v2_sparse_classes_36k_train_015341 | 1,770 | no_license | [
{
"docstring": "(float) rstep - red color step width (float) gstep - green color step width (float) bstep - blue color step width",
"name": "__init__",
"signature": "def __init__(self, rstep, gstep, bstep)"
},
{
"docstring": "returns next color",
"name": "get_color",
"signature": "def ge... | 2 | null | Implement the Python class `ColorGradient` described below.
Class description:
Simple Class to give back gradient colors
Method signatures and docstrings:
- def __init__(self, rstep, gstep, bstep): (float) rstep - red color step width (float) gstep - green color step width (float) bstep - blue color step width
- def ... | Implement the Python class `ColorGradient` described below.
Class description:
Simple Class to give back gradient colors
Method signatures and docstrings:
- def __init__(self, rstep, gstep, bstep): (float) rstep - red color step width (float) gstep - green color step width (float) bstep - blue color step width
- def ... | 1fd421195a2888c0588a49f5a043a1110eedcdbf | <|skeleton|>
class ColorGradient:
"""Simple Class to give back gradient colors"""
def __init__(self, rstep, gstep, bstep):
"""(float) rstep - red color step width (float) gstep - green color step width (float) bstep - blue color step width"""
<|body_0|>
def get_color(self):
"""retu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ColorGradient:
"""Simple Class to give back gradient colors"""
def __init__(self, rstep, gstep, bstep):
"""(float) rstep - red color step width (float) gstep - green color step width (float) bstep - blue color step width"""
self.rstep = float(rstep)
self.gstep = float(gstep)
... | the_stack_v2_python_sparse | effects/ColorGradient.py | gunny26/pygame | train | 5 |
d97fedd04e7a93ed0210030a216a8f0fb2c59e7f | [
"super(SelfAttention, self).__init__()\nself.W = tf.keras.layers.Dense(units)\nself.U = tf.keras.layers.Dense(units)\nself.V = tf.keras.layers.Dense(1)",
"prev = self.W(tf.expand_dims(s_prev, 1))\nenc = self.U(hidden_states)\ne = self.V(tf.tanh(prev + enc))\nw = tf.nn.softmax(e, 1)\ncontext = w * hidden_states\nr... | <|body_start_0|>
super(SelfAttention, self).__init__()
self.W = tf.keras.layers.Dense(units)
self.U = tf.keras.layers.Dense(units)
self.V = tf.keras.layers.Dense(1)
<|end_body_0|>
<|body_start_1|>
prev = self.W(tf.expand_dims(s_prev, 1))
enc = self.U(hidden_states)
... | Self Attention | SelfAttention | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SelfAttention:
"""Self Attention"""
def __init__(self, units):
"""Self Attention"""
<|body_0|>
def call(self, s_prev, hidden_states):
"""Self Attention"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(SelfAttention, self).__init__()
... | stack_v2_sparse_classes_36k_train_015342 | 702 | no_license | [
{
"docstring": "Self Attention",
"name": "__init__",
"signature": "def __init__(self, units)"
},
{
"docstring": "Self Attention",
"name": "call",
"signature": "def call(self, s_prev, hidden_states)"
}
] | 2 | null | Implement the Python class `SelfAttention` described below.
Class description:
Self Attention
Method signatures and docstrings:
- def __init__(self, units): Self Attention
- def call(self, s_prev, hidden_states): Self Attention | Implement the Python class `SelfAttention` described below.
Class description:
Self Attention
Method signatures and docstrings:
- def __init__(self, units): Self Attention
- def call(self, s_prev, hidden_states): Self Attention
<|skeleton|>
class SelfAttention:
"""Self Attention"""
def __init__(self, units)... | 8761eb876046ad3c0c3f85d98dbdca4007d93cd1 | <|skeleton|>
class SelfAttention:
"""Self Attention"""
def __init__(self, units):
"""Self Attention"""
<|body_0|>
def call(self, s_prev, hidden_states):
"""Self Attention"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SelfAttention:
"""Self Attention"""
def __init__(self, units):
"""Self Attention"""
super(SelfAttention, self).__init__()
self.W = tf.keras.layers.Dense(units)
self.U = tf.keras.layers.Dense(units)
self.V = tf.keras.layers.Dense(1)
def call(self, s_prev, hidde... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/1-self_attention.py | oran2527/holbertonschool-machine_learning | train | 0 |
99a588fd1b3c8e7defae24d01c4ae7e08c5fb5c1 | [
"super(Binarize, self).__init__()\nself.threshold = threshold\n'Threshold by which to decide the class;\\n low class if ``x<=post_target_thresh``, else high'\nself.val_low_class = val_low_class\n'Value to set the low class to.'\nself.val_high_class = val_high_class\n'Value to set the high class to.'",
"set... | <|body_start_0|>
super(Binarize, self).__init__()
self.threshold = threshold
'Threshold by which to decide the class;\n low class if ``x<=post_target_thresh``, else high'
self.val_low_class = val_low_class
'Value to set the low class to.'
self.val_high_class = val_... | Simple class for binarizing tensors into high and low class values. The operation is: .. code-block: python x = val_low_class if x <= post_target_thresh else val_high_class .. note:: :py:attr:`val_low_class` needs *not* to be lower than :py:attr:`val_high_class`, so one can also invert binary masks with this. | Binarize | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Binarize:
"""Simple class for binarizing tensors into high and low class values. The operation is: .. code-block: python x = val_low_class if x <= post_target_thresh else val_high_class .. note:: :py:attr:`val_low_class` needs *not* to be lower than :py:attr:`val_high_class`, so one can also inve... | stack_v2_sparse_classes_36k_train_015343 | 14,707 | permissive | [
{
"docstring": "Init. :param threshold: the threshold that defines the border between low and high class :param val_high_class: the value to which to set entries from high class :param val_low_class: the value to which to set entries from low class",
"name": "__init__",
"signature": "def __init__(self, ... | 3 | stack_v2_sparse_classes_30k_train_020684 | Implement the Python class `Binarize` described below.
Class description:
Simple class for binarizing tensors into high and low class values. The operation is: .. code-block: python x = val_low_class if x <= post_target_thresh else val_high_class .. note:: :py:attr:`val_low_class` needs *not* to be lower than :py:attr... | Implement the Python class `Binarize` described below.
Class description:
Simple class for binarizing tensors into high and low class values. The operation is: .. code-block: python x = val_low_class if x <= post_target_thresh else val_high_class .. note:: :py:attr:`val_low_class` needs *not* to be lower than :py:attr... | 37b9fc83d7b14902dfe92e0c45071c150bcf3779 | <|skeleton|>
class Binarize:
"""Simple class for binarizing tensors into high and low class values. The operation is: .. code-block: python x = val_low_class if x <= post_target_thresh else val_high_class .. note:: :py:attr:`val_low_class` needs *not* to be lower than :py:attr:`val_high_class`, so one can also inve... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Binarize:
"""Simple class for binarizing tensors into high and low class values. The operation is: .. code-block: python x = val_low_class if x <= post_target_thresh else val_high_class .. note:: :py:attr:`val_low_class` needs *not* to be lower than :py:attr:`val_high_class`, so one can also invert binary mas... | the_stack_v2_python_sparse | hybrid_learning/datasets/transforms/image_transforms.py | JohnnyZhang917/hybrid_learning | train | 0 |
f8e5bbb5bcd89a1bd103ec6892c080d719ed5f0f | [
"self.trie_node = Trie()\nfor word in words:\n ptr = self.trie_node\n for char in reversed(word):\n if char not in ptr.nodes:\n ptr.nodes[char] = Trie()\n ptr = ptr.nodes[char]\n ptr.word = True\nself.stream = []",
"self.stream.append(letter)\nroot = self.trie_node\nfor char in r... | <|body_start_0|>
self.trie_node = Trie()
for word in words:
ptr = self.trie_node
for char in reversed(word):
if char not in ptr.nodes:
ptr.nodes[char] = Trie()
ptr = ptr.nodes[char]
ptr.word = True
self.strea... | StreamChecker | [
"MIT",
"LicenseRef-scancode-other-permissive"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StreamChecker:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def query(self, letter):
""":type letter: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.trie_node = Trie()
for word in words:
... | stack_v2_sparse_classes_36k_train_015344 | 2,461 | permissive | [
{
"docstring": ":type words: List[str]",
"name": "__init__",
"signature": "def __init__(self, words)"
},
{
"docstring": ":type letter: str :rtype: bool",
"name": "query",
"signature": "def query(self, letter)"
}
] | 2 | null | Implement the Python class `StreamChecker` described below.
Class description:
Implement the StreamChecker class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def query(self, letter): :type letter: str :rtype: bool | Implement the Python class `StreamChecker` described below.
Class description:
Implement the StreamChecker class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def query(self, letter): :type letter: str :rtype: bool
<|skeleton|>
class StreamChecker:
def __init__(self, w... | b0136eb1e4ae11dc6abcc10f5dc82fa9761bdaba | <|skeleton|>
class StreamChecker:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def query(self, letter):
""":type letter: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StreamChecker:
def __init__(self, words):
""":type words: List[str]"""
self.trie_node = Trie()
for word in words:
ptr = self.trie_node
for char in reversed(word):
if char not in ptr.nodes:
ptr.nodes[char] = Trie()
... | the_stack_v2_python_sparse | 1000-1100q/1032.py | aggy07/Leetcode | train | 1 | |
387aaf52765f86e43f055e339b290a25a6eae457 | [
"super(Board, self).__init__()\nself.outline = pygame.Rect(45, 45, 720, 720)\nself.draw()",
"pygame.draw.rect(background, BLACK, self.outline, 3)\nself.outline.inflate_ip(20, 20)\nfor i in range(18):\n for j in range(18):\n rect = pygame.Rect(45 + 40 * i, 45 + 40 * j, 40, 40)\n pygame.draw.rect(b... | <|body_start_0|>
super(Board, self).__init__()
self.outline = pygame.Rect(45, 45, 720, 720)
self.draw()
<|end_body_0|>
<|body_start_1|>
pygame.draw.rect(background, BLACK, self.outline, 3)
self.outline.inflate_ip(20, 20)
for i in range(18):
for j in range(18)... | Board | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Board:
def __init__(self):
"""Create, initialize and draw an empty board."""
<|body_0|>
def draw(self):
"""Draw the board to the background and blit it to the screen. The board is drawn by first drawing the outline, then the 19x19 grid and finally by adding hoshi to ... | stack_v2_sparse_classes_36k_train_015345 | 3,957 | permissive | [
{
"docstring": "Create, initialize and draw an empty board.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Draw the board to the background and blit it to the screen. The board is drawn by first drawing the outline, then the 19x19 grid and finally by adding hoshi to t... | 3 | stack_v2_sparse_classes_30k_train_002712 | Implement the Python class `Board` described below.
Class description:
Implement the Board class.
Method signatures and docstrings:
- def __init__(self): Create, initialize and draw an empty board.
- def draw(self): Draw the board to the background and blit it to the screen. The board is drawn by first drawing the ou... | Implement the Python class `Board` described below.
Class description:
Implement the Board class.
Method signatures and docstrings:
- def __init__(self): Create, initialize and draw an empty board.
- def draw(self): Draw the board to the background and blit it to the screen. The board is drawn by first drawing the ou... | 866e45e13171322ad1892d604508cfee9f8086c8 | <|skeleton|>
class Board:
def __init__(self):
"""Create, initialize and draw an empty board."""
<|body_0|>
def draw(self):
"""Draw the board to the background and blit it to the screen. The board is drawn by first drawing the outline, then the 19x19 grid and finally by adding hoshi to ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Board:
def __init__(self):
"""Create, initialize and draw an empty board."""
super(Board, self).__init__()
self.outline = pygame.Rect(45, 45, 720, 720)
self.draw()
def draw(self):
"""Draw the board to the background and blit it to the screen. The board is drawn by ... | the_stack_v2_python_sparse | toys/12_go/goban/goban.py | git4robot/PyKids | train | 1 | |
c04250cd8f9e384bd4f6fa026aeb20c36b38cef2 | [
"self.name = 'eeg_preprocessing_stage'\nself.bids_subject_label = subject\nself.bids_session_label = session\nself.bids_dir = bids_dir\nself.output_dir = output_dir\nself.config = EEGPreprocessingConfig()\nself.inputs = ['eeg_ts_file', 'events_file', 'electrodes_file']\nself.outputs = ['epochs_file']",
"if self.c... | <|body_start_0|>
self.name = 'eeg_preprocessing_stage'
self.bids_subject_label = subject
self.bids_session_label = session
self.bids_dir = bids_dir
self.output_dir = output_dir
self.config = EEGPreprocessingConfig()
self.inputs = ['eeg_ts_file', 'events_file', 'el... | Class that represents the preprocessing stage of a :class:`~cmp.pipelines.functional.eeg.EEGPipeline`. This stage consists of converting EEGLab `.set` EEG files to MNE Epochs in `.fif` format, the format used in the rest of the pipeline by calling, if necessary the following interface: - :class:`~cmtklib.interfaces.mne... | EEGPreprocessingStage | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EEGPreprocessingStage:
"""Class that represents the preprocessing stage of a :class:`~cmp.pipelines.functional.eeg.EEGPipeline`. This stage consists of converting EEGLab `.set` EEG files to MNE Epochs in `.fif` format, the format used in the rest of the pipeline by calling, if necessary the follo... | stack_v2_sparse_classes_36k_train_015346 | 9,232 | permissive | [
{
"docstring": "Constructor of a :class:`~cmp.stages.eeg.prerocessing.EEGPreprocessingStage` instance.",
"name": "__init__",
"signature": "def __init__(self, subject, session, bids_dir, output_dir)"
},
{
"docstring": "Create the stage workflow. Parameters ---------- flow : nipype.pipeline.engine... | 3 | null | Implement the Python class `EEGPreprocessingStage` described below.
Class description:
Class that represents the preprocessing stage of a :class:`~cmp.pipelines.functional.eeg.EEGPipeline`. This stage consists of converting EEGLab `.set` EEG files to MNE Epochs in `.fif` format, the format used in the rest of the pipe... | Implement the Python class `EEGPreprocessingStage` described below.
Class description:
Class that represents the preprocessing stage of a :class:`~cmp.pipelines.functional.eeg.EEGPipeline`. This stage consists of converting EEGLab `.set` EEG files to MNE Epochs in `.fif` format, the format used in the rest of the pipe... | 35cb2ee7be2e73896061359a6cd0a10503fadd42 | <|skeleton|>
class EEGPreprocessingStage:
"""Class that represents the preprocessing stage of a :class:`~cmp.pipelines.functional.eeg.EEGPipeline`. This stage consists of converting EEGLab `.set` EEG files to MNE Epochs in `.fif` format, the format used in the rest of the pipeline by calling, if necessary the follo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EEGPreprocessingStage:
"""Class that represents the preprocessing stage of a :class:`~cmp.pipelines.functional.eeg.EEGPipeline`. This stage consists of converting EEGLab `.set` EEG files to MNE Epochs in `.fif` format, the format used in the rest of the pipeline by calling, if necessary the following interfac... | the_stack_v2_python_sparse | cmp/stages/eeg/preprocessing.py | jwirsich/connectomemapper3 | train | 0 |
8283f6ea9a3e758bac786adc6cc13ca761efdc1e | [
"from sktime.distances._distance_alignment_paths import compute_twe_return_path\nfrom sktime.distances._twe_numba import _twe_cost_matrix\nfrom sktime.distances.lower_bounding import resolve_bounding_matrix\nfrom sktime.utils.numba.njit import njit\n_bounding_matrix = resolve_bounding_matrix(x, y, window, itakura_m... | <|body_start_0|>
from sktime.distances._distance_alignment_paths import compute_twe_return_path
from sktime.distances._twe_numba import _twe_cost_matrix
from sktime.distances.lower_bounding import resolve_bounding_matrix
from sktime.utils.numba.njit import njit
_bounding_matrix =... | Time Warp Edit (TWE) distance between two time series. The Time Warp Edit (TWE) distance is a distance measure for discrete time series matching with time 'elasticity'. In comparison to other distance measures, (e.g. DTW (Dynamic Time Warping) or LCS (Longest Common Subsequence Problem)), TWE is a metric. Its computati... | _TweDistance | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _TweDistance:
"""Time Warp Edit (TWE) distance between two time series. The Time Warp Edit (TWE) distance is a distance measure for discrete time series matching with time 'elasticity'. In comparison to other distance measures, (e.g. DTW (Dynamic Time Warping) or LCS (Longest Common Subsequence P... | stack_v2_sparse_classes_36k_train_015347 | 7,764 | permissive | [
{
"docstring": "Create a no_python compiled twe distance callable. Series should be shape (d, m), where d is the number of dimensions, m the series length. Parameters ---------- x: np.ndarray (2d array of shape (d,m1)). First time series. y: np.ndarray (2d array of shape (d,m2)). Second time series. return_cost... | 2 | null | Implement the Python class `_TweDistance` described below.
Class description:
Time Warp Edit (TWE) distance between two time series. The Time Warp Edit (TWE) distance is a distance measure for discrete time series matching with time 'elasticity'. In comparison to other distance measures, (e.g. DTW (Dynamic Time Warpin... | Implement the Python class `_TweDistance` described below.
Class description:
Time Warp Edit (TWE) distance between two time series. The Time Warp Edit (TWE) distance is a distance measure for discrete time series matching with time 'elasticity'. In comparison to other distance measures, (e.g. DTW (Dynamic Time Warpin... | 70b2bfaaa597eb31bc3a1032366dcc0e1f4c8a9f | <|skeleton|>
class _TweDistance:
"""Time Warp Edit (TWE) distance between two time series. The Time Warp Edit (TWE) distance is a distance measure for discrete time series matching with time 'elasticity'. In comparison to other distance measures, (e.g. DTW (Dynamic Time Warping) or LCS (Longest Common Subsequence P... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _TweDistance:
"""Time Warp Edit (TWE) distance between two time series. The Time Warp Edit (TWE) distance is a distance measure for discrete time series matching with time 'elasticity'. In comparison to other distance measures, (e.g. DTW (Dynamic Time Warping) or LCS (Longest Common Subsequence Problem)), TWE... | the_stack_v2_python_sparse | sktime/distances/_twe.py | sktime/sktime | train | 1,117 |
5e94920ec3f7aece10243db2afd9ebc2db742f65 | [
"self.slicer = slicer\nself.wake_kicks = []\nfor source in wake_sources:\n kicks = source.get_wake_kicks(self.slicer)\n self.wake_kicks.extend(kicks)\nn_turns_wake_max = max([source.n_turns_wake for source in wake_sources])\nself.slice_set_deque = deque([], maxlen=n_turns_wake_max)\nself.slice_set_age_deque =... | <|body_start_0|>
self.slicer = slicer
self.wake_kicks = []
for source in wake_sources:
kicks = source.get_wake_kicks(self.slicer)
self.wake_kicks.extend(kicks)
n_turns_wake_max = max([source.n_turns_wake for source in wake_sources])
self.slice_set_deque = ... | A WakeField is defined by elementary WakeKick objects that may originate from different WakeSource objects. Usually, there is no need for the user to define more than one instance of the WakeField class in a simulation - except if one wants to use different slicing configurations (one WakeField object is allowed to hav... | WakeField | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WakeField:
"""A WakeField is defined by elementary WakeKick objects that may originate from different WakeSource objects. Usually, there is no need for the user to define more than one instance of the WakeField class in a simulation - except if one wants to use different slicing configurations (o... | stack_v2_sparse_classes_36k_train_015348 | 28,906 | permissive | [
{
"docstring": "Accepts a list of WakeSource objects. Each WakeSource object knows how to generate its corresponding WakeKick objects. The collection of all the WakeKick objects of each of the passed WakeSource objects defines the WakeField. When instantiating the WakeField object, the WakeKick objects for each... | 2 | null | Implement the Python class `WakeField` described below.
Class description:
A WakeField is defined by elementary WakeKick objects that may originate from different WakeSource objects. Usually, there is no need for the user to define more than one instance of the WakeField class in a simulation - except if one wants to ... | Implement the Python class `WakeField` described below.
Class description:
A WakeField is defined by elementary WakeKick objects that may originate from different WakeSource objects. Usually, there is no need for the user to define more than one instance of the WakeField class in a simulation - except if one wants to ... | b238bf3fbea02fcfaf8795ee54cc0e3134de477a | <|skeleton|>
class WakeField:
"""A WakeField is defined by elementary WakeKick objects that may originate from different WakeSource objects. Usually, there is no need for the user to define more than one instance of the WakeField class in a simulation - except if one wants to use different slicing configurations (o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WakeField:
"""A WakeField is defined by elementary WakeKick objects that may originate from different WakeSource objects. Usually, there is no need for the user to define more than one instance of the WakeField class in a simulation - except if one wants to use different slicing configurations (one WakeField ... | the_stack_v2_python_sparse | PyHEADTAIL/impedances/wakes.py | PyCOMPLETE/PyHEADTAIL | train | 39 |
9810f110f3647afc115629e29615433696d05d52 | [
"subdivision_code = '{country_code}-{subdivision_code}'.format(country_code=country_alpha2, subdivision_code=subdivision_code)\ncity_records = City.query.filter(City.subdivision == subdivision_code).order_by(City.name).all()\nreturn city_records",
"data = request.json\ncode = '{country_alpha2}-{subdivision_code}'... | <|body_start_0|>
subdivision_code = '{country_code}-{subdivision_code}'.format(country_code=country_alpha2, subdivision_code=subdivision_code)
city_records = City.query.filter(City.subdivision == subdivision_code).order_by(City.name).all()
return city_records
<|end_body_0|>
<|body_start_1|>
... | CityCollection | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CityCollection:
def get(self, country_alpha2: str, subdivision_code: str):
"""Returns list of city records for the subdivision. :param country_alpha2: The unique two character identifier of the country record. :type country_alpha2: str :param subdivision_code: The unique two character id... | stack_v2_sparse_classes_36k_train_015349 | 9,552 | permissive | [
{
"docstring": "Returns list of city records for the subdivision. :param country_alpha2: The unique two character identifier of the country record. :type country_alpha2: str :param subdivision_code: The unique two character identifier of the subdivision record. :type subdivision_code: str :return:",
"name":... | 2 | stack_v2_sparse_classes_30k_train_017278 | Implement the Python class `CityCollection` described below.
Class description:
Implement the CityCollection class.
Method signatures and docstrings:
- def get(self, country_alpha2: str, subdivision_code: str): Returns list of city records for the subdivision. :param country_alpha2: The unique two character identifie... | Implement the Python class `CityCollection` described below.
Class description:
Implement the CityCollection class.
Method signatures and docstrings:
- def get(self, country_alpha2: str, subdivision_code: str): Returns list of city records for the subdivision. :param country_alpha2: The unique two character identifie... | a38097d0f4a2f59c7c4892df6a72c19236df48e9 | <|skeleton|>
class CityCollection:
def get(self, country_alpha2: str, subdivision_code: str):
"""Returns list of city records for the subdivision. :param country_alpha2: The unique two character identifier of the country record. :type country_alpha2: str :param subdivision_code: The unique two character id... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CityCollection:
def get(self, country_alpha2: str, subdivision_code: str):
"""Returns list of city records for the subdivision. :param country_alpha2: The unique two character identifier of the country record. :type country_alpha2: str :param subdivision_code: The unique two character identifier of th... | the_stack_v2_python_sparse | api/geolocation_data_flaskapi/endpoints/location_endpoint.py | Fyzel/geolocation-data-flaskapi | train | 3 | |
64ffda6ed86aaee36da250f53f9f1dc306cdb1a1 | [
"majorindex = 0\ncount = 1\nfor i in range(1, len(nums)):\n if count == 0:\n majorindex = i\n count = 1\n continue\n if nums[i] == nums[majorindex]:\n count += 1\n else:\n count -= 1\nreturn nums[majorindex]",
"majorindex = 0\ncount = 1\nfor i in range(1, len(nums)):\n ... | <|body_start_0|>
majorindex = 0
count = 1
for i in range(1, len(nums)):
if count == 0:
majorindex = i
count = 1
continue
if nums[i] == nums[majorindex]:
count += 1
else:
count -= 1... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def majorityElement(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def majorityElement(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
def majorityElement(self, nums):
""":type nums: List[int] :rtype: in... | stack_v2_sparse_classes_36k_train_015350 | 1,420 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "majorityElement",
"signature": "def majorityElement(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "majorityElement",
"signature": "def majorityElement(self, nums)"
},
{
"docstring": ":type ... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def majorityElement(self, nums): :type nums: List[int] :rtype: int
- def majorityElement(self, nums): :type nums: List[int] :rtype: int
- def majorityElement(self, nums): :type n... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def majorityElement(self, nums): :type nums: List[int] :rtype: int
- def majorityElement(self, nums): :type nums: List[int] :rtype: int
- def majorityElement(self, nums): :type n... | d953abe2c9680f636563e76287d2f907e90ced63 | <|skeleton|>
class Solution:
def majorityElement(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def majorityElement(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
def majorityElement(self, nums):
""":type nums: List[int] :rtype: in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def majorityElement(self, nums):
""":type nums: List[int] :rtype: int"""
majorindex = 0
count = 1
for i in range(1, len(nums)):
if count == 0:
majorindex = i
count = 1
continue
if nums[i] == nums[... | the_stack_v2_python_sparse | Python_leetcode/169_majority_elements.py | xiangcao/Leetcode | train | 0 | |
f8b5dcf7bf4ed4b997724aba8615b426148d4297 | [
"dest = cast(str, values.get('dest', ''))\nsrc = cast(str, values.get('src', ''))\nsrc_type = 's3' if src.startswith('s3://') else 'local'\ndest_type = 's3' if dest.startswith('s3://') else 'local'\nreturn cast(PathsType, f'{src_type}{dest_type}')",
"if v.startswith('s3://'):\n _bucket, key = find_bucket_key(v... | <|body_start_0|>
dest = cast(str, values.get('dest', ''))
src = cast(str, values.get('src', ''))
src_type = 's3' if src.startswith('s3://') else 'local'
dest_type = 's3' if dest.startswith('s3://') else 'local'
return cast(PathsType, f'{src_type}{dest_type}')
<|end_body_0|>
<|bo... | Parameters data model. Attributes: dest: File/object destination. src: File/object source. content_type: Explicitly provided content type. delete: Whether or not to delete files at the destination that are missing from the source location. dir_op: If the source location is a directory. dryrun: Whether this is a dry run... | ParametersDataModel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParametersDataModel:
"""Parameters data model. Attributes: dest: File/object destination. src: File/object source. content_type: Explicitly provided content type. delete: Whether or not to delete files at the destination that are missing from the source location. dir_op: If the source location is... | stack_v2_sparse_classes_36k_train_015351 | 5,394 | permissive | [
{
"docstring": "Determine paths type for the given src and dest.",
"name": "_determine_paths_type",
"signature": "def _determine_paths_type(cls, v: Optional[str], values: Dict[str, Any]) -> PathsType"
},
{
"docstring": "Add a trailing \"/\" if the root of an S3 bucket was provided.",
"name":... | 2 | stack_v2_sparse_classes_30k_train_005446 | Implement the Python class `ParametersDataModel` described below.
Class description:
Parameters data model. Attributes: dest: File/object destination. src: File/object source. content_type: Explicitly provided content type. delete: Whether or not to delete files at the destination that are missing from the source loca... | Implement the Python class `ParametersDataModel` described below.
Class description:
Parameters data model. Attributes: dest: File/object destination. src: File/object source. content_type: Explicitly provided content type. delete: Whether or not to delete files at the destination that are missing from the source loca... | 0763b06aee07d2cf3f037a49ca0cb81a048c5deb | <|skeleton|>
class ParametersDataModel:
"""Parameters data model. Attributes: dest: File/object destination. src: File/object source. content_type: Explicitly provided content type. delete: Whether or not to delete files at the destination that are missing from the source location. dir_op: If the source location is... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ParametersDataModel:
"""Parameters data model. Attributes: dest: File/object destination. src: File/object source. content_type: Explicitly provided content type. delete: Whether or not to delete files at the destination that are missing from the source location. dir_op: If the source location is a directory.... | the_stack_v2_python_sparse | runway/core/providers/aws/s3/_helpers/parameters.py | onicagroup/runway | train | 156 |
198cb71b66375b931883c110f37c23e7c5d3adb7 | [
"super().__init__(coordinator)\nself.key = description.key\nself._attr_unique_id = f\"{coordinator.config_entry.data['device_number']}_{description.key}\"\nself._attr_name = f'Heat Meter {description.name}'\nself.entity_description = description\nself._attr_device_info = device\nself._attr_should_poll = bool(self.k... | <|body_start_0|>
super().__init__(coordinator)
self.key = description.key
self._attr_unique_id = f"{coordinator.config_entry.data['device_number']}_{description.key}"
self._attr_name = f'Heat Meter {description.name}'
self.entity_description = description
self._attr_devic... | Representation of a Sensor. | HeatMeterSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HeatMeterSensor:
"""Representation of a Sensor."""
def __init__(self, coordinator: DataUpdateCoordinator[HeatMeterResponse], description: SensorEntityDescription, device: DeviceInfo) -> None:
"""Set up the sensor with the initial values."""
<|body_0|>
async def async_add... | stack_v2_sparse_classes_36k_train_015352 | 3,551 | permissive | [
{
"docstring": "Set up the sensor with the initial values.",
"name": "__init__",
"signature": "def __init__(self, coordinator: DataUpdateCoordinator[HeatMeterResponse], description: SensorEntityDescription, device: DeviceInfo) -> None"
},
{
"docstring": "Call when entity about to be added to has... | 3 | null | Implement the Python class `HeatMeterSensor` described below.
Class description:
Representation of a Sensor.
Method signatures and docstrings:
- def __init__(self, coordinator: DataUpdateCoordinator[HeatMeterResponse], description: SensorEntityDescription, device: DeviceInfo) -> None: Set up the sensor with the initi... | Implement the Python class `HeatMeterSensor` described below.
Class description:
Representation of a Sensor.
Method signatures and docstrings:
- def __init__(self, coordinator: DataUpdateCoordinator[HeatMeterResponse], description: SensorEntityDescription, device: DeviceInfo) -> None: Set up the sensor with the initi... | bfa315be51371a1b63e04342a0b275a57ae148bd | <|skeleton|>
class HeatMeterSensor:
"""Representation of a Sensor."""
def __init__(self, coordinator: DataUpdateCoordinator[HeatMeterResponse], description: SensorEntityDescription, device: DeviceInfo) -> None:
"""Set up the sensor with the initial values."""
<|body_0|>
async def async_add... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HeatMeterSensor:
"""Representation of a Sensor."""
def __init__(self, coordinator: DataUpdateCoordinator[HeatMeterResponse], description: SensorEntityDescription, device: DeviceInfo) -> None:
"""Set up the sensor with the initial values."""
super().__init__(coordinator)
self.key =... | the_stack_v2_python_sparse | homeassistant/components/landisgyr_heat_meter/sensor.py | bdraco/home-assistant | train | 13 |
0f705680777286ba31d3702d748b8c6e29070faa | [
"self.Whf = np.random.randn(h + i, h)\nself.Whb = np.random.randn(h + i, h)\nself.Wy = np.random.randn(h + h, o)\nself.bhf = np.zeros((1, h))\nself.bhb = np.zeros((1, h))\nself.by = np.zeros((1, o))",
"m, i = x_t.shape\n_, h = h_prev.shape\nx_ht = np.hstack((h_prev, x_t))\nh_next = np.tanh(np.matmul(x_ht, self.Wh... | <|body_start_0|>
self.Whf = np.random.randn(h + i, h)
self.Whb = np.random.randn(h + i, h)
self.Wy = np.random.randn(h + h, o)
self.bhf = np.zeros((1, h))
self.bhb = np.zeros((1, h))
self.by = np.zeros((1, o))
<|end_body_0|>
<|body_start_1|>
m, i = x_t.shape
... | Class Bidirectional | BidirectionalCell | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BidirectionalCell:
"""Class Bidirectional"""
def __init__(self, i, h, o):
"""Constructor i is the dimensionality of the data h is the dimensionality of the hidden state o is the dimensionality of the outputs"""
<|body_0|>
def forward(self, h_prev, x_t):
"""Method... | stack_v2_sparse_classes_36k_train_015353 | 2,380 | permissive | [
{
"docstring": "Constructor i is the dimensionality of the data h is the dimensionality of the hidden state o is the dimensionality of the outputs",
"name": "__init__",
"signature": "def __init__(self, i, h, o)"
},
{
"docstring": "Method Forward calculates the hidden state in the forward directi... | 3 | null | Implement the Python class `BidirectionalCell` described below.
Class description:
Class Bidirectional
Method signatures and docstrings:
- def __init__(self, i, h, o): Constructor i is the dimensionality of the data h is the dimensionality of the hidden state o is the dimensionality of the outputs
- def forward(self,... | Implement the Python class `BidirectionalCell` described below.
Class description:
Class Bidirectional
Method signatures and docstrings:
- def __init__(self, i, h, o): Constructor i is the dimensionality of the data h is the dimensionality of the hidden state o is the dimensionality of the outputs
- def forward(self,... | eaf23423ec0f412f103f5931d6610fdd67bcc5be | <|skeleton|>
class BidirectionalCell:
"""Class Bidirectional"""
def __init__(self, i, h, o):
"""Constructor i is the dimensionality of the data h is the dimensionality of the hidden state o is the dimensionality of the outputs"""
<|body_0|>
def forward(self, h_prev, x_t):
"""Method... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BidirectionalCell:
"""Class Bidirectional"""
def __init__(self, i, h, o):
"""Constructor i is the dimensionality of the data h is the dimensionality of the hidden state o is the dimensionality of the outputs"""
self.Whf = np.random.randn(h + i, h)
self.Whb = np.random.randn(h + i,... | the_stack_v2_python_sparse | supervised_learning/0x0D-RNN/6-bi_backward.py | ledbagholberton/holbertonschool-machine_learning | train | 1 |
d1aa84c185cb236fbebc07b753069c3b18f7067f | [
"ast = lexer.SearchParser(' (\\'file name\\' contains \"foo\") and (size > 100k\\nor date before \"2011-10\")').Parse()\nself.assertEqual(ast.operator, 'and')\nself.assertEqual(ast.args[0].attribute, 'file name')\nself.assertEqual(ast.args[0].operator, 'contains')\nself.assertEqual(ast.args[0].args[0], 'foo')\nself... | <|body_start_0|>
ast = lexer.SearchParser(' (\'file name\' contains "foo") and (size > 100k\nor date before "2011-10")').Parse()
self.assertEqual(ast.operator, 'and')
self.assertEqual(ast.args[0].attribute, 'file name')
self.assertEqual(ast.args[0].operator, 'contains')
self.asse... | Test the query language parser. | LexerTests | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LexerTests:
"""Test the query language parser."""
def testParser(self):
"""Test parenthesis precedence."""
<|body_0|>
def testParser2(self):
"""Test operator precedence."""
<|body_1|>
def testParser3(self):
"""Test quote escaping in strings."... | stack_v2_sparse_classes_36k_train_015354 | 3,132 | permissive | [
{
"docstring": "Test parenthesis precedence.",
"name": "testParser",
"signature": "def testParser(self)"
},
{
"docstring": "Test operator precedence.",
"name": "testParser2",
"signature": "def testParser2(self)"
},
{
"docstring": "Test quote escaping in strings.",
"name": "te... | 4 | stack_v2_sparse_classes_30k_train_008372 | Implement the Python class `LexerTests` described below.
Class description:
Test the query language parser.
Method signatures and docstrings:
- def testParser(self): Test parenthesis precedence.
- def testParser2(self): Test operator precedence.
- def testParser3(self): Test quote escaping in strings.
- def testFaile... | Implement the Python class `LexerTests` described below.
Class description:
Test the query language parser.
Method signatures and docstrings:
- def testParser(self): Test parenthesis precedence.
- def testParser2(self): Test operator precedence.
- def testParser3(self): Test quote escaping in strings.
- def testFaile... | 44c0eb8c938302098ef7efae8cfd6b90bcfbb2d6 | <|skeleton|>
class LexerTests:
"""Test the query language parser."""
def testParser(self):
"""Test parenthesis precedence."""
<|body_0|>
def testParser2(self):
"""Test operator precedence."""
<|body_1|>
def testParser3(self):
"""Test quote escaping in strings."... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LexerTests:
"""Test the query language parser."""
def testParser(self):
"""Test parenthesis precedence."""
ast = lexer.SearchParser(' (\'file name\' contains "foo") and (size > 100k\nor date before "2011-10")').Parse()
self.assertEqual(ast.operator, 'and')
self.assertEqual... | the_stack_v2_python_sparse | grr/core/grr_response_core/lib/lexer_test.py | google/grr | train | 4,683 |
28166d3b47e0a9e14d626e7cc08bd3448d38b196 | [
"qs = self.queryset\ncities = self.request.query_params.get('city', None)\nif cities:\n cities = cities.split(',')\n qs = qs.filter(registrations__organization__city__in=cities)\nactivity = self.request.query_params.get('activity', None)\nif not self.request.user.is_staff:\n if activity:\n qs = qs.f... | <|body_start_0|>
qs = self.queryset
cities = self.request.query_params.get('city', None)
if cities:
cities = cities.split(',')
qs = qs.filter(registrations__organization__city__in=cities)
activity = self.request.query_params.get('activity', None)
if not se... | get: Returns a list of all person records post: Creates a new person record | PersonListView | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PersonListView:
"""get: Returns a list of all person records post: Creates a new person record"""
def get_queryset(self):
"""Returns Person queryset, removing non-active and unregistered drillers for anonymous users"""
<|body_0|>
def get_serializer_class(self):
"... | stack_v2_sparse_classes_36k_train_015355 | 22,178 | permissive | [
{
"docstring": "Returns Person queryset, removing non-active and unregistered drillers for anonymous users",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "Returns the appropriate serializer for the user",
"name": "get_serializer_class",
"signature": "de... | 3 | stack_v2_sparse_classes_30k_train_009114 | Implement the Python class `PersonListView` described below.
Class description:
get: Returns a list of all person records post: Creates a new person record
Method signatures and docstrings:
- def get_queryset(self): Returns Person queryset, removing non-active and unregistered drillers for anonymous users
- def get_s... | Implement the Python class `PersonListView` described below.
Class description:
get: Returns a list of all person records post: Creates a new person record
Method signatures and docstrings:
- def get_queryset(self): Returns Person queryset, removing non-active and unregistered drillers for anonymous users
- def get_s... | cb47ec1d0c31b6f1586843e491f7cb5f1b98d61a | <|skeleton|>
class PersonListView:
"""get: Returns a list of all person records post: Creates a new person record"""
def get_queryset(self):
"""Returns Person queryset, removing non-active and unregistered drillers for anonymous users"""
<|body_0|>
def get_serializer_class(self):
"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PersonListView:
"""get: Returns a list of all person records post: Creates a new person record"""
def get_queryset(self):
"""Returns Person queryset, removing non-active and unregistered drillers for anonymous users"""
qs = self.queryset
cities = self.request.query_params.get('cit... | the_stack_v2_python_sparse | app/registries/views.py | cvarjao/gwells | train | 0 |
3d8100ebc12685a003b43f081e83a6d4986bc396 | [
"cur = root\nwhile cur:\n if cur.left:\n pre = cur.left\n while pre.right:\n pre = pre.right\n pre.right = cur.right\n cur.right = cur.left\n cur.left = None\n cur = cur.right",
"links = []\nif not root:\n return\nstack = [root]\nwhile stack:\n root = stac... | <|body_start_0|>
cur = root
while cur:
if cur.left:
pre = cur.left
while pre.right:
pre = pre.right
pre.right = cur.right
cur.right = cur.left
cur.left = None
cur = cur.right
<|end... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def flatten(self, root: TreeNode) -> None:
"""寻找前驱节点 空间复杂度 O(1) 对于当前节点 - 如果左节点为空,不需操作 - 如果左节点不为空,那么左子树的最右节点(先序遍历最后1个) 作为右节点的前驱节点 更新过程中,不是一直维护着顺序;而是每到1个节点,先确保右找到前驱,找到链表部分关系,再继续遍历链表"""
<|body_0|>
def flatten_store(self, root: TreeNode) -> None:
"""Do not retu... | stack_v2_sparse_classes_36k_train_015356 | 2,212 | no_license | [
{
"docstring": "寻找前驱节点 空间复杂度 O(1) 对于当前节点 - 如果左节点为空,不需操作 - 如果左节点不为空,那么左子树的最右节点(先序遍历最后1个) 作为右节点的前驱节点 更新过程中,不是一直维护着顺序;而是每到1个节点,先确保右找到前驱,找到链表部分关系,再继续遍历链表",
"name": "flatten",
"signature": "def flatten(self, root: TreeNode) -> None"
},
{
"docstring": "Do not return anything, modify root in-place inst... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def flatten(self, root: TreeNode) -> None: 寻找前驱节点 空间复杂度 O(1) 对于当前节点 - 如果左节点为空,不需操作 - 如果左节点不为空,那么左子树的最右节点(先序遍历最后1个) 作为右节点的前驱节点 更新过程中,不是一直维护着顺序;而是每到1个节点,先确保右找到前驱,找到链表部分关系,再继续遍历链表
-... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def flatten(self, root: TreeNode) -> None: 寻找前驱节点 空间复杂度 O(1) 对于当前节点 - 如果左节点为空,不需操作 - 如果左节点不为空,那么左子树的最右节点(先序遍历最后1个) 作为右节点的前驱节点 更新过程中,不是一直维护着顺序;而是每到1个节点,先确保右找到前驱,找到链表部分关系,再继续遍历链表
-... | 4ca0ec2ab9510b12b7e8c65af52dee719f099ea6 | <|skeleton|>
class Solution:
def flatten(self, root: TreeNode) -> None:
"""寻找前驱节点 空间复杂度 O(1) 对于当前节点 - 如果左节点为空,不需操作 - 如果左节点不为空,那么左子树的最右节点(先序遍历最后1个) 作为右节点的前驱节点 更新过程中,不是一直维护着顺序;而是每到1个节点,先确保右找到前驱,找到链表部分关系,再继续遍历链表"""
<|body_0|>
def flatten_store(self, root: TreeNode) -> None:
"""Do not retu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def flatten(self, root: TreeNode) -> None:
"""寻找前驱节点 空间复杂度 O(1) 对于当前节点 - 如果左节点为空,不需操作 - 如果左节点不为空,那么左子树的最右节点(先序遍历最后1个) 作为右节点的前驱节点 更新过程中,不是一直维护着顺序;而是每到1个节点,先确保右找到前驱,找到链表部分关系,再继续遍历链表"""
cur = root
while cur:
if cur.left:
pre = cur.left
... | the_stack_v2_python_sparse | case/dfs/二叉树展开为链表.py | JDer-liuodngkai/LeetCode | train | 0 | |
189c763023eca6be54ac3d713a99b6a0b0e2142c | [
"from yahoo_finance import Share\nself._name = name\nself._symbol = symbol\nself.state = None\nself.price_change = None\nself.price_open = None\nself.prev_close = None\nself.stock = Share(symbol)",
"self.stock.refresh()\nself.state = self.stock.get_price()\nself.price_change = self.stock.get_change()\nself.price_... | <|body_start_0|>
from yahoo_finance import Share
self._name = name
self._symbol = symbol
self.state = None
self.price_change = None
self.price_open = None
self.prev_close = None
self.stock = Share(symbol)
<|end_body_0|>
<|body_start_1|>
self.stock... | Get data from Yahoo Finance. | YahooFinanceData | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class YahooFinanceData:
"""Get data from Yahoo Finance."""
def __init__(self, name, symbol):
"""Initialize the data object."""
<|body_0|>
def update(self):
"""Get the latest data and updates the states."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_015357 | 3,588 | permissive | [
{
"docstring": "Initialize the data object.",
"name": "__init__",
"signature": "def __init__(self, name, symbol)"
},
{
"docstring": "Get the latest data and updates the states.",
"name": "update",
"signature": "def update(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004169 | Implement the Python class `YahooFinanceData` described below.
Class description:
Get data from Yahoo Finance.
Method signatures and docstrings:
- def __init__(self, name, symbol): Initialize the data object.
- def update(self): Get the latest data and updates the states. | Implement the Python class `YahooFinanceData` described below.
Class description:
Get data from Yahoo Finance.
Method signatures and docstrings:
- def __init__(self, name, symbol): Initialize the data object.
- def update(self): Get the latest data and updates the states.
<|skeleton|>
class YahooFinanceData:
"""... | ca0e92aba83de2fd6cb1cc4d14f3b4471f17cf3d | <|skeleton|>
class YahooFinanceData:
"""Get data from Yahoo Finance."""
def __init__(self, name, symbol):
"""Initialize the data object."""
<|body_0|>
def update(self):
"""Get the latest data and updates the states."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class YahooFinanceData:
"""Get data from Yahoo Finance."""
def __init__(self, name, symbol):
"""Initialize the data object."""
from yahoo_finance import Share
self._name = name
self._symbol = symbol
self.state = None
self.price_change = None
self.price_op... | the_stack_v2_python_sparse | homeassistant/components/sensor/yahoo_finance.py | Smart-Torvy/torvy-home-assistant | train | 2 |
d3eff8dc0a267d363f7759037a727c4b04dc7553 | [
"n = []\nwhile head != None:\n n.append(head.val)\n head = head.next\nreturn self.sortedArrayToBST(n)",
"k = len(nums)\nif k == 0:\n return None\nif k == 1:\n return TreeNode(nums[0])\nq = k / 2\nNode = TreeNode(nums[q])\nif q == 0:\n Node.left = None\nelse:\n Node.left = self.sortedArrayToBST(n... | <|body_start_0|>
n = []
while head != None:
n.append(head.val)
head = head.next
return self.sortedArrayToBST(n)
<|end_body_0|>
<|body_start_1|>
k = len(nums)
if k == 0:
return None
if k == 1:
return TreeNode(nums[0])
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sortedListToBST(self, head):
""":type head: ListNode :rtype: TreeNode"""
<|body_0|>
def sortedArrayToBST(self, nums):
""":type nums: List[int] :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n = []
while head !... | stack_v2_sparse_classes_36k_train_015358 | 1,041 | no_license | [
{
"docstring": ":type head: ListNode :rtype: TreeNode",
"name": "sortedListToBST",
"signature": "def sortedListToBST(self, head)"
},
{
"docstring": ":type nums: List[int] :rtype: TreeNode",
"name": "sortedArrayToBST",
"signature": "def sortedArrayToBST(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021402 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortedListToBST(self, head): :type head: ListNode :rtype: TreeNode
- def sortedArrayToBST(self, nums): :type nums: List[int] :rtype: TreeNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortedListToBST(self, head): :type head: ListNode :rtype: TreeNode
- def sortedArrayToBST(self, nums): :type nums: List[int] :rtype: TreeNode
<|skeleton|>
class Solution:
... | 16422c3297ff5911a3721dcf1a5b50d09187fbc5 | <|skeleton|>
class Solution:
def sortedListToBST(self, head):
""":type head: ListNode :rtype: TreeNode"""
<|body_0|>
def sortedArrayToBST(self, nums):
""":type nums: List[int] :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def sortedListToBST(self, head):
""":type head: ListNode :rtype: TreeNode"""
n = []
while head != None:
n.append(head.val)
head = head.next
return self.sortedArrayToBST(n)
def sortedArrayToBST(self, nums):
""":type nums: List[int] ... | the_stack_v2_python_sparse | 109.py | Robert-MYM/LeetCode620 | train | 0 | |
13482df4285582a2ac66ff8b947e92a06c22d56b | [
"try:\n self.administrator\nexcept:\n return False\nreturn True",
"try:\n self.coordinator\nexcept:\n return False\nreturn True"
] | <|body_start_0|>
try:
self.administrator
except:
return False
return True
<|end_body_0|>
<|body_start_1|>
try:
self.coordinator
except:
return False
return True
<|end_body_1|>
| Proxy for the main User class. | User | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class User:
"""Proxy for the main User class."""
def is_administrator(self):
"""Returns True if the user is an administrator."""
<|body_0|>
def is_coordinator(self):
"""Returns True if the user is a coordinator."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_36k_train_015359 | 758 | no_license | [
{
"docstring": "Returns True if the user is an administrator.",
"name": "is_administrator",
"signature": "def is_administrator(self)"
},
{
"docstring": "Returns True if the user is a coordinator.",
"name": "is_coordinator",
"signature": "def is_coordinator(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000717 | Implement the Python class `User` described below.
Class description:
Proxy for the main User class.
Method signatures and docstrings:
- def is_administrator(self): Returns True if the user is an administrator.
- def is_coordinator(self): Returns True if the user is a coordinator. | Implement the Python class `User` described below.
Class description:
Proxy for the main User class.
Method signatures and docstrings:
- def is_administrator(self): Returns True if the user is an administrator.
- def is_coordinator(self): Returns True if the user is a coordinator.
<|skeleton|>
class User:
"""Pro... | b9992dc1ea27fe5e3a87cb10e691d277689008a5 | <|skeleton|>
class User:
"""Proxy for the main User class."""
def is_administrator(self):
"""Returns True if the user is an administrator."""
<|body_0|>
def is_coordinator(self):
"""Returns True if the user is a coordinator."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class User:
"""Proxy for the main User class."""
def is_administrator(self):
"""Returns True if the user is an administrator."""
try:
self.administrator
except:
return False
return True
def is_coordinator(self):
"""Returns True if the user is... | the_stack_v2_python_sparse | foji_project/foji/models/user.py | SoporteFoji/catastro | train | 0 |
961223936b42c3d4950ffe18ab4b01f9f82fc440 | [
"LcgCrypto.__init__(self, the_rnt, n_prngs, integer_width, vector_depth, paranoia_level)\nself.vector_depth = vector_depth\nself.entropy_bits = the_rnt.password_hash\nself.bit_selection_mask = integer_width - 1\nself.next_prng = 0\nself.max_integer_mask = (1 << integer_width) - 1\nself.max_integer = 1 << integer_wi... | <|body_start_0|>
LcgCrypto.__init__(self, the_rnt, n_prngs, integer_width, vector_depth, paranoia_level)
self.vector_depth = vector_depth
self.entropy_bits = the_rnt.password_hash
self.bit_selection_mask = integer_width - 1
self.next_prng = 0
self.max_integer_mask = (1 <<... | Uses a set of PRNGs to produce a crypto-quality pseudo-random number generator. Algorithm is to use N PRNGs, with the last PRNG selecting the particular bits from the others. All of the PRNGs have a uniform interface, whether they use all the arguments or not. This uses randomly chosen primes for the two constants, and... | PrngCrypto | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrngCrypto:
"""Uses a set of PRNGs to produce a crypto-quality pseudo-random number generator. Algorithm is to use N PRNGs, with the last PRNG selecting the particular bits from the others. All of the PRNGs have a uniform interface, whether they use all the arguments or not. This uses randomly ch... | stack_v2_sparse_classes_36k_train_015360 | 47,334 | no_license | [
{
"docstring": "Initializes N PRNGs of bit_width and vector_depth. The goal is to calculate and set the tuple ( RNT, int_width, lcg_array_size, multiplier, constant, lag ) for each PRNG instantiated. All PRNG algorithms may not use all of them, but the interfaces are uniform. lcg_array_size is the # of prng_bit... | 2 | stack_v2_sparse_classes_30k_train_015460 | Implement the Python class `PrngCrypto` described below.
Class description:
Uses a set of PRNGs to produce a crypto-quality pseudo-random number generator. Algorithm is to use N PRNGs, with the last PRNG selecting the particular bits from the others. All of the PRNGs have a uniform interface, whether they use all the ... | Implement the Python class `PrngCrypto` described below.
Class description:
Uses a set of PRNGs to produce a crypto-quality pseudo-random number generator. Algorithm is to use N PRNGs, with the last PRNG selecting the particular bits from the others. All of the PRNGs have a uniform interface, whether they use all the ... | 8425cfc9756eab4c8d090c14a11bfe91b0a17271 | <|skeleton|>
class PrngCrypto:
"""Uses a set of PRNGs to produce a crypto-quality pseudo-random number generator. Algorithm is to use N PRNGs, with the last PRNG selecting the particular bits from the others. All of the PRNGs have a uniform interface, whether they use all the arguments or not. This uses randomly ch... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PrngCrypto:
"""Uses a set of PRNGs to produce a crypto-quality pseudo-random number generator. Algorithm is to use N PRNGs, with the last PRNG selecting the particular bits from the others. All of the PRNGs have a uniform interface, whether they use all the arguments or not. This uses randomly chosen primes f... | the_stack_v2_python_sparse | evocprngs.py | lew128/evocrypt | train | 0 |
f8c77f184a20988fcb965264a7e9b5d44220bd56 | [
"super().__init__(coordinator)\nself.entity_description = sensor_description\ndevice_name = data.name.title()\nself._attr_unique_id = f'{unique_id}_{sensor_description.key}'\nself._attr_device_info = DeviceInfo(identifiers={(DOMAIN, unique_id)}, name=device_name)\nself._attr_device_info.update(_get_nut_device_info(... | <|body_start_0|>
super().__init__(coordinator)
self.entity_description = sensor_description
device_name = data.name.title()
self._attr_unique_id = f'{unique_id}_{sensor_description.key}'
self._attr_device_info = DeviceInfo(identifiers={(DOMAIN, unique_id)}, name=device_name)
... | Representation of a sensor entity for NUT status values. | NUTSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NUTSensor:
"""Representation of a sensor entity for NUT status values."""
def __init__(self, coordinator: DataUpdateCoordinator[dict[str, str]], sensor_description: SensorEntityDescription, data: PyNUTData, unique_id: str) -> None:
"""Initialize the sensor."""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_015361 | 29,032 | permissive | [
{
"docstring": "Initialize the sensor.",
"name": "__init__",
"signature": "def __init__(self, coordinator: DataUpdateCoordinator[dict[str, str]], sensor_description: SensorEntityDescription, data: PyNUTData, unique_id: str) -> None"
},
{
"docstring": "Return entity state from ups.",
"name": ... | 2 | null | Implement the Python class `NUTSensor` described below.
Class description:
Representation of a sensor entity for NUT status values.
Method signatures and docstrings:
- def __init__(self, coordinator: DataUpdateCoordinator[dict[str, str]], sensor_description: SensorEntityDescription, data: PyNUTData, unique_id: str) -... | Implement the Python class `NUTSensor` described below.
Class description:
Representation of a sensor entity for NUT status values.
Method signatures and docstrings:
- def __init__(self, coordinator: DataUpdateCoordinator[dict[str, str]], sensor_description: SensorEntityDescription, data: PyNUTData, unique_id: str) -... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class NUTSensor:
"""Representation of a sensor entity for NUT status values."""
def __init__(self, coordinator: DataUpdateCoordinator[dict[str, str]], sensor_description: SensorEntityDescription, data: PyNUTData, unique_id: str) -> None:
"""Initialize the sensor."""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NUTSensor:
"""Representation of a sensor entity for NUT status values."""
def __init__(self, coordinator: DataUpdateCoordinator[dict[str, str]], sensor_description: SensorEntityDescription, data: PyNUTData, unique_id: str) -> None:
"""Initialize the sensor."""
super().__init__(coordinator... | the_stack_v2_python_sparse | homeassistant/components/nut/sensor.py | home-assistant/core | train | 35,501 |
f258f0dd77fa1a80fae83317c33d2a91b673b9cb | [
"self.dic = collections.defaultdict(set)\nfor s in dictionary:\n key = s\n if len(s) > 2:\n key = s[0] + str(len(s) - 2) + s[-1]\n self.dic[key].add(s)",
"key = word\nif len(key) > 2:\n key = word[0] + str(len(word) - 2) + word[-1]\nreturn len(self.dic[key]) == 0 or (len(self.dic[key]) == 1 and... | <|body_start_0|>
self.dic = collections.defaultdict(set)
for s in dictionary:
key = s
if len(s) > 2:
key = s[0] + str(len(s) - 2) + s[-1]
self.dic[key].add(s)
<|end_body_0|>
<|body_start_1|>
key = word
if len(key) > 2:
key ... | ValidWordAbbr | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ValidWordAbbr:
def __init__(self, dictionary):
"""initialize your data structure here. :type dictionary: List[str]"""
<|body_0|>
def isUnique(self, word):
"""check if a word is unique. :type word: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start... | stack_v2_sparse_classes_36k_train_015362 | 864 | no_license | [
{
"docstring": "initialize your data structure here. :type dictionary: List[str]",
"name": "__init__",
"signature": "def __init__(self, dictionary)"
},
{
"docstring": "check if a word is unique. :type word: str :rtype: bool",
"name": "isUnique",
"signature": "def isUnique(self, word)"
... | 2 | stack_v2_sparse_classes_30k_train_005598 | Implement the Python class `ValidWordAbbr` described below.
Class description:
Implement the ValidWordAbbr class.
Method signatures and docstrings:
- def __init__(self, dictionary): initialize your data structure here. :type dictionary: List[str]
- def isUnique(self, word): check if a word is unique. :type word: str ... | Implement the Python class `ValidWordAbbr` described below.
Class description:
Implement the ValidWordAbbr class.
Method signatures and docstrings:
- def __init__(self, dictionary): initialize your data structure here. :type dictionary: List[str]
- def isUnique(self, word): check if a word is unique. :type word: str ... | 024c1b5c98a9e85706e110fc2be8dcebf0f460c3 | <|skeleton|>
class ValidWordAbbr:
def __init__(self, dictionary):
"""initialize your data structure here. :type dictionary: List[str]"""
<|body_0|>
def isUnique(self, word):
"""check if a word is unique. :type word: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ValidWordAbbr:
def __init__(self, dictionary):
"""initialize your data structure here. :type dictionary: List[str]"""
self.dic = collections.defaultdict(set)
for s in dictionary:
key = s
if len(s) > 2:
key = s[0] + str(len(s) - 2) + s[-1]
... | the_stack_v2_python_sparse | 288.UniqueWordAbbreviation.py | yao9208/lc | train | 0 | |
881cdb99e2b12a8d213e1d201c8a9e6dcd7313c3 | [
"def merge(node1, node2):\n dummy = node = ListNode(0)\n while node1 and node2:\n if node1.val < node2.val:\n node.next = node1\n node1 = node1.next\n else:\n node.next = node2\n node2 = node2.next\n node = node.next\n if node1:\n node... | <|body_start_0|>
def merge(node1, node2):
dummy = node = ListNode(0)
while node1 and node2:
if node1.val < node2.val:
node.next = node1
node1 = node1.next
else:
node.next = node2
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
"""执行用时 :136 ms, 在所有 Python3 提交中击败了41.59%的用户 内存消耗 :16.6 MB, 在所有 Python3 提交中击败了21.43%的用户 :param lists: :return:"""
<|body_0|>
def mergeKLists2(self, lists: List[ListNode]) -> ListNode:
"""执行用时 :100 ms... | stack_v2_sparse_classes_36k_train_015363 | 2,294 | no_license | [
{
"docstring": "执行用时 :136 ms, 在所有 Python3 提交中击败了41.59%的用户 内存消耗 :16.6 MB, 在所有 Python3 提交中击败了21.43%的用户 :param lists: :return:",
"name": "mergeKLists",
"signature": "def mergeKLists(self, lists: List[ListNode]) -> ListNode"
},
{
"docstring": "执行用时 :100 ms, 在所有 Python3 提交中击败了71.39%的用户 内存消耗 :17.5 MB,... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeKLists(self, lists: List[ListNode]) -> ListNode: 执行用时 :136 ms, 在所有 Python3 提交中击败了41.59%的用户 内存消耗 :16.6 MB, 在所有 Python3 提交中击败了21.43%的用户 :param lists: :return:
- def mergeK... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeKLists(self, lists: List[ListNode]) -> ListNode: 执行用时 :136 ms, 在所有 Python3 提交中击败了41.59%的用户 内存消耗 :16.6 MB, 在所有 Python3 提交中击败了21.43%的用户 :param lists: :return:
- def mergeK... | e43ee86c5a8cdb808da09b4b6138e10275abadb5 | <|skeleton|>
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
"""执行用时 :136 ms, 在所有 Python3 提交中击败了41.59%的用户 内存消耗 :16.6 MB, 在所有 Python3 提交中击败了21.43%的用户 :param lists: :return:"""
<|body_0|>
def mergeKLists2(self, lists: List[ListNode]) -> ListNode:
"""执行用时 :100 ms... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
"""执行用时 :136 ms, 在所有 Python3 提交中击败了41.59%的用户 内存消耗 :16.6 MB, 在所有 Python3 提交中击败了21.43%的用户 :param lists: :return:"""
def merge(node1, node2):
dummy = node = ListNode(0)
while node1 and node2:
... | the_stack_v2_python_sparse | LeetCode/链表(Linked list)/23. Merge k Sorted Lists.py | yiming1012/MyLeetCode | train | 2 | |
04ff6c9a18d51f668a6d0132de24fa882c712995 | [
"self.servicecallname = rpcstatsproto.service_call_name()\nself.category = _RPCCategory(rpcstatsproto)\nself.time = 0\nself.numcalls = 0\nself.keys_read = []\nself.keys_written = []\nself.keys_failed_get = []\nself.Incr(rpcstatsproto)",
"self.time += int(rpcstatsproto.duration_milliseconds())\nself.numcalls += 1\... | <|body_start_0|>
self.servicecallname = rpcstatsproto.service_call_name()
self.category = _RPCCategory(rpcstatsproto)
self.time = 0
self.numcalls = 0
self.keys_read = []
self.keys_written = []
self.keys_failed_get = []
self.Incr(rpcstatsproto)
<|end_body_0... | Statistics associated with each RPC call category for a request. For each RPC call category associated with a URL request, track the number of calls, and total time spent summed across all calls. For datastore related RPCs, track list of entities accessed (fetched/written/failed get requests). | RPCStats | [
"Apache-2.0",
"LGPL-2.1-or-later",
"BSD-3-Clause",
"MIT",
"GPL-2.0-or-later",
"MPL-1.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RPCStats:
"""Statistics associated with each RPC call category for a request. For each RPC call category associated with a URL request, track the number of calls, and total time spent summed across all calls. For datastore related RPCs, track list of entities accessed (fetched/written/failed get ... | stack_v2_sparse_classes_36k_train_015364 | 13,320 | permissive | [
{
"docstring": "Initialize stats first time RPC called for that URL request. Args: rpcstatsproto: IndividualRPCStatsProto from Appstats recording which represents statistics for a single RPC in a request.",
"name": "__init__",
"signature": "def __init__(self, rpcstatsproto)"
},
{
"docstring": "U... | 4 | null | Implement the Python class `RPCStats` described below.
Class description:
Statistics associated with each RPC call category for a request. For each RPC call category associated with a URL request, track the number of calls, and total time spent summed across all calls. For datastore related RPCs, track list of entitie... | Implement the Python class `RPCStats` described below.
Class description:
Statistics associated with each RPC call category for a request. For each RPC call category associated with a URL request, track the number of calls, and total time spent summed across all calls. For datastore related RPCs, track list of entitie... | be17e5f658d7b42b5aa7eeb7a5ddd4962f3ea82f | <|skeleton|>
class RPCStats:
"""Statistics associated with each RPC call category for a request. For each RPC call category associated with a URL request, track the number of calls, and total time spent summed across all calls. For datastore related RPCs, track list of entities accessed (fetched/written/failed get ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RPCStats:
"""Statistics associated with each RPC call category for a request. For each RPC call category associated with a URL request, track the number of calls, and total time spent summed across all calls. For datastore related RPCs, track list of entities accessed (fetched/written/failed get requests)."""... | the_stack_v2_python_sparse | AppServer/google/appengine/ext/analytics/stats.py | obino/appscale | train | 1 |
a5b99b714a38d39f8b69a064b3be7467093200dd | [
"m = len(low)\nn = len(high)\ncount = 0\nfor i in range(m + 1, n):\n count += len(self.findStrobogrammatic(i))\nif m == n:\n for elem in self.findStrobogrammatic(m):\n if int(low) <= int(elem) <= int(high):\n count += 1\nelse:\n for elem in self.findStrobogrammatic(m):\n if int(ele... | <|body_start_0|>
m = len(low)
n = len(high)
count = 0
for i in range(m + 1, n):
count += len(self.findStrobogrammatic(i))
if m == n:
for elem in self.findStrobogrammatic(m):
if int(low) <= int(elem) <= int(high):
count +... | Solution3 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution3:
def strobogrammaticInRange(self, low, high):
""":type low: str :type high: str :rtype: int"""
<|body_0|>
def findStrobogrammatic(self, n):
""":type n: int :rtype: list[str]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
m = len(low)
... | stack_v2_sparse_classes_36k_train_015365 | 5,487 | no_license | [
{
"docstring": ":type low: str :type high: str :rtype: int",
"name": "strobogrammaticInRange",
"signature": "def strobogrammaticInRange(self, low, high)"
},
{
"docstring": ":type n: int :rtype: list[str]",
"name": "findStrobogrammatic",
"signature": "def findStrobogrammatic(self, n)"
}... | 2 | null | Implement the Python class `Solution3` described below.
Class description:
Implement the Solution3 class.
Method signatures and docstrings:
- def strobogrammaticInRange(self, low, high): :type low: str :type high: str :rtype: int
- def findStrobogrammatic(self, n): :type n: int :rtype: list[str] | Implement the Python class `Solution3` described below.
Class description:
Implement the Solution3 class.
Method signatures and docstrings:
- def strobogrammaticInRange(self, low, high): :type low: str :type high: str :rtype: int
- def findStrobogrammatic(self, n): :type n: int :rtype: list[str]
<|skeleton|>
class S... | 0584b86642dff667f5bf6b7acfbbce86a41a55b6 | <|skeleton|>
class Solution3:
def strobogrammaticInRange(self, low, high):
""":type low: str :type high: str :rtype: int"""
<|body_0|>
def findStrobogrammatic(self, n):
""":type n: int :rtype: list[str]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution3:
def strobogrammaticInRange(self, low, high):
""":type low: str :type high: str :rtype: int"""
m = len(low)
n = len(high)
count = 0
for i in range(m + 1, n):
count += len(self.findStrobogrammatic(i))
if m == n:
for elem in self.... | the_stack_v2_python_sparse | python_solution/241_250/StrobogrammaticNumber.py | CescWang1991/LeetCode-Python | train | 1 | |
4e7b2d75e7903fb465f2fc40fdcfa40609bd3961 | [
"self.config = ConfigParser({}, collections.OrderedDict)\nself.patterns = collections.OrderedDict()\nif not filename:\n self.patterns[re.compile('.*')] = 'total'\n self.config.add_section('total')\n return\nself.config.read(filename)\nfor section in self.config.sections():\n pattern = re.compile(self.co... | <|body_start_0|>
self.config = ConfigParser({}, collections.OrderedDict)
self.patterns = collections.OrderedDict()
if not filename:
self.patterns[re.compile('.*')] = 'total'
self.config.add_section('total')
return
self.config.read(filename)
for... | Helper for namespaces. The config file would look like: ``` [carbon-relay] pattern = carbon\\.relay\\.* [carbon-cache] pattern = carbon\\.agents\\.* [carbon-aggregator] pattern = carbon\\.aggregator\\.* [prometheus] pattern = prometheus\\.* ``` | Namespaces | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Namespaces:
"""Helper for namespaces. The config file would look like: ``` [carbon-relay] pattern = carbon\\.relay\\.* [carbon-cache] pattern = carbon\\.agents\\.* [carbon-aggregator] pattern = carbon\\.aggregator\\.* [prometheus] pattern = prometheus\\.* ```"""
def __init__(self, filename=N... | stack_v2_sparse_classes_36k_train_015366 | 13,270 | permissive | [
{
"docstring": "Initializer.",
"name": "__init__",
"signature": "def __init__(self, filename=None)"
},
{
"docstring": "Return the namespace corresponding to the metric.",
"name": "lookup",
"signature": "def lookup(self, metric_name)"
}
] | 2 | null | Implement the Python class `Namespaces` described below.
Class description:
Helper for namespaces. The config file would look like: ``` [carbon-relay] pattern = carbon\\.relay\\.* [carbon-cache] pattern = carbon\\.agents\\.* [carbon-aggregator] pattern = carbon\\.aggregator\\.* [prometheus] pattern = prometheus\\.* ``... | Implement the Python class `Namespaces` described below.
Class description:
Helper for namespaces. The config file would look like: ``` [carbon-relay] pattern = carbon\\.relay\\.* [carbon-cache] pattern = carbon\\.agents\\.* [carbon-aggregator] pattern = carbon\\.aggregator\\.* [prometheus] pattern = prometheus\\.* ``... | 1f647ada6b3f2b2f3fb4e59d326f73a2c891fc30 | <|skeleton|>
class Namespaces:
"""Helper for namespaces. The config file would look like: ``` [carbon-relay] pattern = carbon\\.relay\\.* [carbon-cache] pattern = carbon\\.agents\\.* [carbon-aggregator] pattern = carbon\\.aggregator\\.* [prometheus] pattern = prometheus\\.* ```"""
def __init__(self, filename=N... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Namespaces:
"""Helper for namespaces. The config file would look like: ``` [carbon-relay] pattern = carbon\\.relay\\.* [carbon-cache] pattern = carbon\\.agents\\.* [carbon-aggregator] pattern = carbon\\.aggregator\\.* [prometheus] pattern = prometheus\\.* ```"""
def __init__(self, filename=None):
... | the_stack_v2_python_sparse | biggraphite/cli/command_stats.py | criteo/biggraphite | train | 129 |
678f0b217ef63cbff4f1c3189dcb58b82202d46b | [
"super(LabelSmoothing, self).__init__()\nself.smoothing = smoothing\nself.padding_token_index = padding_token_index",
"batch_size, target_sequence_length, caption_vocab_size = predicted_tensor.shape\npredicted_tensor = predicted_tensor.contiguous().view(-1, caption_vocab_size)\ntarget_tensor = target_tensor.conti... | <|body_start_0|>
super(LabelSmoothing, self).__init__()
self.smoothing = smoothing
self.padding_token_index = padding_token_index
<|end_body_0|>
<|body_start_1|>
batch_size, target_sequence_length, caption_vocab_size = predicted_tensor.shape
predicted_tensor = predicted_tensor.c... | The loss essentially drives your “gradients”, which in simple terms determines the “learning” of the model. Many manual annotations are the results of multiple participants. They might have different criteria. They might make some mistakes. So complete reliance on correct label probabilites for calculating loss is prob... | LabelSmoothing | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LabelSmoothing:
"""The loss essentially drives your “gradients”, which in simple terms determines the “learning” of the model. Many manual annotations are the results of multiple participants. They might have different criteria. They might make some mistakes. So complete reliance on correct label... | stack_v2_sparse_classes_36k_train_015367 | 4,419 | no_license | [
{
"docstring": "Args: smoothing_factor: Smooting factor to be used in label smoothing padding_token_index: Padding token index",
"name": "__init__",
"signature": "def __init__(self, smoothing, padding_token_index)"
},
{
"docstring": "Apply label smoothing to obtained new loss for predicted token... | 2 | stack_v2_sparse_classes_30k_train_007784 | Implement the Python class `LabelSmoothing` described below.
Class description:
The loss essentially drives your “gradients”, which in simple terms determines the “learning” of the model. Many manual annotations are the results of multiple participants. They might have different criteria. They might make some mistakes... | Implement the Python class `LabelSmoothing` described below.
Class description:
The loss essentially drives your “gradients”, which in simple terms determines the “learning” of the model. Many manual annotations are the results of multiple participants. They might have different criteria. They might make some mistakes... | 921557ee2f63bec10d2d3edfdad32919df3b82cf | <|skeleton|>
class LabelSmoothing:
"""The loss essentially drives your “gradients”, which in simple terms determines the “learning” of the model. Many manual annotations are the results of multiple participants. They might have different criteria. They might make some mistakes. So complete reliance on correct label... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LabelSmoothing:
"""The loss essentially drives your “gradients”, which in simple terms determines the “learning” of the model. Many manual annotations are the results of multiple participants. They might have different criteria. They might make some mistakes. So complete reliance on correct label probabilites... | the_stack_v2_python_sparse | multiModalDense/src/loss/lossComputer.py | VP-0822/Video-Keyword-Extractor | train | 11 |
e0c93dc77c335b79d2c44874e316fa28ca14ecb4 | [
"self.name = name\nself.file_path = file_path\nself.client_hellos = client_hellos\nself.server_hellos = server_hellos\nself.certificates = certificates",
"checked_signature = []\nmatches = []\nfor pkt1 in self.client_hellos:\n for pkt2 in trace.client_hellos:\n sign1 = pkt1.tls_info.fingerprint\n ... | <|body_start_0|>
self.name = name
self.file_path = file_path
self.client_hellos = client_hellos
self.server_hellos = server_hellos
self.certificates = certificates
<|end_body_0|>
<|body_start_1|>
checked_signature = []
matches = []
for pkt1 in self.client... | Class that represents a Wireshark trace file | Trace | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Trace:
"""Class that represents a Wireshark trace file"""
def __init__(self, name, file_path, client_hellos, server_hellos, certificates):
"""Constructor :param name: the name of the trace :param file_path: the path of the trace file (as specified in the args) :param client_hellos: t... | stack_v2_sparse_classes_36k_train_015368 | 4,056 | no_license | [
{
"docstring": "Constructor :param name: the name of the trace :param file_path: the path of the trace file (as specified in the args) :param client_hellos: the list of packets corresponding to client hello :param server_hellos: the list of packets corresponding to server hello :param certificates: the list of ... | 6 | stack_v2_sparse_classes_30k_train_003495 | Implement the Python class `Trace` described below.
Class description:
Class that represents a Wireshark trace file
Method signatures and docstrings:
- def __init__(self, name, file_path, client_hellos, server_hellos, certificates): Constructor :param name: the name of the trace :param file_path: the path of the trac... | Implement the Python class `Trace` described below.
Class description:
Class that represents a Wireshark trace file
Method signatures and docstrings:
- def __init__(self, name, file_path, client_hellos, server_hellos, certificates): Constructor :param name: the name of the trace :param file_path: the path of the trac... | 1118f4401c5ec574e57d1278afd58c62a98c277c | <|skeleton|>
class Trace:
"""Class that represents a Wireshark trace file"""
def __init__(self, name, file_path, client_hellos, server_hellos, certificates):
"""Constructor :param name: the name of the trace :param file_path: the path of the trace file (as specified in the args) :param client_hellos: t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Trace:
"""Class that represents a Wireshark trace file"""
def __init__(self, name, file_path, client_hellos, server_hellos, certificates):
"""Constructor :param name: the name of the trace :param file_path: the path of the trace file (as specified in the args) :param client_hellos: the list of pa... | the_stack_v2_python_sparse | classes/Trace.py | Chillimeat/iot_tls_fingerprinter | train | 0 |
fb804ebc23fc595a76f2a18d3ba4d87bc9b9b9fa | [
"AGG_LIST_SIZE = 50\nes_client = elasticsearch_factory.get_client()\nes_profile_search = {'query': {'bool': {'must': [{'term': {'author_id': profile_id}}]}}}\nes_search_result = es_client.search(index=settings.ES_RECOMMEND_USER, body=es_profile_search)\nagg_query_term = {}\nif len(es_search_result['hits']['hits']) ... | <|body_start_0|>
AGG_LIST_SIZE = 50
es_client = elasticsearch_factory.get_client()
es_profile_search = {'query': {'bool': {'must': [{'term': {'author_id': profile_id}}]}}}
es_search_result = es_client.search(index=settings.ES_RECOMMEND_USER, body=es_profile_search)
agg_query_term... | Elasticsearch User based recommendation engine Steps: - Perform aggregations on data to obtain recommendation list - Need to ensure that user apps and bookmarked apps are not in list - Output with query and put into recommendation table: See: https://github.com/aml-development/ozp-backend/wiki/Elasticsearch-Recommendat... | ElasticsearchUserBaseRecommender | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ElasticsearchUserBaseRecommender:
"""Elasticsearch User based recommendation engine Steps: - Perform aggregations on data to obtain recommendation list - Need to ensure that user apps and bookmarked apps are not in list - Output with query and put into recommendation table: See: https://github.co... | stack_v2_sparse_classes_36k_train_015369 | 31,247 | permissive | [
{
"docstring": "Recommendation Logic for Collaborative/User Based Recommendations: Recommendation logic - Take profile id passed in - Get User Profile information based on id - Get Categories, Bookmarks, Rated Apps (all and ones only greater than MIN_ES_RATING) - Compose Query to match profile of bookmarked and... | 2 | stack_v2_sparse_classes_30k_train_020062 | Implement the Python class `ElasticsearchUserBaseRecommender` described below.
Class description:
Elasticsearch User based recommendation engine Steps: - Perform aggregations on data to obtain recommendation list - Need to ensure that user apps and bookmarked apps are not in list - Output with query and put into recom... | Implement the Python class `ElasticsearchUserBaseRecommender` described below.
Class description:
Elasticsearch User based recommendation engine Steps: - Perform aggregations on data to obtain recommendation list - Need to ensure that user apps and bookmarked apps are not in list - Output with query and put into recom... | d31d00bb8a28a8d0c999813f616b398f41516244 | <|skeleton|>
class ElasticsearchUserBaseRecommender:
"""Elasticsearch User based recommendation engine Steps: - Perform aggregations on data to obtain recommendation list - Need to ensure that user apps and bookmarked apps are not in list - Output with query and put into recommendation table: See: https://github.co... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ElasticsearchUserBaseRecommender:
"""Elasticsearch User based recommendation engine Steps: - Perform aggregations on data to obtain recommendation list - Need to ensure that user apps and bookmarked apps are not in list - Output with query and put into recommendation table: See: https://github.com/aml-develop... | the_stack_v2_python_sparse | ozpcenter/recommend/recommend_es.py | ozoneplatform/ozp-backend | train | 1 |
07c94975c2840d4c2d2c22e8ec4ba0f112fba832 | [
"assert first_available_dim < 0, first_available_dim\nself.next_available_dim = first_available_dim\nself.next_available_id = 0\nself.dim_to_id = {}",
"id_ = self.next_available_id\nself.next_available_id += 1\ndim = self.next_available_dim\nif dim == -float('inf'):\n raise ValueError('max_plate_nesting must b... | <|body_start_0|>
assert first_available_dim < 0, first_available_dim
self.next_available_dim = first_available_dim
self.next_available_id = 0
self.dim_to_id = {}
<|end_body_0|>
<|body_start_1|>
id_ = self.next_available_id
self.next_available_id += 1
dim = self.n... | Dimension allocator for internal use by :func:`~pyro.poutine.markov`. There is a single global instance. Note that dimensions are indexed from the right, e.g. -1, -2. Note that ids are simply nonnegative integers here. | _EnumAllocator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _EnumAllocator:
"""Dimension allocator for internal use by :func:`~pyro.poutine.markov`. There is a single global instance. Note that dimensions are indexed from the right, e.g. -1, -2. Note that ids are simply nonnegative integers here."""
def set_first_available_dim(self, first_available_d... | stack_v2_sparse_classes_36k_train_015370 | 10,402 | permissive | [
{
"docstring": "Set the first available dim, which should be to the left of all :class:`plate` dimensions, e.g. ``-1 - max_plate_nesting``. This should be called once per program. In SVI this should be called only once per (guide,model) pair.",
"name": "set_first_available_dim",
"signature": "def set_fi... | 2 | stack_v2_sparse_classes_30k_train_001768 | Implement the Python class `_EnumAllocator` described below.
Class description:
Dimension allocator for internal use by :func:`~pyro.poutine.markov`. There is a single global instance. Note that dimensions are indexed from the right, e.g. -1, -2. Note that ids are simply nonnegative integers here.
Method signatures a... | Implement the Python class `_EnumAllocator` described below.
Class description:
Dimension allocator for internal use by :func:`~pyro.poutine.markov`. There is a single global instance. Note that dimensions are indexed from the right, e.g. -1, -2. Note that ids are simply nonnegative integers here.
Method signatures a... | 0e82cad30f75b892a07e6c9a5f9e24f2cb5d0d81 | <|skeleton|>
class _EnumAllocator:
"""Dimension allocator for internal use by :func:`~pyro.poutine.markov`. There is a single global instance. Note that dimensions are indexed from the right, e.g. -1, -2. Note that ids are simply nonnegative integers here."""
def set_first_available_dim(self, first_available_d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _EnumAllocator:
"""Dimension allocator for internal use by :func:`~pyro.poutine.markov`. There is a single global instance. Note that dimensions are indexed from the right, e.g. -1, -2. Note that ids are simply nonnegative integers here."""
def set_first_available_dim(self, first_available_dim):
... | the_stack_v2_python_sparse | pyro/poutine/runtime.py | pyro-ppl/pyro | train | 3,647 |
158d5fa3c62411632ca0cdb81ffba6bcb5eba3ad | [
"sg_node0 = SceneGraph.SceneGraphNode('sg_node0')\nsg_node1 = SceneGraph.SceneGraphNode('sg_node1')\np0 = numpy.array([-2.0, -2.0, -2.0])\np1 = numpy.array([1.0, 1.0, 3.0])\nbbox0 = Primitive.BBox()\nbbox0.insert_point(p0)\nbbox0.insert_point(p1)\nsg_node0.set_bbox(bbox0)\np2 = numpy.array([4.0, 4.0, 4.0])\nbbox0.i... | <|body_start_0|>
sg_node0 = SceneGraph.SceneGraphNode('sg_node0')
sg_node1 = SceneGraph.SceneGraphNode('sg_node1')
p0 = numpy.array([-2.0, -2.0, -2.0])
p1 = numpy.array([1.0, 1.0, 3.0])
bbox0 = Primitive.BBox()
bbox0.insert_point(p0)
bbox0.insert_point(p1)
... | test scenegraph node | TestSceneGraph | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestSceneGraph:
"""test scenegraph node"""
def test_bbox(self):
""""scenegraph bbox"""
<|body_0|>
def test_node_creation(self):
"""test node creation"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
sg_node0 = SceneGraph.SceneGraphNode('sg_node0'... | stack_v2_sparse_classes_36k_train_015371 | 2,131 | no_license | [
{
"docstring": "\"scenegraph bbox",
"name": "test_bbox",
"signature": "def test_bbox(self)"
},
{
"docstring": "test node creation",
"name": "test_node_creation",
"signature": "def test_node_creation(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006674 | Implement the Python class `TestSceneGraph` described below.
Class description:
test scenegraph node
Method signatures and docstrings:
- def test_bbox(self): "scenegraph bbox
- def test_node_creation(self): test node creation | Implement the Python class `TestSceneGraph` described below.
Class description:
test scenegraph node
Method signatures and docstrings:
- def test_bbox(self): "scenegraph bbox
- def test_node_creation(self): test node creation
<|skeleton|>
class TestSceneGraph:
"""test scenegraph node"""
def test_bbox(self):... | f163b6b9e15100d223ddf4e180727a2b63fbae2d | <|skeleton|>
class TestSceneGraph:
"""test scenegraph node"""
def test_bbox(self):
""""scenegraph bbox"""
<|body_0|>
def test_node_creation(self):
"""test node creation"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestSceneGraph:
"""test scenegraph node"""
def test_bbox(self):
""""scenegraph bbox"""
sg_node0 = SceneGraph.SceneGraphNode('sg_node0')
sg_node1 = SceneGraph.SceneGraphNode('sg_node1')
p0 = numpy.array([-2.0, -2.0, -2.0])
p1 = numpy.array([1.0, 1.0, 3.0])
b... | the_stack_v2_python_sparse | ifgi/scene/test_SceneGraph.py | yamauchih/ifgi-path-tracer | train | 0 |
ff6a91606a6e77be08ef3ecbee03ea084d84de47 | [
"web_session = async_get_clientsession(self.hass)\nweather_api = TrafikverketWeather(web_session, sensor_api)\nawait weather_api.async_get_weather(station)",
"errors = {}\nif user_input is not None:\n name = user_input[CONF_STATION]\n api_key = user_input[CONF_API_KEY]\n station = user_input[CONF_STATION... | <|body_start_0|>
web_session = async_get_clientsession(self.hass)
weather_api = TrafikverketWeather(web_session, sensor_api)
await weather_api.async_get_weather(station)
<|end_body_0|>
<|body_start_1|>
errors = {}
if user_input is not None:
name = user_input[CONF_STA... | Handle a config flow for Trafikverket Weatherstation integration. | TVWeatherConfigFlow | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TVWeatherConfigFlow:
"""Handle a config flow for Trafikverket Weatherstation integration."""
async def validate_input(self, sensor_api: str, station: str) -> None:
"""Validate input from user input."""
<|body_0|>
async def async_step_user(self, user_input: dict[str, str]... | stack_v2_sparse_classes_36k_train_015372 | 2,519 | permissive | [
{
"docstring": "Validate input from user input.",
"name": "validate_input",
"signature": "async def validate_input(self, sensor_api: str, station: str) -> None"
},
{
"docstring": "Handle the initial step.",
"name": "async_step_user",
"signature": "async def async_step_user(self, user_inp... | 2 | null | Implement the Python class `TVWeatherConfigFlow` described below.
Class description:
Handle a config flow for Trafikverket Weatherstation integration.
Method signatures and docstrings:
- async def validate_input(self, sensor_api: str, station: str) -> None: Validate input from user input.
- async def async_step_user(... | Implement the Python class `TVWeatherConfigFlow` described below.
Class description:
Handle a config flow for Trafikverket Weatherstation integration.
Method signatures and docstrings:
- async def validate_input(self, sensor_api: str, station: str) -> None: Validate input from user input.
- async def async_step_user(... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class TVWeatherConfigFlow:
"""Handle a config flow for Trafikverket Weatherstation integration."""
async def validate_input(self, sensor_api: str, station: str) -> None:
"""Validate input from user input."""
<|body_0|>
async def async_step_user(self, user_input: dict[str, str]... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TVWeatherConfigFlow:
"""Handle a config flow for Trafikverket Weatherstation integration."""
async def validate_input(self, sensor_api: str, station: str) -> None:
"""Validate input from user input."""
web_session = async_get_clientsession(self.hass)
weather_api = TrafikverketWeat... | the_stack_v2_python_sparse | homeassistant/components/trafikverket_weatherstation/config_flow.py | home-assistant/core | train | 35,501 |
607db387ef25c1944a8519011ac9aafe49019962 | [
"if isinstance(_id, int):\n return _id\nints = struct.unpack('>III', _id.binary)\nreturn (ints[0] << 64) + (ints[1] << 32) + ints[2]",
"if number < 0 or number >= 1 << 96:\n raise ValueError('number value must be within [0, %s)' % (1 << 96))\nints = [(number & 79228162495817593519834398720) >> 64, (number &... | <|body_start_0|>
if isinstance(_id, int):
return _id
ints = struct.unpack('>III', _id.binary)
return (ints[0] << 64) + (ints[1] << 32) + ints[2]
<|end_body_0|>
<|body_start_1|>
if number < 0 or number >= 1 << 96:
raise ValueError('number value must be within [0, ... | A Utility class to manipulate bson object ids. | _ObjectIdHelper | [
"BSD-3-Clause",
"MIT",
"LicenseRef-scancode-protobuf",
"Apache-2.0",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _ObjectIdHelper:
"""A Utility class to manipulate bson object ids."""
def id_to_int(cls, _id: Union[int, ObjectId]) -> int:
"""Args: _id: ObjectId required for each MongoDB document _id field. Returns: Converted integer value of ObjectId's 12 bytes binary value."""
<|body_0|>... | stack_v2_sparse_classes_36k_train_015373 | 28,533 | permissive | [
{
"docstring": "Args: _id: ObjectId required for each MongoDB document _id field. Returns: Converted integer value of ObjectId's 12 bytes binary value.",
"name": "id_to_int",
"signature": "def id_to_int(cls, _id: Union[int, ObjectId]) -> int"
},
{
"docstring": "Args: number(int): The integer val... | 3 | null | Implement the Python class `_ObjectIdHelper` described below.
Class description:
A Utility class to manipulate bson object ids.
Method signatures and docstrings:
- def id_to_int(cls, _id: Union[int, ObjectId]) -> int: Args: _id: ObjectId required for each MongoDB document _id field. Returns: Converted integer value o... | Implement the Python class `_ObjectIdHelper` described below.
Class description:
A Utility class to manipulate bson object ids.
Method signatures and docstrings:
- def id_to_int(cls, _id: Union[int, ObjectId]) -> int: Args: _id: ObjectId required for each MongoDB document _id field. Returns: Converted integer value o... | 6d5048e05087ea54abc889ce402ae2a0abb9252b | <|skeleton|>
class _ObjectIdHelper:
"""A Utility class to manipulate bson object ids."""
def id_to_int(cls, _id: Union[int, ObjectId]) -> int:
"""Args: _id: ObjectId required for each MongoDB document _id field. Returns: Converted integer value of ObjectId's 12 bytes binary value."""
<|body_0|>... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _ObjectIdHelper:
"""A Utility class to manipulate bson object ids."""
def id_to_int(cls, _id: Union[int, ObjectId]) -> int:
"""Args: _id: ObjectId required for each MongoDB document _id field. Returns: Converted integer value of ObjectId's 12 bytes binary value."""
if isinstance(_id, int)... | the_stack_v2_python_sparse | sdks/python/apache_beam/io/mongodbio.py | apache/beam | train | 7,061 |
bcec2e7f59c72c241c5a161a524b4622978eceaf | [
"super().__init__()\nassert Kxs.ndim == 3\nassert x_desireds.ndim == 2\nassert u_ffs.ndim == 2\nassert Kxs.shape[0] == x_desireds.shape[0]\nassert Kxs.shape[0] == u_ffs.shape[0]\nassert Kxs.shape[2] == x_desireds.shape[1]\nassert Kxs.shape[1] == u_ffs.shape[1]\nself.Kxs = torch.nn.Parameter(to_tensor(Kxs))\nself.x_... | <|body_start_0|>
super().__init__()
assert Kxs.ndim == 3
assert x_desireds.ndim == 2
assert u_ffs.ndim == 2
assert Kxs.shape[0] == x_desireds.shape[0]
assert Kxs.shape[0] == u_ffs.shape[0]
assert Kxs.shape[2] == x_desireds.shape[1]
assert Kxs.shape[1] == u... | Executes a time-varying linear feedback policy (output of iLQR optimization) | iLQR | [
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class iLQR:
"""Executes a time-varying linear feedback policy (output of iLQR optimization)"""
def __init__(self, Kxs, x_desireds, u_ffs):
"""Definitions: state_dim = number of state dimensions num_dofs = number of action dimensions Args: Kxs: [ time_horizon x num_dofs x state_dim ] series... | stack_v2_sparse_classes_36k_train_015374 | 2,365 | permissive | [
{
"docstring": "Definitions: state_dim = number of state dimensions num_dofs = number of action dimensions Args: Kxs: [ time_horizon x num_dofs x state_dim ] series of gain matrices x_desireds: [ time_horizon x state_dim ] series of desired state u_ffs: [ time_horizon x num_dofs ] series of desired torques",
... | 2 | stack_v2_sparse_classes_30k_train_014305 | Implement the Python class `iLQR` described below.
Class description:
Executes a time-varying linear feedback policy (output of iLQR optimization)
Method signatures and docstrings:
- def __init__(self, Kxs, x_desireds, u_ffs): Definitions: state_dim = number of state dimensions num_dofs = number of action dimensions ... | Implement the Python class `iLQR` described below.
Class description:
Executes a time-varying linear feedback policy (output of iLQR optimization)
Method signatures and docstrings:
- def __init__(self, Kxs, x_desireds, u_ffs): Definitions: state_dim = number of state dimensions num_dofs = number of action dimensions ... | 1b2ea8528d4fb9ad72cec9c766be4cbdbdf76f18 | <|skeleton|>
class iLQR:
"""Executes a time-varying linear feedback policy (output of iLQR optimization)"""
def __init__(self, Kxs, x_desireds, u_ffs):
"""Definitions: state_dim = number of state dimensions num_dofs = number of action dimensions Args: Kxs: [ time_horizon x num_dofs x state_dim ] series... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class iLQR:
"""Executes a time-varying linear feedback policy (output of iLQR optimization)"""
def __init__(self, Kxs, x_desireds, u_ffs):
"""Definitions: state_dim = number of state dimensions num_dofs = number of action dimensions Args: Kxs: [ time_horizon x num_dofs x state_dim ] series of gain matr... | the_stack_v2_python_sparse | polymetis/python/torchcontrol/policies/ilqr.py | facebookresearch/polymetis | train | 44 |
e8cbd8d3ccb736f34b31156756509f510ea97d95 | [
"cmd = '%s %s./config --prefix=%s threads shared %s' % (self.cfg['preconfigopts'], cmd_prefix, self.installdir, self.cfg['configopts'])\nout, _ = run_cmd(cmd, log_all=True, simple=False)\nreturn out",
"libdir = None\nfor libdir_cand in ['lib', 'lib64']:\n if os.path.exists(os.path.join(self.installdir, libdir_... | <|body_start_0|>
cmd = '%s %s./config --prefix=%s threads shared %s' % (self.cfg['preconfigopts'], cmd_prefix, self.installdir, self.cfg['configopts'])
out, _ = run_cmd(cmd, log_all=True, simple=False)
return out
<|end_body_0|>
<|body_start_1|>
libdir = None
for libdir_cand in [... | Support for building OpenSSL | EB_OpenSSL | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EB_OpenSSL:
"""Support for building OpenSSL"""
def configure_step(self, cmd_prefix=''):
"""Configure step"""
<|body_0|>
def sanity_check_step(self):
"""Custom sanity check"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
cmd = '%s %s./config --pr... | stack_v2_sparse_classes_36k_train_015375 | 2,597 | no_license | [
{
"docstring": "Configure step",
"name": "configure_step",
"signature": "def configure_step(self, cmd_prefix='')"
},
{
"docstring": "Custom sanity check",
"name": "sanity_check_step",
"signature": "def sanity_check_step(self)"
}
] | 2 | null | Implement the Python class `EB_OpenSSL` described below.
Class description:
Support for building OpenSSL
Method signatures and docstrings:
- def configure_step(self, cmd_prefix=''): Configure step
- def sanity_check_step(self): Custom sanity check | Implement the Python class `EB_OpenSSL` described below.
Class description:
Support for building OpenSSL
Method signatures and docstrings:
- def configure_step(self, cmd_prefix=''): Configure step
- def sanity_check_step(self): Custom sanity check
<|skeleton|>
class EB_OpenSSL:
"""Support for building OpenSSL"""... | 3c5434f9a4193fbe4cf8107327faadda83d798ae | <|skeleton|>
class EB_OpenSSL:
"""Support for building OpenSSL"""
def configure_step(self, cmd_prefix=''):
"""Configure step"""
<|body_0|>
def sanity_check_step(self):
"""Custom sanity check"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EB_OpenSSL:
"""Support for building OpenSSL"""
def configure_step(self, cmd_prefix=''):
"""Configure step"""
cmd = '%s %s./config --prefix=%s threads shared %s' % (self.cfg['preconfigopts'], cmd_prefix, self.installdir, self.cfg['configopts'])
out, _ = run_cmd(cmd, log_all=True, s... | the_stack_v2_python_sparse | 1.11.1/easyblock/easyblocks/o/openssl.py | lsuhpchelp/easybuild_smic | train | 0 |
2f3a43ab7610f3425b5a914020cd5e9b7bb41dd5 | [
"SequentialBackoffLemmatizer.__init__(self, backoff)\nRegexpTagger.__init__(self, regexps, backoff)\nself._regexs = regexps",
"for pattern, replace in self._regexs:\n if re.search(pattern, tokens[index]):\n return re.sub(pattern, replace, tokens[index])\n break"
] | <|body_start_0|>
SequentialBackoffLemmatizer.__init__(self, backoff)
RegexpTagger.__init__(self, regexps, backoff)
self._regexs = regexps
<|end_body_0|>
<|body_start_1|>
for pattern, replace in self._regexs:
if re.search(pattern, tokens[index]):
return re.sub... | RegexpLemmatizer | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegexpLemmatizer:
def __init__(self, regexps=None, backoff=None):
"""Setup for RegexpLemmatizer() :param regexps: List of tuples of form (PATTERN, REPLACEMENT) :param backoff: Next lemmatizer in backoff chain."""
<|body_0|>
def choose_lemma(self, tokens, index, history):
... | stack_v2_sparse_classes_36k_train_015376 | 23,254 | permissive | [
{
"docstring": "Setup for RegexpLemmatizer() :param regexps: List of tuples of form (PATTERN, REPLACEMENT) :param backoff: Next lemmatizer in backoff chain.",
"name": "__init__",
"signature": "def __init__(self, regexps=None, backoff=None)"
},
{
"docstring": "Use regular expressions for rules-ba... | 2 | stack_v2_sparse_classes_30k_train_002674 | Implement the Python class `RegexpLemmatizer` described below.
Class description:
Implement the RegexpLemmatizer class.
Method signatures and docstrings:
- def __init__(self, regexps=None, backoff=None): Setup for RegexpLemmatizer() :param regexps: List of tuples of form (PATTERN, REPLACEMENT) :param backoff: Next le... | Implement the Python class `RegexpLemmatizer` described below.
Class description:
Implement the RegexpLemmatizer class.
Method signatures and docstrings:
- def __init__(self, regexps=None, backoff=None): Setup for RegexpLemmatizer() :param regexps: List of tuples of form (PATTERN, REPLACEMENT) :param backoff: Next le... | 085420eaed7055fbcb311714eebb67861fd1b241 | <|skeleton|>
class RegexpLemmatizer:
def __init__(self, regexps=None, backoff=None):
"""Setup for RegexpLemmatizer() :param regexps: List of tuples of form (PATTERN, REPLACEMENT) :param backoff: Next lemmatizer in backoff chain."""
<|body_0|>
def choose_lemma(self, tokens, index, history):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RegexpLemmatizer:
def __init__(self, regexps=None, backoff=None):
"""Setup for RegexpLemmatizer() :param regexps: List of tuples of form (PATTERN, REPLACEMENT) :param backoff: Next lemmatizer in backoff chain."""
SequentialBackoffLemmatizer.__init__(self, backoff)
RegexpTagger.__init__... | the_stack_v2_python_sparse | cltk/lemmatize/latin/backoff.py | jerryfrancis-97/cltk | train | 1 | |
fd9170e9e6144146496359d46112e3f5b2ae8252 | [
"LOG.info('doLogin called {}.'.format(PrettyFormatAny.form(p_json, 'Login From Browser')))\nl_obj = json_tools.decode_json_unicode(p_json)\nl_login_obj = self.validate_user(l_obj)\nl_json = json_tools.encode_json(l_login_obj)\nreturn l_json",
"l_obj = dict(Devices=VALID_DEVICE_TYPES, Families=VALID_FAMILIES, Floo... | <|body_start_0|>
LOG.info('doLogin called {}.'.format(PrettyFormatAny.form(p_json, 'Login From Browser')))
l_obj = json_tools.decode_json_unicode(p_json)
l_login_obj = self.validate_user(l_obj)
l_json = json_tools.encode_json(l_login_obj)
return l_json
<|end_body_0|>
<|body_star... | LoginHelper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoginHelper:
def doLogin(self, p_json):
"""This will receive json of username, password when the user clicks on the login button in the browser. First, we validate the user If valid, display the user and then the root menu. If not - allow the user to retry the login. also allow user to c... | stack_v2_sparse_classes_36k_train_015377 | 10,628 | no_license | [
{
"docstring": "This will receive json of username, password when the user clicks on the login button in the browser. First, we validate the user If valid, display the user and then the root menu. If not - allow the user to retry the login. also allow user to check the change button and apply the change after l... | 3 | stack_v2_sparse_classes_30k_train_013350 | Implement the Python class `LoginHelper` described below.
Class description:
Implement the LoginHelper class.
Method signatures and docstrings:
- def doLogin(self, p_json): This will receive json of username, password when the user clicks on the login button in the browser. First, we validate the user If valid, displ... | Implement the Python class `LoginHelper` described below.
Class description:
Implement the LoginHelper class.
Method signatures and docstrings:
- def doLogin(self, p_json): This will receive json of username, password when the user clicks on the login button in the browser. First, we validate the user If valid, displ... | 8ccbbd1494b7b33ff5099d321cda634fbb254ceb | <|skeleton|>
class LoginHelper:
def doLogin(self, p_json):
"""This will receive json of username, password when the user clicks on the login button in the browser. First, we validate the user If valid, display the user and then the root menu. If not - allow the user to retry the login. also allow user to c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LoginHelper:
def doLogin(self, p_json):
"""This will receive json of username, password when the user clicks on the login button in the browser. First, we validate the user If valid, display the user and then the root menu. If not - allow the user to retry the login. also allow user to check the chang... | the_stack_v2_python_sparse | Project/src/Modules/Computer/Web/web_login.py | bopopescu/PyHouse | train | 0 | |
c99a61c7bfc46362f3fb6b963f683afb4af19c6b | [
"dict = Counter(s)\nif all((dict[i] >= k for i in dict)):\n return len(s)\nstart, longest = (0, 0)\nfor i in xrange(len(s)):\n if dict[s[i]] < k:\n longest = max(longest, self.longestSubstring(s[start:i], k))\n start = i + 1\nlongest = max(longest, self.longestSubstring(s[start:], k))\nreturn lo... | <|body_start_0|>
dict = Counter(s)
if all((dict[i] >= k for i in dict)):
return len(s)
start, longest = (0, 0)
for i in xrange(len(s)):
if dict[s[i]] < k:
longest = max(longest, self.longestSubstring(s[start:i], k))
start = i + 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestSubstring(self, s, k):
""":type s: str :type k: int :rtype: int"""
<|body_0|>
def longestSubstring2(self, s, k):
""":type s: str :type k: int :rtype: int"""
<|body_1|>
def longestSubstring3(self, s, k):
""":type s: str :type ... | stack_v2_sparse_classes_36k_train_015378 | 1,552 | no_license | [
{
"docstring": ":type s: str :type k: int :rtype: int",
"name": "longestSubstring",
"signature": "def longestSubstring(self, s, k)"
},
{
"docstring": ":type s: str :type k: int :rtype: int",
"name": "longestSubstring2",
"signature": "def longestSubstring2(self, s, k)"
},
{
"docst... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestSubstring(self, s, k): :type s: str :type k: int :rtype: int
- def longestSubstring2(self, s, k): :type s: str :type k: int :rtype: int
- def longestSubstring3(self, s... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestSubstring(self, s, k): :type s: str :type k: int :rtype: int
- def longestSubstring2(self, s, k): :type s: str :type k: int :rtype: int
- def longestSubstring3(self, s... | 0fc4c7af59246e3064db41989a45d9db413a624b | <|skeleton|>
class Solution:
def longestSubstring(self, s, k):
""":type s: str :type k: int :rtype: int"""
<|body_0|>
def longestSubstring2(self, s, k):
""":type s: str :type k: int :rtype: int"""
<|body_1|>
def longestSubstring3(self, s, k):
""":type s: str :type ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def longestSubstring(self, s, k):
""":type s: str :type k: int :rtype: int"""
dict = Counter(s)
if all((dict[i] >= k for i in dict)):
return len(s)
start, longest = (0, 0)
for i in xrange(len(s)):
if dict[s[i]] < k:
long... | the_stack_v2_python_sparse | 395. Longest Substring with At Least K Repeating Characters/kRepeating.py | Macielyoung/LeetCode | train | 1 | |
f84234d21e7b4b87200d9b41033382f78d9030e8 | [
"self.datamover_image_location = datamover_image_location\nself.datamover_upgradability = datamover_upgradability\nself.description = description\nself.distribution = distribution\nself.init_container_image_location = init_container_image_location\nself.label_attributes = label_attributes\nself.name = name\nself.mt... | <|body_start_0|>
self.datamover_image_location = datamover_image_location
self.datamover_upgradability = datamover_upgradability
self.description = description
self.distribution = distribution
self.init_container_image_location = init_container_image_location
self.label_a... | Implementation of the 'KubernetesProtectionSource' model. Specifies a Protection Source in Kubernetes environment. Attributes: datamover_image_location (string): Specifies the location of Datamover image in private registry. datamover_upgradability (int): Specifies if the deployed Datamover image needs to be upgraded f... | KubernetesProtectionSource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KubernetesProtectionSource:
"""Implementation of the 'KubernetesProtectionSource' model. Specifies a Protection Source in Kubernetes environment. Attributes: datamover_image_location (string): Specifies the location of Datamover image in private registry. datamover_upgradability (int): Specifies ... | stack_v2_sparse_classes_36k_train_015379 | 6,431 | permissive | [
{
"docstring": "Constructor for the KubernetesProtectionSource class",
"name": "__init__",
"signature": "def __init__(self, datamover_image_location=None, datamover_upgradability=None, description=None, distribution=None, init_container_image_location=None, label_attributes=None, name=None, mtype=None, ... | 2 | null | Implement the Python class `KubernetesProtectionSource` described below.
Class description:
Implementation of the 'KubernetesProtectionSource' model. Specifies a Protection Source in Kubernetes environment. Attributes: datamover_image_location (string): Specifies the location of Datamover image in private registry. da... | Implement the Python class `KubernetesProtectionSource` described below.
Class description:
Implementation of the 'KubernetesProtectionSource' model. Specifies a Protection Source in Kubernetes environment. Attributes: datamover_image_location (string): Specifies the location of Datamover image in private registry. da... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class KubernetesProtectionSource:
"""Implementation of the 'KubernetesProtectionSource' model. Specifies a Protection Source in Kubernetes environment. Attributes: datamover_image_location (string): Specifies the location of Datamover image in private registry. datamover_upgradability (int): Specifies ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KubernetesProtectionSource:
"""Implementation of the 'KubernetesProtectionSource' model. Specifies a Protection Source in Kubernetes environment. Attributes: datamover_image_location (string): Specifies the location of Datamover image in private registry. datamover_upgradability (int): Specifies if the deploy... | the_stack_v2_python_sparse | cohesity_management_sdk/models/kubernetes_protection_source.py | cohesity/management-sdk-python | train | 24 |
3e6acf01ff7930d875752325445aa6c69ed47ff3 | [
"self.mass = mass\nself.n_states = 4\nself.n_inputs = 2\nModel.__init__(self)",
"n_steps = u.shape[1]\nx = np.zeros([4, n_steps + 1])\ndxdt = np.zeros([4, n_steps + 1])\ndxdt[:, 0] = self._diffequation(None, x0, [0, 0])\nx[:, 0] = x0\nfor ids in range(1, n_steps + 1):\n x[:, ids] = self._integrate(x[:, ids - 1... | <|body_start_0|>
self.mass = mass
self.n_states = 4
self.n_inputs = 2
Model.__init__(self)
<|end_body_0|>
<|body_start_1|>
n_steps = u.shape[1]
x = np.zeros([4, n_steps + 1])
dxdt = np.zeros([4, n_steps + 1])
dxdt[:, 0] = self._diffequation(None, x0, [0, ... | FrictionCircle | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FrictionCircle:
def __init__(self, mass, **kwargs):
"""specify model params here"""
<|body_0|>
def sim_continuous(self, x0, u, t):
"""simulates the nonlinear continuous model with given input vector by numerical integration using 6th order Runge Kutta method x0 is th... | stack_v2_sparse_classes_36k_train_015380 | 3,494 | permissive | [
{
"docstring": "specify model params here",
"name": "__init__",
"signature": "def __init__(self, mass, **kwargs)"
},
{
"docstring": "simulates the nonlinear continuous model with given input vector by numerical integration using 6th order Runge Kutta method x0 is the initial state of size 4x1 u ... | 3 | stack_v2_sparse_classes_30k_train_017419 | Implement the Python class `FrictionCircle` described below.
Class description:
Implement the FrictionCircle class.
Method signatures and docstrings:
- def __init__(self, mass, **kwargs): specify model params here
- def sim_continuous(self, x0, u, t): simulates the nonlinear continuous model with given input vector b... | Implement the Python class `FrictionCircle` described below.
Class description:
Implement the FrictionCircle class.
Method signatures and docstrings:
- def __init__(self, mass, **kwargs): specify model params here
- def sim_continuous(self, x0, u, t): simulates the nonlinear continuous model with given input vector b... | 0a23cf950d5ec97c12c373622a4606c2321ad7ed | <|skeleton|>
class FrictionCircle:
def __init__(self, mass, **kwargs):
"""specify model params here"""
<|body_0|>
def sim_continuous(self, x0, u, t):
"""simulates the nonlinear continuous model with given input vector by numerical integration using 6th order Runge Kutta method x0 is th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FrictionCircle:
def __init__(self, mass, **kwargs):
"""specify model params here"""
self.mass = mass
self.n_states = 4
self.n_inputs = 2
Model.__init__(self)
def sim_continuous(self, x0, u, t):
"""simulates the nonlinear continuous model with given input ve... | the_stack_v2_python_sparse | bayes_race/models/frictioncircle.py | lp02781/bayesrace | train | 0 | |
00a16404f30a7f2e6baa4e684ec4435e5ae5287a | [
"self.corpora = self.process_corpora(corporaList, stopwords_f)\nprint('loading pre-trained w2v model...')\ntic = time.time()\nif pretrained_w2v:\n self.w2v_model = pretrained_w2v\nelif w2v_f.endswith('.bin'):\n self.w2v_model = gensim.models.KeyedVectors.load_word2vec_format(w2v_f, binary=True)\nelse:\n se... | <|body_start_0|>
self.corpora = self.process_corpora(corporaList, stopwords_f)
print('loading pre-trained w2v model...')
tic = time.time()
if pretrained_w2v:
self.w2v_model = pretrained_w2v
elif w2v_f.endswith('.bin'):
self.w2v_model = gensim.models.KeyedV... | W2VModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class W2VModel:
def __init__(self, corporaList, w2v_f, stopwords_f, pretrained_w2v=None, saved_corpora_vec_M=None):
"""实现使用语言模型对句子和句子, 词语对句子的匹配. 初始化模型: StatisticModel(corpora) Args: corporaList: 多个语料组成的列表, 应该是一个嵌套Python列表. For example: [["There", "is", "a", "cat"], ["There", "is", "a", "dog"],... | stack_v2_sparse_classes_36k_train_015381 | 8,398 | no_license | [
{
"docstring": "实现使用语言模型对句子和句子, 词语对句子的匹配. 初始化模型: StatisticModel(corpora) Args: corporaList: 多个语料组成的列表, 应该是一个嵌套Python列表. For example: [[\"There\", \"is\", \"a\", \"cat\"], [\"There\", \"is\", \"a\", \"dog\"], [\"There\", \"is\", \"a\", \"wolf\"]] w2v_f: str, 预训练的词向量文件路径 stopwords_f: str, 停用词文件 pretrained_w2v: ge... | 6 | stack_v2_sparse_classes_30k_train_010832 | Implement the Python class `W2VModel` described below.
Class description:
Implement the W2VModel class.
Method signatures and docstrings:
- def __init__(self, corporaList, w2v_f, stopwords_f, pretrained_w2v=None, saved_corpora_vec_M=None): 实现使用语言模型对句子和句子, 词语对句子的匹配. 初始化模型: StatisticModel(corpora) Args: corporaList: 多个... | Implement the Python class `W2VModel` described below.
Class description:
Implement the W2VModel class.
Method signatures and docstrings:
- def __init__(self, corporaList, w2v_f, stopwords_f, pretrained_w2v=None, saved_corpora_vec_M=None): 实现使用语言模型对句子和句子, 词语对句子的匹配. 初始化模型: StatisticModel(corpora) Args: corporaList: 多个... | c2a20a430de197d06dca5ada96160388730a5db5 | <|skeleton|>
class W2VModel:
def __init__(self, corporaList, w2v_f, stopwords_f, pretrained_w2v=None, saved_corpora_vec_M=None):
"""实现使用语言模型对句子和句子, 词语对句子的匹配. 初始化模型: StatisticModel(corpora) Args: corporaList: 多个语料组成的列表, 应该是一个嵌套Python列表. For example: [["There", "is", "a", "cat"], ["There", "is", "a", "dog"],... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class W2VModel:
def __init__(self, corporaList, w2v_f, stopwords_f, pretrained_w2v=None, saved_corpora_vec_M=None):
"""实现使用语言模型对句子和句子, 词语对句子的匹配. 初始化模型: StatisticModel(corpora) Args: corporaList: 多个语料组成的列表, 应该是一个嵌套Python列表. For example: [["There", "is", "a", "cat"], ["There", "is", "a", "dog"], ["There", "is... | the_stack_v2_python_sparse | Models/Word2Vec/API/Word2VecModel.py | JaMesLiMers/Image_Retrieval_Framework_FYP | train | 2 | |
87250cdfec393eac1eae3b9caa25ab05c3452cd3 | [
"mongo = parallel.MongoDBConnection()\nwith mongo:\n db = mongo.connection.get_database(name=config.TEST_DATABASE_NAME)\n db.drop_collection('customers')\n db.drop_collection('products')\n db.drop_collection('rentals')",
"parent_path = Path(__file__).parent\nresult = parallel.import_product_data(paren... | <|body_start_0|>
mongo = parallel.MongoDBConnection()
with mongo:
db = mongo.connection.get_database(name=config.TEST_DATABASE_NAME)
db.drop_collection('customers')
db.drop_collection('products')
db.drop_collection('rentals')
<|end_body_0|>
<|body_start_1... | Test_Mongo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_Mongo:
def setup(self):
"""Fixture to execute before and after tests"""
<|body_0|>
def test_import_data(self):
"""Test the import_data method"""
<|body_1|>
def test_show_available_products(self):
"""Test the show_available_products function"... | stack_v2_sparse_classes_36k_train_015382 | 2,629 | no_license | [
{
"docstring": "Fixture to execute before and after tests",
"name": "setup",
"signature": "def setup(self)"
},
{
"docstring": "Test the import_data method",
"name": "test_import_data",
"signature": "def test_import_data(self)"
},
{
"docstring": "Test the show_available_products f... | 4 | null | Implement the Python class `Test_Mongo` described below.
Class description:
Implement the Test_Mongo class.
Method signatures and docstrings:
- def setup(self): Fixture to execute before and after tests
- def test_import_data(self): Test the import_data method
- def test_show_available_products(self): Test the show_a... | Implement the Python class `Test_Mongo` described below.
Class description:
Implement the Test_Mongo class.
Method signatures and docstrings:
- def setup(self): Fixture to execute before and after tests
- def test_import_data(self): Test the import_data method
- def test_show_available_products(self): Test the show_a... | 99271cd60485bd2e54f8d133c9057a2ccd6c91c2 | <|skeleton|>
class Test_Mongo:
def setup(self):
"""Fixture to execute before and after tests"""
<|body_0|>
def test_import_data(self):
"""Test the import_data method"""
<|body_1|>
def test_show_available_products(self):
"""Test the show_available_products function"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test_Mongo:
def setup(self):
"""Fixture to execute before and after tests"""
mongo = parallel.MongoDBConnection()
with mongo:
db = mongo.connection.get_database(name=config.TEST_DATABASE_NAME)
db.drop_collection('customers')
db.drop_collection('produ... | the_stack_v2_python_sparse | students/DrewSmith/lessons/lesson07/assignment/test_parallel.py | zconn/PythonCert220Assign | train | 2 | |
6d35beec0cbaab2f71b098024e0924ca2482f9b3 | [
"data = self.get_json()\nvote = data.get('vote')\nif vote is None:\n return self.error('Missing required parameter: `vote`')\nwith self.Session() as session:\n classification = session.scalars(Classification.select(session.user_or_token).where(Classification.id == classification_id)).first()\n if classific... | <|body_start_0|>
data = self.get_json()
vote = data.get('vote')
if vote is None:
return self.error('Missing required parameter: `vote`')
with self.Session() as session:
classification = session.scalars(Classification.select(session.user_or_token).where(Classificat... | ClassificationVotesHandler | [
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClassificationVotesHandler:
def post(self, classification_id):
"""--- description: Vote for a classification. tags: - classifications - classification_votes parameters: - in: path name: classification_id required: true schema: type: string description: | ID of classification to indicate ... | stack_v2_sparse_classes_36k_train_015383 | 31,707 | permissive | [
{
"docstring": "--- description: Vote for a classification. tags: - classifications - classification_votes parameters: - in: path name: classification_id required: true schema: type: string description: | ID of classification to indicate the vote for requestBody: content: application/json: schema: type: object ... | 2 | null | Implement the Python class `ClassificationVotesHandler` described below.
Class description:
Implement the ClassificationVotesHandler class.
Method signatures and docstrings:
- def post(self, classification_id): --- description: Vote for a classification. tags: - classifications - classification_votes parameters: - in... | Implement the Python class `ClassificationVotesHandler` described below.
Class description:
Implement the ClassificationVotesHandler class.
Method signatures and docstrings:
- def post(self, classification_id): --- description: Vote for a classification. tags: - classifications - classification_votes parameters: - in... | 161d3532ba3ba059446addcdac58ca96f39e9636 | <|skeleton|>
class ClassificationVotesHandler:
def post(self, classification_id):
"""--- description: Vote for a classification. tags: - classifications - classification_votes parameters: - in: path name: classification_id required: true schema: type: string description: | ID of classification to indicate ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClassificationVotesHandler:
def post(self, classification_id):
"""--- description: Vote for a classification. tags: - classifications - classification_votes parameters: - in: path name: classification_id required: true schema: type: string description: | ID of classification to indicate the vote for r... | the_stack_v2_python_sparse | skyportal/handlers/api/classification.py | skyportal/skyportal | train | 80 | |
4f7d83c3b987f082420462f0dc96e04463c57693 | [
"def inorder(root, result):\n if root:\n inorder(root.left, result)\n result.append(root.val)\n inorder(root.right, result)\nresult = []\ninorder(root, result)\nreturn result",
"result, stack = ([], [])\nwhile True:\n while root:\n stack.append(root)\n root = root.left\n ... | <|body_start_0|>
def inorder(root, result):
if root:
inorder(root.left, result)
result.append(root.val)
inorder(root.right, result)
result = []
inorder(root, result)
return result
<|end_body_0|>
<|body_start_1|>
result,... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def inorderTraversal_recursive(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_0|>
def inorderTraversal_iterative(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def i... | stack_v2_sparse_classes_36k_train_015384 | 1,447 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: List[int]",
"name": "inorderTraversal_recursive",
"signature": "def inorderTraversal_recursive(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: List[int]",
"name": "inorderTraversal_iterative",
"signature": "def inorderTraversal_it... | 2 | stack_v2_sparse_classes_30k_train_019756 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def inorderTraversal_recursive(self, root): :type root: TreeNode :rtype: List[int]
- def inorderTraversal_iterative(self, root): :type root: TreeNode :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def inorderTraversal_recursive(self, root): :type root: TreeNode :rtype: List[int]
- def inorderTraversal_iterative(self, root): :type root: TreeNode :rtype: List[int]
<|skeleto... | 9ac54720f571a4bea09d0cceb0039381a78df9e8 | <|skeleton|>
class Solution:
def inorderTraversal_recursive(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_0|>
def inorderTraversal_iterative(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def inorderTraversal_recursive(self, root):
""":type root: TreeNode :rtype: List[int]"""
def inorder(root, result):
if root:
inorder(root.left, result)
result.append(root.val)
inorder(root.right, result)
result = []
... | the_stack_v2_python_sparse | code/094_binary-tree-inorder-traversal.py | linhdvu14/leetcode-solutions | train | 2 | |
4f364dde2e422c73b664d60a2399b5677a8373ac | [
"self.chunkArray = []\nfor j in range(self.chunksWide):\n pos = []\n for i in range(self.chunksHigh):\n pos.append((i, j))\n self.chunkArray.append(chunk_column.Chunk_Column(pos))",
"for c in self.chunkArray:\n if not c.filled:\n height = image.shape[0]\n width = image.shape[1] / ... | <|body_start_0|>
self.chunkArray = []
for j in range(self.chunksWide):
pos = []
for i in range(self.chunksHigh):
pos.append((i, j))
self.chunkArray.append(chunk_column.Chunk_Column(pos))
<|end_body_0|>
<|body_start_1|>
for c in self.chunkArray... | Vertical mode fills the image with chunk columns and draws from left to right | Mode_Vertical | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Mode_Vertical:
"""Vertical mode fills the image with chunk columns and draws from left to right"""
def _createChunkArray(self):
"""Uses the current state of the class to create a fresh chunk array filled with chunk columns"""
<|body_0|>
def fillNextChunk(self, image):
... | stack_v2_sparse_classes_36k_train_015385 | 1,535 | no_license | [
{
"docstring": "Uses the current state of the class to create a fresh chunk array filled with chunk columns",
"name": "_createChunkArray",
"signature": "def _createChunkArray(self)"
},
{
"docstring": "Take the current chunk array and fill a chunk row if it needs to be done Arguments: image - A p... | 2 | stack_v2_sparse_classes_30k_train_012397 | Implement the Python class `Mode_Vertical` described below.
Class description:
Vertical mode fills the image with chunk columns and draws from left to right
Method signatures and docstrings:
- def _createChunkArray(self): Uses the current state of the class to create a fresh chunk array filled with chunk columns
- de... | Implement the Python class `Mode_Vertical` described below.
Class description:
Vertical mode fills the image with chunk columns and draws from left to right
Method signatures and docstrings:
- def _createChunkArray(self): Uses the current state of the class to create a fresh chunk array filled with chunk columns
- de... | b87c1d826485695565f7f4ff22fb3b78db4f43d0 | <|skeleton|>
class Mode_Vertical:
"""Vertical mode fills the image with chunk columns and draws from left to right"""
def _createChunkArray(self):
"""Uses the current state of the class to create a fresh chunk array filled with chunk columns"""
<|body_0|>
def fillNextChunk(self, image):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Mode_Vertical:
"""Vertical mode fills the image with chunk columns and draws from left to right"""
def _createChunkArray(self):
"""Uses the current state of the class to create a fresh chunk array filled with chunk columns"""
self.chunkArray = []
for j in range(self.chunksWide):
... | the_stack_v2_python_sparse | Python/mode_vertical.py | SNAP-SAPIENT/plotting-time-and-space | train | 0 |
3c0a68e399548287377fbf4f5d4e646524722057 | [
"if not kwargs.get('auth_plugin') and (not kwargs.get('session')):\n kwargs['auth_plugin'] = monitoringclient.get_auth_plugin(*args, **kwargs)\nself.auth_plugin = kwargs.get('auth_plugin')\nself.http_client = monitoringclient._construct_http_client(**kwargs)\nself.alarm_client = self._get_alarm_client(**kwargs)\... | <|body_start_0|>
if not kwargs.get('auth_plugin') and (not kwargs.get('session')):
kwargs['auth_plugin'] = monitoringclient.get_auth_plugin(*args, **kwargs)
self.auth_plugin = kwargs.get('auth_plugin')
self.http_client = monitoringclient._construct_http_client(**kwargs)
self.... | Client for the Ceilometer v2 API. :param session: a keystoneauth session object :type session: keystoneauth1.session.Session :param str service_type: The default service_type for URL discovery :param str service_name: The default service_name for URL discovery :param str interface: The default interface for URL discove... | Client | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Client:
"""Client for the Ceilometer v2 API. :param session: a keystoneauth session object :type session: keystoneauth1.session.Session :param str service_type: The default service_type for URL discovery :param str service_name: The default service_name for URL discovery :param str interface: The... | stack_v2_sparse_classes_36k_train_015386 | 5,420 | permissive | [
{
"docstring": "Initialize a new client for the Ceilometer v2 API.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Get client for alarm manager that redirect to aodh.",
"name": "_get_alarm_client",
"signature": "def _get_alarm_client(**ceilo_kw... | 2 | stack_v2_sparse_classes_30k_train_014681 | Implement the Python class `Client` described below.
Class description:
Client for the Ceilometer v2 API. :param session: a keystoneauth session object :type session: keystoneauth1.session.Session :param str service_type: The default service_type for URL discovery :param str service_name: The default service_name for ... | Implement the Python class `Client` described below.
Class description:
Client for the Ceilometer v2 API. :param session: a keystoneauth session object :type session: keystoneauth1.session.Session :param str service_type: The default service_type for URL discovery :param str service_name: The default service_name for ... | 5e88cf438b4d24b92f996ae31907d44bd736c7f1 | <|skeleton|>
class Client:
"""Client for the Ceilometer v2 API. :param session: a keystoneauth session object :type session: keystoneauth1.session.Session :param str service_type: The default service_type for URL discovery :param str service_name: The default service_name for URL discovery :param str interface: The... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Client:
"""Client for the Ceilometer v2 API. :param session: a keystoneauth session object :type session: keystoneauth1.session.Session :param str service_type: The default service_type for URL discovery :param str service_name: The default service_name for URL discovery :param str interface: The default inte... | the_stack_v2_python_sparse | eclcli/monitoring/monitoringclient/v2/client.py | nttcom/eclcli | train | 32 |
96c25624734842849d8692e57ae6664ebcf59b17 | [
"query = q\nquery = self._build_params_header(params) + query\nif profile:\n cmd = PROFILE_CMD\nelse:\n cmd = RO_QUERY_CMD if read_only else QUERY_CMD\ncommand = [cmd, self.name, query, '--compact']\nif isinstance(timeout, int):\n command.extend(['timeout', timeout])\nelif timeout is not None:\n raise E... | <|body_start_0|>
query = q
query = self._build_params_header(params) + query
if profile:
cmd = PROFILE_CMD
else:
cmd = RO_QUERY_CMD if read_only else QUERY_CMD
command = [cmd, self.name, query, '--compact']
if isinstance(timeout, int):
... | AsyncGraphCommands | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AsyncGraphCommands:
async def query(self, q, params=None, timeout=None, read_only=False, profile=False):
"""Executes a query against the graph. For more information see `GRAPH.QUERY <https://oss.redis.com/redisgraph/master/commands/#graphquery>`_. # noqa Args: q : str The query. params :... | stack_v2_sparse_classes_36k_train_015387 | 10,379 | permissive | [
{
"docstring": "Executes a query against the graph. For more information see `GRAPH.QUERY <https://oss.redis.com/redisgraph/master/commands/#graphquery>`_. # noqa Args: q : str The query. params : dict Query parameters. timeout : int Maximum runtime for read queries in milliseconds. read_only : bool Executes a ... | 4 | stack_v2_sparse_classes_30k_train_009609 | Implement the Python class `AsyncGraphCommands` described below.
Class description:
Implement the AsyncGraphCommands class.
Method signatures and docstrings:
- async def query(self, q, params=None, timeout=None, read_only=False, profile=False): Executes a query against the graph. For more information see `GRAPH.QUERY... | Implement the Python class `AsyncGraphCommands` described below.
Class description:
Implement the AsyncGraphCommands class.
Method signatures and docstrings:
- async def query(self, q, params=None, timeout=None, read_only=False, profile=False): Executes a query against the graph. For more information see `GRAPH.QUERY... | e3de026a90ef2cc35a5b68934029a0ef2a5b2f53 | <|skeleton|>
class AsyncGraphCommands:
async def query(self, q, params=None, timeout=None, read_only=False, profile=False):
"""Executes a query against the graph. For more information see `GRAPH.QUERY <https://oss.redis.com/redisgraph/master/commands/#graphquery>`_. # noqa Args: q : str The query. params :... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AsyncGraphCommands:
async def query(self, q, params=None, timeout=None, read_only=False, profile=False):
"""Executes a query against the graph. For more information see `GRAPH.QUERY <https://oss.redis.com/redisgraph/master/commands/#graphquery>`_. # noqa Args: q : str The query. params : dict Query pa... | the_stack_v2_python_sparse | redis/commands/graph/commands.py | redis/redis-py | train | 2,213 | |
d5080e6bb3d4e0ca3a7a5dc748a7ebc28116f7b6 | [
"super(MultiHeadedAttention, self).__init__()\nassert d_model % h == 0\nself.d_k = d_model // h\nself.h = h\nself.linears = clones(nn.Linear(d_model, d_model), 4)\nself.attn = None\nself.dropout = nn.Dropout(p=dropout)",
"if mask is not None:\n if len(mask.shape) == 3:\n mask = mask.unsqueeze(1)\n el... | <|body_start_0|>
super(MultiHeadedAttention, self).__init__()
assert d_model % h == 0
self.d_k = d_model // h
self.h = h
self.linears = clones(nn.Linear(d_model, d_model), 4)
self.attn = None
self.dropout = nn.Dropout(p=dropout)
<|end_body_0|>
<|body_start_1|>
... | MultiHeadedAttention | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiHeadedAttention:
def __init__(self, h, d_model, dropout=0.1):
"""Take in model size and number of heads."""
<|body_0|>
def forward(self, query, key, value, mask=None):
"""Implements Figure 2"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super... | stack_v2_sparse_classes_36k_train_015388 | 5,977 | no_license | [
{
"docstring": "Take in model size and number of heads.",
"name": "__init__",
"signature": "def __init__(self, h, d_model, dropout=0.1)"
},
{
"docstring": "Implements Figure 2",
"name": "forward",
"signature": "def forward(self, query, key, value, mask=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001850 | Implement the Python class `MultiHeadedAttention` described below.
Class description:
Implement the MultiHeadedAttention class.
Method signatures and docstrings:
- def __init__(self, h, d_model, dropout=0.1): Take in model size and number of heads.
- def forward(self, query, key, value, mask=None): Implements Figure ... | Implement the Python class `MultiHeadedAttention` described below.
Class description:
Implement the MultiHeadedAttention class.
Method signatures and docstrings:
- def __init__(self, h, d_model, dropout=0.1): Take in model size and number of heads.
- def forward(self, query, key, value, mask=None): Implements Figure ... | 05cc5124ac188013f8efda082d67d92a8ed6dbd4 | <|skeleton|>
class MultiHeadedAttention:
def __init__(self, h, d_model, dropout=0.1):
"""Take in model size and number of heads."""
<|body_0|>
def forward(self, query, key, value, mask=None):
"""Implements Figure 2"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiHeadedAttention:
def __init__(self, h, d_model, dropout=0.1):
"""Take in model size and number of heads."""
super(MultiHeadedAttention, self).__init__()
assert d_model % h == 0
self.d_k = d_model // h
self.h = h
self.linears = clones(nn.Linear(d_model, d_mo... | the_stack_v2_python_sparse | 2020000888/src/scripts/model/transformer.py | info-ruc/web21projects | train | 1 | |
f61d606639088dd477963fa8ce5e5effb4675a20 | [
"res = {}\nfor section in config.sections(issuer=request.environ.get('issuer'), vo=request.environ.get('vo')):\n res[section] = {}\n for item in config.items(section, issuer=request.environ.get('issuer'), vo=request.environ.get('vo')):\n res[section][item[0]] = item[1]\nreturn (jsonify(res), 200)",
"... | <|body_start_0|>
res = {}
for section in config.sections(issuer=request.environ.get('issuer'), vo=request.environ.get('vo')):
res[section] = {}
for item in config.items(section, issuer=request.environ.get('issuer'), vo=request.environ.get('vo')):
res[section][item... | REST API for full configuration. | Config | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Config:
"""REST API for full configuration."""
def get(self):
"""--- summary: List description: List the full configuration. tags: - Config responses: 200: description: OK content: application/json: schema: description: A dict with the sections as keys and a dict with the configurati... | stack_v2_sparse_classes_36k_train_015389 | 10,156 | permissive | [
{
"docstring": "--- summary: List description: List the full configuration. tags: - Config responses: 200: description: OK content: application/json: schema: description: A dict with the sections as keys and a dict with the configuration as value. type: object 401: description: Invalid Auth Token 406: descripti... | 2 | stack_v2_sparse_classes_30k_train_013593 | Implement the Python class `Config` described below.
Class description:
REST API for full configuration.
Method signatures and docstrings:
- def get(self): --- summary: List description: List the full configuration. tags: - Config responses: 200: description: OK content: application/json: schema: description: A dict ... | Implement the Python class `Config` described below.
Class description:
REST API for full configuration.
Method signatures and docstrings:
- def get(self): --- summary: List description: List the full configuration. tags: - Config responses: 200: description: OK content: application/json: schema: description: A dict ... | 7f0d229ac0b3bc7dec12c6e158bea2b82d414a3b | <|skeleton|>
class Config:
"""REST API for full configuration."""
def get(self):
"""--- summary: List description: List the full configuration. tags: - Config responses: 200: description: OK content: application/json: schema: description: A dict with the sections as keys and a dict with the configurati... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Config:
"""REST API for full configuration."""
def get(self):
"""--- summary: List description: List the full configuration. tags: - Config responses: 200: description: OK content: application/json: schema: description: A dict with the sections as keys and a dict with the configuration as value. ... | the_stack_v2_python_sparse | lib/rucio/web/rest/flaskapi/v1/config.py | rucio/rucio | train | 232 |
32512d58c594ff7aac5f5b146e5cfcbfb6bca84e | [
"self.label = label\nself.description = description\nself.creation_counter = ModelField.creation_counter\nModelField.creation_counter += 1",
"self.name = name\nif self.label is None:\n self.label = self.name\nif self.description is None:\n self.description = self.label"
] | <|body_start_0|>
self.label = label
self.description = description
self.creation_counter = ModelField.creation_counter
ModelField.creation_counter += 1
<|end_body_0|>
<|body_start_1|>
self.name = name
if self.label is None:
self.label = self.name
if s... | Abstract base class for all field types | ModelField | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModelField:
"""Abstract base class for all field types"""
def __init__(self, label=None, description=None):
""":param str label: text :param str description: verbose description"""
<|body_0|>
def setName(self, name):
"""This method is explicitly called to set the... | stack_v2_sparse_classes_36k_train_015390 | 8,614 | no_license | [
{
"docstring": ":param str label: text :param str description: verbose description",
"name": "__init__",
"signature": "def __init__(self, label=None, description=None)"
},
{
"docstring": "This method is explicitly called to set the field name :param name: field name",
"name": "setName",
... | 2 | null | Implement the Python class `ModelField` described below.
Class description:
Abstract base class for all field types
Method signatures and docstrings:
- def __init__(self, label=None, description=None): :param str label: text :param str description: verbose description
- def setName(self, name): This method is explici... | Implement the Python class `ModelField` described below.
Class description:
Abstract base class for all field types
Method signatures and docstrings:
- def __init__(self, label=None, description=None): :param str label: text :param str description: verbose description
- def setName(self, name): This method is explici... | 91d2eca1e443c5bca0757c5576e86a227c45288c | <|skeleton|>
class ModelField:
"""Abstract base class for all field types"""
def __init__(self, label=None, description=None):
""":param str label: text :param str description: verbose description"""
<|body_0|>
def setName(self, name):
"""This method is explicitly called to set the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ModelField:
"""Abstract base class for all field types"""
def __init__(self, label=None, description=None):
""":param str label: text :param str description: verbose description"""
self.label = label
self.description = description
self.creation_counter = ModelField.creatio... | the_stack_v2_python_sparse | smo/dynamical_models/core/Fields.py | wzzhhh1/SmoWeb | train | 0 |
360344bffecce399a668c5a77d9d76a15d9dd637 | [
"super().__init__(syncthru, name)\nself._name = f'{name} Toner {color}'\nself._color = color\nself._unit_of_measurement = PERCENTAGE\nself._id_suffix = f'_toner_{color}'",
"if self.syncthru.is_online():\n self._attributes = self.syncthru.toner_status().get(self._color, {})\n self._state = self._attributes.g... | <|body_start_0|>
super().__init__(syncthru, name)
self._name = f'{name} Toner {color}'
self._color = color
self._unit_of_measurement = PERCENTAGE
self._id_suffix = f'_toner_{color}'
<|end_body_0|>
<|body_start_1|>
if self.syncthru.is_online():
self._attribute... | Implementation of a Samsung Printer toner sensor platform. | SyncThruTonerSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SyncThruTonerSensor:
"""Implementation of a Samsung Printer toner sensor platform."""
def __init__(self, syncthru, name, color):
"""Initialize the sensor."""
<|body_0|>
def update(self):
"""Get the latest data from SyncThru and update the state."""
<|body... | stack_v2_sparse_classes_36k_train_015391 | 8,262 | permissive | [
{
"docstring": "Initialize the sensor.",
"name": "__init__",
"signature": "def __init__(self, syncthru, name, color)"
},
{
"docstring": "Get the latest data from SyncThru and update the state.",
"name": "update",
"signature": "def update(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001210 | Implement the Python class `SyncThruTonerSensor` described below.
Class description:
Implementation of a Samsung Printer toner sensor platform.
Method signatures and docstrings:
- def __init__(self, syncthru, name, color): Initialize the sensor.
- def update(self): Get the latest data from SyncThru and update the sta... | Implement the Python class `SyncThruTonerSensor` described below.
Class description:
Implementation of a Samsung Printer toner sensor platform.
Method signatures and docstrings:
- def __init__(self, syncthru, name, color): Initialize the sensor.
- def update(self): Get the latest data from SyncThru and update the sta... | ed4ab403deaed9e8c95e0db728477fcb012bf4fa | <|skeleton|>
class SyncThruTonerSensor:
"""Implementation of a Samsung Printer toner sensor platform."""
def __init__(self, syncthru, name, color):
"""Initialize the sensor."""
<|body_0|>
def update(self):
"""Get the latest data from SyncThru and update the state."""
<|body... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SyncThruTonerSensor:
"""Implementation of a Samsung Printer toner sensor platform."""
def __init__(self, syncthru, name, color):
"""Initialize the sensor."""
super().__init__(syncthru, name)
self._name = f'{name} Toner {color}'
self._color = color
self._unit_of_mea... | the_stack_v2_python_sparse | homeassistant/components/syncthru/sensor.py | tchellomello/home-assistant | train | 8 |
ee72026709729badf7a7bc994f10d54b400ae3e4 | [
"super(ImNet, self).__init__(name=name)\nself.dim = dim\nself.in_features = in_features\nself.dimz = dim + in_features\nself.out_features = out_features\nself.num_filters = num_filters\nself.activ = activation\nself.fc0 = layers.Dense(num_filters * 16, name='dense_1')\nself.fc1 = layers.Dense(num_filters * 8, name=... | <|body_start_0|>
super(ImNet, self).__init__(name=name)
self.dim = dim
self.in_features = in_features
self.dimz = dim + in_features
self.out_features = out_features
self.num_filters = num_filters
self.activ = activation
self.fc0 = layers.Dense(num_filters ... | ImNet layer keras implementation. | ImNet | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImNet:
"""ImNet layer keras implementation."""
def __init__(self, dim=3, in_features=128, out_features=1, num_filters=128, activation=tf.nn.leaky_relu, name='im_net'):
"""Initialization. Args: dim: int, dimension of input points. in_features: int, length of input features (i.e., late... | stack_v2_sparse_classes_36k_train_015392 | 2,473 | permissive | [
{
"docstring": "Initialization. Args: dim: int, dimension of input points. in_features: int, length of input features (i.e., latent code). out_features: number of output features. num_filters: int, width of the second to last layer. activation: tf activation op. name: str, name of the layer.",
"name": "__in... | 2 | null | Implement the Python class `ImNet` described below.
Class description:
ImNet layer keras implementation.
Method signatures and docstrings:
- def __init__(self, dim=3, in_features=128, out_features=1, num_filters=128, activation=tf.nn.leaky_relu, name='im_net'): Initialization. Args: dim: int, dimension of input point... | Implement the Python class `ImNet` described below.
Class description:
ImNet layer keras implementation.
Method signatures and docstrings:
- def __init__(self, dim=3, in_features=128, out_features=1, num_filters=128, activation=tf.nn.leaky_relu, name='im_net'): Initialization. Args: dim: int, dimension of input point... | 1b0203eb538f2b6a1013ec7736d0d548416f059a | <|skeleton|>
class ImNet:
"""ImNet layer keras implementation."""
def __init__(self, dim=3, in_features=128, out_features=1, num_filters=128, activation=tf.nn.leaky_relu, name='im_net'):
"""Initialization. Args: dim: int, dimension of input points. in_features: int, length of input features (i.e., late... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ImNet:
"""ImNet layer keras implementation."""
def __init__(self, dim=3, in_features=128, out_features=1, num_filters=128, activation=tf.nn.leaky_relu, name='im_net'):
"""Initialization. Args: dim: int, dimension of input points. in_features: int, length of input features (i.e., latent code). out... | the_stack_v2_python_sparse | tensorflow_graphics/projects/local_implicit_grid/core/implicit_nets.py | tensorflow/graphics | train | 2,920 |
14cae492b75a0012682fbe442aff821ce4c6c089 | [
"goods_json = {}\nad_goods = IndexAd.objects.filter(category_id=obj.id)\nif ad_goods:\n good_ins = ad_goods[0].goods\n goods_json = GoodsSerializer(good_ins, many=False, context={'request': self.context['request']}).data\nreturn goods_json",
"all_goods = Goods.objects.filter(Q(category_id=obj.id) | Q(catego... | <|body_start_0|>
goods_json = {}
ad_goods = IndexAd.objects.filter(category_id=obj.id)
if ad_goods:
good_ins = ad_goods[0].goods
goods_json = GoodsSerializer(good_ins, many=False, context={'request': self.context['request']}).data
return goods_json
<|end_body_0|>
... | 商品类别一对多 这里为 GoodsCategory 是 GoodsCateGoryBrand 的主表,所以这里使用的话需要为many=True 如果是在 BrandSerializer 中需要使用 GoodsCategorySerializer 的话 为副表引用主表 所以 many=False | IndexCategorySerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IndexCategorySerializer:
"""商品类别一对多 这里为 GoodsCategory 是 GoodsCateGoryBrand 的主表,所以这里使用的话需要为many=True 如果是在 BrandSerializer 中需要使用 GoodsCategorySerializer 的话 为副表引用主表 所以 many=False"""
def get_ad_goods(self, obj):
"""显示首页商品类别的信息"""
<|body_0|>
def get_goods(self, obj):
... | stack_v2_sparse_classes_36k_train_015393 | 3,438 | no_license | [
{
"docstring": "显示首页商品类别的信息",
"name": "get_ad_goods",
"signature": "def get_ad_goods(self, obj)"
},
{
"docstring": "对goods 返回的数据进行操作",
"name": "get_goods",
"signature": "def get_goods(self, obj)"
}
] | 2 | stack_v2_sparse_classes_30k_val_001130 | Implement the Python class `IndexCategorySerializer` described below.
Class description:
商品类别一对多 这里为 GoodsCategory 是 GoodsCateGoryBrand 的主表,所以这里使用的话需要为many=True 如果是在 BrandSerializer 中需要使用 GoodsCategorySerializer 的话 为副表引用主表 所以 many=False
Method signatures and docstrings:
- def get_ad_goods(self, obj): 显示首页商品类别的信息
- de... | Implement the Python class `IndexCategorySerializer` described below.
Class description:
商品类别一对多 这里为 GoodsCategory 是 GoodsCateGoryBrand 的主表,所以这里使用的话需要为many=True 如果是在 BrandSerializer 中需要使用 GoodsCategorySerializer 的话 为副表引用主表 所以 many=False
Method signatures and docstrings:
- def get_ad_goods(self, obj): 显示首页商品类别的信息
- de... | 8414da97036aef52c96ae42e6e760bbbc6f64c05 | <|skeleton|>
class IndexCategorySerializer:
"""商品类别一对多 这里为 GoodsCategory 是 GoodsCateGoryBrand 的主表,所以这里使用的话需要为many=True 如果是在 BrandSerializer 中需要使用 GoodsCategorySerializer 的话 为副表引用主表 所以 many=False"""
def get_ad_goods(self, obj):
"""显示首页商品类别的信息"""
<|body_0|>
def get_goods(self, obj):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IndexCategorySerializer:
"""商品类别一对多 这里为 GoodsCategory 是 GoodsCateGoryBrand 的主表,所以这里使用的话需要为many=True 如果是在 BrandSerializer 中需要使用 GoodsCategorySerializer 的话 为副表引用主表 所以 many=False"""
def get_ad_goods(self, obj):
"""显示首页商品类别的信息"""
goods_json = {}
ad_goods = IndexAd.objects.filter(categ... | the_stack_v2_python_sparse | apps/goods/serializers.py | lize240810/Shop | train | 0 |
fe799bfedafa0f3f645c6f952b7238de24bd2941 | [
"rv = self.get(ident)\nif rv is None:\n raise EntityNotFound(self.column_descriptions[0]['name'], ident)\nreturn rv",
"rv = self.first()\nif rv is None:\n raise NoDataFound(self.column_descriptions[0]['name'])\nreturn rv"
] | <|body_start_0|>
rv = self.get(ident)
if rv is None:
raise EntityNotFound(self.column_descriptions[0]['name'], ident)
return rv
<|end_body_0|>
<|body_start_1|>
rv = self.first()
if rv is None:
raise NoDataFound(self.column_descriptions[0]['name'])
... | SQLAlchemy :class:`~sqlalchemy.orm.query.Query` subclass with convenience methods for querying in a web application. This is the default :attr:`~Model.query` object used for models, and exposed as :attr:`~SQLAlchemy.Query`. Override the query class for an individual model by subclassing this and setting :attr:`~Model.q... | BaseQueryJSON | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseQueryJSON:
"""SQLAlchemy :class:`~sqlalchemy.orm.query.Query` subclass with convenience methods for querying in a web application. This is the default :attr:`~Model.query` object used for models, and exposed as :attr:`~SQLAlchemy.Query`. Override the query class for an individual model by sub... | stack_v2_sparse_classes_36k_train_015394 | 11,222 | permissive | [
{
"docstring": "Like :meth:`get` but aborts with 404 if not found instead of returning ``None``.",
"name": "get_or_raise",
"signature": "def get_or_raise(self, ident, description=None)"
},
{
"docstring": "Like :meth:`first` but aborts with 404 if not found instead of returning ``None``.",
"n... | 2 | stack_v2_sparse_classes_30k_train_001038 | Implement the Python class `BaseQueryJSON` described below.
Class description:
SQLAlchemy :class:`~sqlalchemy.orm.query.Query` subclass with convenience methods for querying in a web application. This is the default :attr:`~Model.query` object used for models, and exposed as :attr:`~SQLAlchemy.Query`. Override the que... | Implement the Python class `BaseQueryJSON` described below.
Class description:
SQLAlchemy :class:`~sqlalchemy.orm.query.Query` subclass with convenience methods for querying in a web application. This is the default :attr:`~Model.query` object used for models, and exposed as :attr:`~SQLAlchemy.Query`. Override the que... | 079d7c91a66e10f13510d89844fbadb27e005b40 | <|skeleton|>
class BaseQueryJSON:
"""SQLAlchemy :class:`~sqlalchemy.orm.query.Query` subclass with convenience methods for querying in a web application. This is the default :attr:`~Model.query` object used for models, and exposed as :attr:`~SQLAlchemy.Query`. Override the query class for an individual model by sub... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseQueryJSON:
"""SQLAlchemy :class:`~sqlalchemy.orm.query.Query` subclass with convenience methods for querying in a web application. This is the default :attr:`~Model.query` object used for models, and exposed as :attr:`~SQLAlchemy.Query`. Override the query class for an individual model by subclassing this... | the_stack_v2_python_sparse | dimensigon/web/helpers.py | dimensigon/dimensigon | train | 2 |
93b52d50255d0944601156243d4ecc2c89e57cd7 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | The ClusterControllerService provides methods to manage clusters of Compute Engine instances. | ClusterControllerServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClusterControllerServicer:
"""The ClusterControllerService provides methods to manage clusters of Compute Engine instances."""
def CreateCluster(self, request, context):
"""Creates a cluster in a project. The returned [Operation.metadata][google.longrunning.Operation.metadata] will b... | stack_v2_sparse_classes_36k_train_015395 | 8,019 | permissive | [
{
"docstring": "Creates a cluster in a project. The returned [Operation.metadata][google.longrunning.Operation.metadata] will be [ClusterOperationMetadata](/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#clusteroperationmetadata).",
"name": "CreateCluster",
"signature": "def CreateCluster(self, re... | 6 | null | Implement the Python class `ClusterControllerServicer` described below.
Class description:
The ClusterControllerService provides methods to manage clusters of Compute Engine instances.
Method signatures and docstrings:
- def CreateCluster(self, request, context): Creates a cluster in a project. The returned [Operatio... | Implement the Python class `ClusterControllerServicer` described below.
Class description:
The ClusterControllerService provides methods to manage clusters of Compute Engine instances.
Method signatures and docstrings:
- def CreateCluster(self, request, context): Creates a cluster in a project. The returned [Operatio... | d897d56bce03d1fda98b79afb08264e51d46c421 | <|skeleton|>
class ClusterControllerServicer:
"""The ClusterControllerService provides methods to manage clusters of Compute Engine instances."""
def CreateCluster(self, request, context):
"""Creates a cluster in a project. The returned [Operation.metadata][google.longrunning.Operation.metadata] will b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClusterControllerServicer:
"""The ClusterControllerService provides methods to manage clusters of Compute Engine instances."""
def CreateCluster(self, request, context):
"""Creates a cluster in a project. The returned [Operation.metadata][google.longrunning.Operation.metadata] will be [ClusterOpe... | the_stack_v2_python_sparse | dataproc/google/cloud/dataproc_v1/proto/clusters_pb2_grpc.py | tswast/google-cloud-python | train | 1 |
7df3034f85670b7b140aab0ce933a36a0ab08667 | [
"if subarray_beam_ids is None:\n subarray_beam_ids = []\nif station_ids is None:\n station_ids = []\nif channel_blocks is None:\n channel_blocks = []\nself.interface = interface\nself.subarray_id = subarray_id\nself.subarray_beam_ids = subarray_beam_ids\nself.station_ids = station_ids\nself.channel_blocks ... | <|body_start_0|>
if subarray_beam_ids is None:
subarray_beam_ids = []
if station_ids is None:
station_ids = []
if channel_blocks is None:
channel_blocks = []
self.interface = interface
self.subarray_id = subarray_id
self.subarray_beam_i... | AssignResourcesRequest is the object representation of the JSON argument for an MCCSController.Allocate command. | AllocateRequest | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AllocateRequest:
"""AssignResourcesRequest is the object representation of the JSON argument for an MCCSController.Allocate command."""
def __init__(self, *, interface: Optional[str]=SCHEMA, subarray_id: int, subarray_beam_ids: List[int]=None, station_ids: List[List[int]]=None, channel_block... | stack_v2_sparse_classes_36k_train_015396 | 2,155 | permissive | [
{
"docstring": "Create a new request object for an MCCSController.Allocate command. :param subarray_id: the numeric SubArray ID :param subarray_beam_ids: subarray beam IDs to allocate to the subarray :param station_ids: IDs of stations to allocate :param channel_blocks: channels to allocate :param interface: th... | 2 | stack_v2_sparse_classes_30k_train_010211 | Implement the Python class `AllocateRequest` described below.
Class description:
AssignResourcesRequest is the object representation of the JSON argument for an MCCSController.Allocate command.
Method signatures and docstrings:
- def __init__(self, *, interface: Optional[str]=SCHEMA, subarray_id: int, subarray_beam_i... | Implement the Python class `AllocateRequest` described below.
Class description:
AssignResourcesRequest is the object representation of the JSON argument for an MCCSController.Allocate command.
Method signatures and docstrings:
- def __init__(self, *, interface: Optional[str]=SCHEMA, subarray_id: int, subarray_beam_i... | 87083655aca8f8f53a26dba253a0189d8519714b | <|skeleton|>
class AllocateRequest:
"""AssignResourcesRequest is the object representation of the JSON argument for an MCCSController.Allocate command."""
def __init__(self, *, interface: Optional[str]=SCHEMA, subarray_id: int, subarray_beam_ids: List[int]=None, station_ids: List[List[int]]=None, channel_block... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AllocateRequest:
"""AssignResourcesRequest is the object representation of the JSON argument for an MCCSController.Allocate command."""
def __init__(self, *, interface: Optional[str]=SCHEMA, subarray_id: int, subarray_beam_ids: List[int]=None, station_ids: List[List[int]]=None, channel_blocks: List[int]=... | the_stack_v2_python_sparse | src/ska_tmc_cdm/messages/mccscontroller/allocate.py | ska-telescope/cdm-shared-library | train | 0 |
0947bfb4086125dbae387cac5148d851eacb747c | [
"result = []\nvisited = [False] * len(nums)\n\ndef backtrace(nums, path):\n repeat = []\n if len(path) == len(nums):\n result.append(path[:])\n return\n for i in range(len(nums)):\n if nums[i] in repeat or visited[i] == True:\n continue\n path.append(nums[i])\n ... | <|body_start_0|>
result = []
visited = [False] * len(nums)
def backtrace(nums, path):
repeat = []
if len(path) == len(nums):
result.append(path[:])
return
for i in range(len(nums)):
if nums[i] in repeat or visit... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def permuteUnique(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def permuteUnique0(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
result = []
... | stack_v2_sparse_classes_36k_train_015397 | 2,019 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "permuteUnique",
"signature": "def permuteUnique(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "permuteUnique0",
"signature": "def permuteUnique0(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def permuteUnique(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def permuteUnique0(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 permuteUnique(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def permuteUnique0(self, nums): :type nums: List[int] :rtype: List[List[int]]
<|skeleton|>
class S... | 6e18c5d257840489cc3fb1079ae3804c743982a4 | <|skeleton|>
class Solution:
def permuteUnique(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def permuteUnique0(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def permuteUnique(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
result = []
visited = [False] * len(nums)
def backtrace(nums, path):
repeat = []
if len(path) == len(nums):
result.append(path[:])
... | the_stack_v2_python_sparse | 47.全排列-ii.py | yangyuxiang1996/leetcode | train | 0 | |
54902f81ad1da75c60b558d006f017e583d05fbd | [
"caller_user_id = auth.user_id\nthread_verifications = ThreadVerifications(value=thread_id)\nthread_verifications.verify_user_is_owner(user_id=caller_user_id)\ninvitation_verifications = InvitationVerifications(thread_id=thread_id, value=invitation_id)\ninvitation_verifications.verify_user_is_owner(user_id=caller_u... | <|body_start_0|>
caller_user_id = auth.user_id
thread_verifications = ThreadVerifications(value=thread_id)
thread_verifications.verify_user_is_owner(user_id=caller_user_id)
invitation_verifications = InvitationVerifications(thread_id=thread_id, value=invitation_id)
invitation_ver... | ThreadsThreadIdInvitationsInvitationIdRoute | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThreadsThreadIdInvitationsInvitationIdRoute:
def get(self, thread_id, invitation_id):
"""@api {GET} /threads/<String:thread_id>/invitations/<String:invitation_id> Get sent thread invitation @apiGroup Thread @apiDescription Get sent thread invitation @apiSuccessExample {JSON} Success-Resp... | stack_v2_sparse_classes_36k_train_015398 | 2,684 | permissive | [
{
"docstring": "@api {GET} /threads/<String:thread_id>/invitations/<String:invitation_id> Get sent thread invitation @apiGroup Thread @apiDescription Get sent thread invitation @apiSuccessExample {JSON} Success-Response: { ThreadInvitationModel }",
"name": "get",
"signature": "def get(self, thread_id, i... | 2 | stack_v2_sparse_classes_30k_train_006961 | Implement the Python class `ThreadsThreadIdInvitationsInvitationIdRoute` described below.
Class description:
Implement the ThreadsThreadIdInvitationsInvitationIdRoute class.
Method signatures and docstrings:
- def get(self, thread_id, invitation_id): @api {GET} /threads/<String:thread_id>/invitations/<String:invitati... | Implement the Python class `ThreadsThreadIdInvitationsInvitationIdRoute` described below.
Class description:
Implement the ThreadsThreadIdInvitationsInvitationIdRoute class.
Method signatures and docstrings:
- def get(self, thread_id, invitation_id): @api {GET} /threads/<String:thread_id>/invitations/<String:invitati... | c144c1cb51422095922310d278f80e4996c10ea0 | <|skeleton|>
class ThreadsThreadIdInvitationsInvitationIdRoute:
def get(self, thread_id, invitation_id):
"""@api {GET} /threads/<String:thread_id>/invitations/<String:invitation_id> Get sent thread invitation @apiGroup Thread @apiDescription Get sent thread invitation @apiSuccessExample {JSON} Success-Resp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ThreadsThreadIdInvitationsInvitationIdRoute:
def get(self, thread_id, invitation_id):
"""@api {GET} /threads/<String:thread_id>/invitations/<String:invitation_id> Get sent thread invitation @apiGroup Thread @apiDescription Get sent thread invitation @apiSuccessExample {JSON} Success-Response: { Thread... | the_stack_v2_python_sparse | app_routes/threads/thread_id/invitations/invitation_id/threads_thread_id_invitations_invitation_id_route.py | kskarbinski/threads-api | train | 0 | |
50bf90c6d9dbb376af07ff23ba33e63f21e2dac9 | [
"if not heightMap:\n return 0\nm, n = (len(heightMap), len(heightMap[0]))\nvisited = [[False] * n for _ in range(m)]\nneighbors = [(0, -1), (-1, 0), (0, 1), (1, 0)]\nqueue = []\nfor row in {0, m - 1}:\n for j in range(n):\n heappush(queue, (heightMap[row][j], row, j))\n visited[row][j] = True\nf... | <|body_start_0|>
if not heightMap:
return 0
m, n = (len(heightMap), len(heightMap[0]))
visited = [[False] * n for _ in range(m)]
neighbors = [(0, -1), (-1, 0), (0, 1), (1, 0)]
queue = []
for row in {0, m - 1}:
for j in range(n):
hea... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def trapRainWater(self, heightMap):
""":type heightMap: List[List[int]] :rtype: int"""
<|body_0|>
def trapRainWater2(self, heightMap):
""":type heightMap: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not h... | stack_v2_sparse_classes_36k_train_015399 | 7,145 | no_license | [
{
"docstring": ":type heightMap: List[List[int]] :rtype: int",
"name": "trapRainWater",
"signature": "def trapRainWater(self, heightMap)"
},
{
"docstring": ":type heightMap: List[List[int]] :rtype: int",
"name": "trapRainWater2",
"signature": "def trapRainWater2(self, heightMap)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def trapRainWater(self, heightMap): :type heightMap: List[List[int]] :rtype: int
- def trapRainWater2(self, heightMap): :type heightMap: List[List[int]] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def trapRainWater(self, heightMap): :type heightMap: List[List[int]] :rtype: int
- def trapRainWater2(self, heightMap): :type heightMap: List[List[int]] :rtype: int
<|skeleton|>... | 635af6e22aa8eef8e7920a585d43a45a891a8157 | <|skeleton|>
class Solution:
def trapRainWater(self, heightMap):
""":type heightMap: List[List[int]] :rtype: int"""
<|body_0|>
def trapRainWater2(self, heightMap):
""":type heightMap: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def trapRainWater(self, heightMap):
""":type heightMap: List[List[int]] :rtype: int"""
if not heightMap:
return 0
m, n = (len(heightMap), len(heightMap[0]))
visited = [[False] * n for _ in range(m)]
neighbors = [(0, -1), (-1, 0), (0, 1), (1, 0)]
... | the_stack_v2_python_sparse | code407TrappingRainWaterII.py | cybelewang/leetcode-python | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.