uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e44842078b65fa76a60ff1da | train | function | @receiver(m2m_changed)
def receive_basket_voucher_change(sender, **kwargs):
if kwargs['model'] == Voucher and kwargs['action'] == 'post_add':
voucher_id = list(kwargs['pk_set'])[0]
voucher = Voucher._default_manager.get(pk=voucher_id)
voucher.num_basket_additions += 1
voucher.save()
| @receiver(m2m_changed)
def receive_basket_voucher_change(sender, **kwargs):
| if kwargs['model'] == Voucher and kwargs['action'] == 'post_add':
voucher_id = list(kwargs['pk_set'])[0]
voucher = Voucher._default_manager.get(pk=voucher_id)
voucher.num_basket_additions += 1
voucher.save()
| .db.models.signals import m2m_changed, post_save
from oscar.core.loading import import_module
import_module('offer.models', ['Voucher'], locals())
import_module('order.models', ['OrderDiscount'], locals())
@receiver(m2m_changed)
def receive_basket_voucher_change(sender, **kwargs):
| 64 | 64 | 77 | 19 | 45 | owad/django-oscar | oscar/apps/offer/receivers.py | Python | receive_basket_voucher_change | receive_basket_voucher_change | 8 | 14 | 8 | 9 | 602f47eb9a7b80ed3bb3189e41542853069b5d70 | bigcode/the-stack | train |
db95b3368520c81f8d4e6371 | train | class | class _GetchUnix:
def __init__(self):
import tty, sys
def __call__(self):
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
... | class _GetchUnix:
| def __init__(self):
import tty, sys
def __call__(self):
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr... | character from standard input. Does not echo to the
screen."""
def __init__(self):
try:
self.impl = _GetchWindows()
except ImportError:
self.impl = _GetchUnix()
def __call__(self): return self.impl()
class _GetchUnix:
| 64 | 64 | 100 | 6 | 58 | KaueHBazilli/brainfuck-Interpreter | bf.py | Python | _GetchUnix | _GetchUnix | 22 | 35 | 22 | 22 | c7a36770cc1c9a6378c6013f4811fa3afe0afac9 | bigcode/the-stack | train |
ff8af9838c02bdee48765adc | train | class | class _Getch:
"""Gets a single character from standard input. Does not echo to the
screen."""
def __init__(self):
try:
self.impl = _GetchWindows()
except ImportError:
self.impl = _GetchUnix()
def __call__(self): return self.impl()
| class _Getch:
| """Gets a single character from standard input. Does not echo to the
screen."""
def __init__(self):
try:
self.impl = _GetchWindows()
except ImportError:
self.impl = _GetchUnix()
def __call__(self): return self.impl()
| """A brainfuck interpreter written in Python
by Kauê Hunnicutt Bazilli
"""
import sys
# TODO: Deal with overflow
# Code for reading a single character input
class _Getch:
| 44 | 64 | 68 | 5 | 38 | KaueHBazilli/brainfuck-Interpreter | bf.py | Python | _Getch | _Getch | 10 | 19 | 10 | 10 | 0962a707e1e8eeffd48f44fd2688c9c67b6d916a | bigcode/the-stack | train |
ee20215be477a2882bdd1889 | train | class | class _GetchWindows:
def __init__(self):
import msvcrt
def __call__(self):
import msvcrt
return msvcrt.getch()
| class _GetchWindows:
| def __init__(self):
import msvcrt
def __call__(self):
import msvcrt
return msvcrt.getch()
| ()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
class _GetchWindows:
| 64 | 64 | 40 | 6 | 57 | KaueHBazilli/brainfuck-Interpreter | bf.py | Python | _GetchWindows | _GetchWindows | 38 | 44 | 38 | 38 | ca76ae8646cf0bedd61f23e2ba87755e0e22bc20 | bigcode/the-stack | train |
df57f5678716fc782a34e203 | train | function | @time_kostil.command()
@click.option("-r", "--remote-filter", type=click.Choice(_TIME_CATEGORIES))
@click.option("-l", "--local-filter", type=click.Choice(_TIME_CATEGORIES))
@click.option("-g", "--grep", type=click.Choice(_TIME_CATEGORIES))
@click.option("--grep-size", type=int, default=1)
@click.pass_context
def show(... | @time_kostil.command()
@click.option("-r", "--remote-filter", type=click.Choice(_TIME_CATEGORIES))
@click.option("-l", "--local-filter", type=click.Choice(_TIME_CATEGORIES))
@click.option("-g", "--grep", type=click.Choice(_TIME_CATEGORIES))
@click.option("--grep-size", type=int, default=1)
@click.pass_context
def show(... | coll = _common.get_coll(ctx.obj["mongo_pass"], apply_options=False)
filter_ = _ctx_obj_to_filter(ctx.obj)
if remote_filter is not None:
filter_["category"] = remote_filter
df = pd.DataFrame(
coll.find(filter=filter_, sort=[("date", pymongo.DESCENDING)], limit=ctx.obj["limit"]))
df = ... | timedelta(days=1)}}]
return res
@time_kostil.command()
@click.option("-r", "--remote-filter", type=click.Choice(_TIME_CATEGORIES))
@click.option("-l", "--local-filter", type=click.Choice(_TIME_CATEGORIES))
@click.option("-g", "--grep", type=click.Choice(_TIME_CATEGORIES))
@click.option("--grep-size", type=int, defa... | 107 | 107 | 357 | 95 | 11 | nailbiter/pyassistantbot2 | time.py | Python | show | show | 69 | 98 | 69 | 75 | 7345e5a78af89de802f02a54bee4fe949b999dbc | bigcode/the-stack | train |
7600aed6812d9443fe5e6054 | train | function | @click.group()
@click.option("--mongo_pass", envvar="MONGO_PASS", required=True)
@click.option("-l", "--limit", type=int, default=24*2, envvar="TIME_KOSTIL_LIMIT")
@click.option("-d", "--day", type=click.DateTime(["%Y-%m-%d"]))
@click.pass_context
def time_kostil(ctx, **kwargs):
logging.basicConfig(level=logging.IN... | @click.group()
@click.option("--mongo_pass", envvar="MONGO_PASS", required=True)
@click.option("-l", "--limit", type=int, default=24*2, envvar="TIME_KOSTIL_LIMIT")
@click.option("-d", "--day", type=click.DateTime(["%Y-%m-%d"]))
@click.pass_context
def time_kostil(ctx, **kwargs):
| logging.basicConfig(level=logging.INFO)
ctx.ensure_object(dict)
for k, v in kwargs.items():
ctx.obj[k] = v
| @click.group()
@click.option("--mongo_pass", envvar="MONGO_PASS", required=True)
@click.option("-l", "--limit", type=int, default=24*2, envvar="TIME_KOSTIL_LIMIT")
@click.option("-d", "--day", type=click.DateTime(["%Y-%m-%d"]))
@click.pass_context
def time_kostil(ctx, **kwargs):
| 80 | 64 | 111 | 80 | 0 | nailbiter/pyassistantbot2 | time.py | Python | time_kostil | time_kostil | 45 | 54 | 45 | 50 | 65a1da79ad57f010b2349ac8eeeae5b193823f27 | bigcode/the-stack | train |
5fc3dbbfb02353f27c9303af | train | function | @time_kostil.command()
@click.pass_context
@click.argument("category", type=click.Choice(_TIME_CATEGORIES))
@click.argument("start", type=int)
@click.option("-e", "--endpoint-inclusive", type=int)
def edit(ctx, category, start, endpoint_inclusive):
logger = logging.getLogger("edit")
if endpoint_inclusive is Non... | @time_kostil.command()
@click.pass_context
@click.argument("category", type=click.Choice(_TIME_CATEGORIES))
@click.argument("start", type=int)
@click.option("-e", "--endpoint-inclusive", type=int)
def edit(ctx, category, start, endpoint_inclusive):
| logger = logging.getLogger("edit")
if endpoint_inclusive is None:
endpoint_inclusive = start
assert 0 <= start <= endpoint_inclusive
coll = _common.get_coll(ctx.obj["mongo_pass"])
df = pd.DataFrame(
coll.find(sort=[("date", pymongo.DESCENDING)], limit=ctx.obj["limit"]))
records =... | {grep_cat}\"!")
@time_kostil.command()
@click.pass_context
@click.argument("category", type=click.Choice(_TIME_CATEGORIES))
@click.argument("start", type=int)
@click.option("-e", "--endpoint-inclusive", type=int)
def edit(ctx, category, start, endpoint_inclusive):
| 63 | 64 | 205 | 58 | 5 | nailbiter/pyassistantbot2 | time.py | Python | edit | edit | 101 | 118 | 101 | 106 | e38d70ae3a47a0517c964b68f28d84841d25aaff | bigcode/the-stack | train |
04bc3ce06a2328469710e614 | train | function | def _ctx_obj_to_filter(obj):
res = {}
if obj.get("day", None) is not None:
day = obj["day"]
dt = datetime(day.year, day.month, day.day)
# FIXME: this can be done more robustly, without hardcoding
dt -= timedelta(hours=9)
res["$and"] = [{"date": {"$gte": dt}}, {
... | def _ctx_obj_to_filter(obj):
| res = {}
if obj.get("day", None) is not None:
day = obj["day"]
dt = datetime(day.year, day.month, day.day)
# FIXME: this can be done more robustly, without hardcoding
dt -= timedelta(hours=9)
res["$and"] = [{"date": {"$gte": dt}}, {
"date": {"$lt": dt+timedelt... | click.DateTime(["%Y-%m-%d"]))
@click.pass_context
def time_kostil(ctx, **kwargs):
logging.basicConfig(level=logging.INFO)
ctx.ensure_object(dict)
for k, v in kwargs.items():
ctx.obj[k] = v
def _ctx_obj_to_filter(obj):
| 64 | 64 | 108 | 8 | 55 | nailbiter/pyassistantbot2 | time.py | Python | _ctx_obj_to_filter | _ctx_obj_to_filter | 57 | 66 | 57 | 57 | bc4aef84d7a9e1308188f203bf03a6ef29990167 | bigcode/the-stack | train |
15b0bf436ab6c4439bc9bd69 | train | function | @time_kostil.command()
@click.pass_context
@click.option("-s", "--start", type=click.DateTime())
@click.option("--dry-run/--no-dry-run", default=False)
@click.option("--category", default="useless", type=click.Choice(_TIME_CATEGORIES))
def fix_db(ctx, start, dry_run, category):
coll = _common.get_coll(ctx.obj["mong... | @time_kostil.command()
@click.pass_context
@click.option("-s", "--start", type=click.DateTime())
@click.option("--dry-run/--no-dry-run", default=False)
@click.option("--category", default="useless", type=click.Choice(_TIME_CATEGORIES))
def fix_db(ctx, start, dry_run, category):
| coll = _common.get_coll(ctx.obj["mongo_pass"])
df = pd.DataFrame(
coll.find(
filter={"date": {"$gt": start}},
sort=[("date", pymongo.DESCENDING)],
)
)
datemin = df.date.min()
df.date = df.date.apply(
lambda dt: datemin+timedelta(minutes=((dt-datemin).t... | ESCENDING)], limit=ctx.obj["limit"]))
records = df.to_dict(orient="records")[start:endpoint_inclusive+1]
logger.info(records)
for r in records:
logger.info(f"{r['_id']}: {r['category']} => {category}")
coll.update_one({"_id": r["_id"]}, {"$set": {"category": category}})
@time_kostil.command(... | 153 | 154 | 516 | 72 | 82 | nailbiter/pyassistantbot2 | time.py | Python | fix_db | fix_db | 121 | 171 | 121 | 126 | d2657fb5db60d92257e7a6e0d72f1ad0007e6e0a | bigcode/the-stack | train |
6bc1664ac3f543c38bb470db | train | function | def parse_filename(filepath, conf):
name = os.path.splitext(os.path.basename(filepath))[0]
for mod_cls in conf.options("filepath_re"):
reobj = re.compile(conf["filepath_re"][mod_cls])
mobj = reobj.match(name)
if mobj:
return mobj.groupdict()["host"], mod_cls, mobj.groupdict()... | def parse_filename(filepath, conf):
| name = os.path.splitext(os.path.basename(filepath))[0]
for mod_cls in conf.options("filepath_re"):
reobj = re.compile(conf["filepath_re"][mod_cls])
mobj = reobj.match(name)
if mobj:
return mobj.groupdict()["host"], mod_cls, mobj.groupdict()["id"]
else:
raise Value... | script for configparser-style rule.conf"""
import sys
import os
import re
import json
import configparser
from collections import defaultdict
from amulog import config
from amulog import common
from amulog import host_alias
from logdag.source import src_rrd
def parse_filename(filepath, conf):
| 64 | 64 | 98 | 7 | 56 | cpflat/logdag | scripts/s4_parse_rrdname_old.py | Python | parse_filename | parse_filename | 20 | 28 | 20 | 20 | 8db3904565e96bc023517d48a1f4a4f35daa429b | bigcode/the-stack | train |
166006d7f0b3fbe6c03f1785 | train | function | def generate_json(iter_fp, conf):
ha = host_alias.HostAlias(conf["general"]["host_alias_filename"])
sources = conf.options("source")
d_group = defaultdict(list)
for fp in iter_fp:
try:
tmp_host, mod_cls, mod_id = parse_filename(fp, conf)
host = ha.resolve_host(tmp_host)
... | def generate_json(iter_fp, conf):
| ha = host_alias.HostAlias(conf["general"]["host_alias_filename"])
sources = conf.options("source")
d_group = defaultdict(list)
for fp in iter_fp:
try:
tmp_host, mod_cls, mod_id = parse_filename(fp, conf)
host = ha.resolve_host(tmp_host)
if host is not None:
... | import rrdtool
import numpy as np
from amulog import common
for fp in common.recur_dir(path):
ut_range = [dt.timestamp() for dt in config.getterm(conf, "general", "whole_term")]
try:
robj = src_rrd.fetch(fp, ut_range)
except IOError as e:
sys.stderr(e)
... | 143 | 143 | 477 | 8 | 134 | cpflat/logdag | scripts/s4_parse_rrdname_old.py | Python | generate_json | generate_json | 51 | 107 | 51 | 51 | 2bf090526a835d708c979d9a1c1ea2fc47adf3ee | bigcode/the-stack | train |
966962f01cc3e83b1f7514cb | train | function | def search_valid(conf, path, th=1.0):
import rrdtool
import numpy as np
from amulog import common
for fp in common.recur_dir(path):
ut_range = [dt.timestamp() for dt in config.getterm(conf, "general", "whole_term")]
try:
robj = src_rrd.fetch(fp, ut_range)
except IOErr... | def search_valid(conf, path, th=1.0):
| import rrdtool
import numpy as np
from amulog import common
for fp in common.recur_dir(path):
ut_range = [dt.timestamp() for dt in config.getterm(conf, "general", "whole_term")]
try:
robj = src_rrd.fetch(fp, ut_range)
except IOError as e:
sys.stderr(e)
... | obj = reobj.match(name)
if mobj:
return mobj.groupdict()["host"], mod_cls, mobj.groupdict()["id"]
else:
raise ValueError("RRD filename parsing failure ({0})".format(name))
def search_valid(conf, path, th=1.0):
| 64 | 64 | 149 | 13 | 51 | cpflat/logdag | scripts/s4_parse_rrdname_old.py | Python | search_valid | search_valid | 31 | 48 | 31 | 31 | 7344f75453ccaf8b3098ea70d4cfd8a74925c084 | bigcode/the-stack | train |
4f946f996b2a8ac52f5d98b0 | train | class | class TestMessage:
@staticmethod
def message(id: str = "1234") -> Activity: # pylint: disable=invalid-name
return Activity(
type=ActivityTypes.message,
id=id,
text="test",
from_property=ChannelAccount(id="user", name="User Name"),
recipient=Ch... | class TestMessage:
@staticmethod
| def message(id: str = "1234") -> Activity: # pylint: disable=invalid-name
return Activity(
type=ActivityTypes.message,
id=id,
text="test",
from_property=ChannelAccount(id="user", name="User Name"),
recipient=ChannelAccount(id="bot", name="Bot Name... | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from botbuilder.schema import (
Activity,
ActivityTypes,
ChannelAccount,
ConversationAccount,
)
class TestMessage:
@staticmethod
| 49 | 64 | 114 | 8 | 41 | Fl4v/botbuilder-python | libraries/botbuilder-core/tests/test_message.py | Python | TestMessage | TestMessage | 12 | 24 | 12 | 13 | 779452df6ee638c4136c69f9f3bd872c1acc8287 | bigcode/the-stack | train |
005cdbba356a60153c4c2078 | train | class | class LoadError(Exception):
pass
| class LoadError(Exception):
| pass
| (path):
# Helps OS path handle case where "/" is at the end of path
if path is None:
return None
elif path[:-1] == '/':
return os.path.basename(path[:-1]) + "/"
else:
return os.path.basename(path)
class LoadError(Exception):
| 64 | 64 | 8 | 5 | 59 | shots47s/boutiques | tools/python/boutiques/util/utils.py | Python | LoadError | LoadError | 17 | 18 | 17 | 17 | 35b6a1e9560893de848b89b0bf9ccaee5764a202 | bigcode/the-stack | train |
70dca9064fcb6e4712a717d4 | train | function | def loadJson(userInput, verbose=False):
# Check for JSON file (local or from Zenodo)
json_file = None
if os.path.isfile(userInput):
json_file = userInput
elif userInput.split(".")[0].lower() == "zenodo":
from boutiques.puller import Puller
puller = Puller([userInput], verbose)
... | def loadJson(userInput, verbose=False):
# Check for JSON file (local or from Zenodo)
| json_file = None
if os.path.isfile(userInput):
json_file = userInput
elif userInput.split(".")[0].lower() == "zenodo":
from boutiques.puller import Puller
puller = Puller([userInput], verbose)
json_file = puller.pull()[0]
if json_file is not None:
with open(json_f... | :
return os.path.basename(path)
class LoadError(Exception):
pass
# Helper function that loads the JSON object coming from either a string,
# a local file or a file pulled from Zenodo
def loadJson(userInput, verbose=False):
# Check for JSON file (local or from Zenodo)
| 64 | 64 | 201 | 22 | 41 | shots47s/boutiques | tools/python/boutiques/util/utils.py | Python | loadJson | loadJson | 23 | 43 | 23 | 24 | 0c68c413151e2375509cfc4d7c3f80bc034d6fe3 | bigcode/the-stack | train |
1d4813a97339a0f7c845a8b9 | train | function | def extractFileName(path):
# Helps OS path handle case where "/" is at the end of path
if path is None:
return None
elif path[:-1] == '/':
return os.path.basename(path[:-1]) + "/"
else:
return os.path.basename(path)
| def extractFileName(path):
# Helps OS path handle case where "/" is at the end of path
| if path is None:
return None
elif path[:-1] == '/':
return os.path.basename(path[:-1]) + "/"
else:
return os.path.basename(path)
| import os
import simplejson as json
from boutiques.logger import raise_error
# Parses absolute path into filename
def extractFileName(path):
# Helps OS path handle case where "/" is at the end of path
| 45 | 64 | 63 | 22 | 22 | shots47s/boutiques | tools/python/boutiques/util/utils.py | Python | extractFileName | extractFileName | 7 | 14 | 7 | 8 | fceb13abd67a683e01cc10ed65d73bd7f5c3bab5 | bigcode/the-stack | train |
746232280c86f976fe429efa | train | function | def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
| def read(fname):
| return open(os.path.join(os.path.dirname(__file__), fname)).read()
| :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Environment :: Web Environment',
'Development Status :: 4 - Beta',
]
def read(fname):
| 64 | 64 | 20 | 4 | 60 | rrader/aio_pybars | setup.py | Python | read | read | 18 | 19 | 18 | 18 | 25140daff2d7629339d0ed0f8504d53a5ea3d9b3 | bigcode/the-stack | train |
4cb54025bb225cc8a740b10a | train | function | @pytest.fixture(scope="session")
def init_variables_1839():
from src.leetcode_1839_longest_substring_of_all_vowels_in_order import Solution
solution = Solution()
def _init_variables_1839():
return solution
yield _init_variables_1839
| @pytest.fixture(scope="session")
def init_variables_1839():
| from src.leetcode_1839_longest_substring_of_all_vowels_in_order import Solution
solution = Solution()
def _init_variables_1839():
return solution
yield _init_variables_1839
| #!/usr/bin/env python
import pytest
"""
Test 1839. Longest Substring Of All Vowels in Order
"""
@pytest.fixture(scope="session")
def init_variables_1839():
| 40 | 64 | 60 | 13 | 27 | sungho-joo/leetcode2github | tests/test_1839.py | Python | init_variables_1839 | init_variables_1839 | 10 | 19 | 10 | 11 | df6fae3255b6f933ebde2454994307177ef1d3f6 | bigcode/the-stack | train |
9436f5d84b9d83786a6c52b6 | train | class | class TestClass1839:
def test_solution_0(self, init_variables_1839):
assert init_variables_1839().longestBeautifulSubstring("aeiaaioaaaaeiiiiouuuooaauuaeiu") == 13
def test_solution_1(self, init_variables_1839):
assert init_variables_1839().longestBeautifulSubstring("aeeeiiiioooauuuaeiou") == 5... | class TestClass1839:
| def test_solution_0(self, init_variables_1839):
assert init_variables_1839().longestBeautifulSubstring("aeiaaioaaaaeiiiiouuuooaauuaeiu") == 13
def test_solution_1(self, init_variables_1839):
assert init_variables_1839().longestBeautifulSubstring("aeeeiiiioooauuuaeiou") == 5
def test_soluti... | (scope="session")
def init_variables_1839():
from src.leetcode_1839_longest_substring_of_all_vowels_in_order import Solution
solution = Solution()
def _init_variables_1839():
return solution
yield _init_variables_1839
class TestClass1839:
| 64 | 64 | 127 | 6 | 57 | sungho-joo/leetcode2github | tests/test_1839.py | Python | TestClass1839 | TestClass1839 | 22 | 30 | 22 | 22 | 24359d16b3db25d6618f1916fdec165bbfa8e11a | bigcode/the-stack | train |
c5aabe20a4d4469823ed7bc8 | train | class | class TestClass1839:
def test_solution_0(self, init_variables_1839):
assert init_variables_1839().longestBeautifulSubstring("aeiaaioaaaaeiiiiouuuooaauuaeiu") == 13
def test_solution_1(self, init_variables_1839):
assert init_variables_1839().longestBeautifulSubstring("aeeeiiiioooauuuaeiou") == 5... | class TestClass1839:
| def test_solution_0(self, init_variables_1839):
assert init_variables_1839().longestBeautifulSubstring("aeiaaioaaaaeiiiiouuuooaauuaeiu") == 13
def test_solution_1(self, init_variables_1839):
assert init_variables_1839().longestBeautifulSubstring("aeeeiiiioooauuuaeiou") == 5
def test_soluti... | (scope="session")
def init_variables_1839():
from src.leetcode_1839_longest_substring_of_all_vowels_in_order import Solution
solution = Solution()
def _init_variables_1839():
return solution
yield _init_variables_1839
class TestClass1839:
| 64 | 64 | 127 | 6 | 57 | sungho-joo/leetcode2github | tests/test_1839.py | Python | TestClass1839 | TestClass1839 | 54 | 62 | 54 | 54 | 24359d16b3db25d6618f1916fdec165bbfa8e11a | bigcode/the-stack | train |
76f20e74bfd447b404ce4917 | train | function | @pytest.fixture(scope="session")
def init_variables_1839():
from src.leetcode_1839_longest_substring_of_all_vowels_in_order import Solution
solution = Solution()
def _init_variables_1839():
return solution
yield _init_variables_1839
| @pytest.fixture(scope="session")
def init_variables_1839():
| from src.leetcode_1839_longest_substring_of_all_vowels_in_order import Solution
solution = Solution()
def _init_variables_1839():
return solution
yield _init_variables_1839
| _variables_1839):
assert init_variables_1839().longestBeautifulSubstring("a") == 0
#!/usr/bin/env python
import pytest
"""
Test 1839. Longest Substring Of All Vowels in Order
"""
@pytest.fixture(scope="session")
def init_variables_1839():
| 64 | 64 | 60 | 13 | 51 | sungho-joo/leetcode2github | tests/test_1839.py | Python | init_variables_1839 | init_variables_1839 | 42 | 51 | 42 | 43 | df6fae3255b6f933ebde2454994307177ef1d3f6 | bigcode/the-stack | train |
e131fba34cb0c89025366531 | train | class | class TestBrandForm(TestCase):
"""
A class for testing checkout forms
"""
def test_add_brand_form(self):
"""
This test tests the order form object
"""
testform = BrandForm({
'name': 'testbrand',
'friendly_name': 'Test Brand'
})
... | class TestBrandForm(TestCase):
| """
A class for testing checkout forms
"""
def test_add_brand_form(self):
"""
This test tests the order form object
"""
testform = BrandForm({
'name': 'testbrand',
'friendly_name': 'Test Brand'
})
self.assertTrue(testform.is_va... | # IMPORTS
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Third party
from django.test import TestCase
# Internal
from .forms import BrandForm
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class TestBrandForm(TestCase):
| 46 | 64 | 75 | 7 | 38 | TaraRhoseyn/CI_MS4_Kicks | brands/test_forms.py | Python | TestBrandForm | TestBrandForm | 12 | 25 | 12 | 12 | 00f708f4467803f7c375d225c5928405f1697e6b | bigcode/the-stack | train |
d0d5c70f255d466f38345f88 | train | function | def findcontainer(dir,keyword): # search all files in a directory for a specific container image keyword
global container_count
for file in os.listdir(dir):
path = dir + "/" + file
try :
if os.path.isdir(path):
findcontainer(path, keyword)
else:
if keyword in open(path)... | def findcontainer(dir,keyword): # search all files in a directory for a specific container image keyword
| global container_count
for file in os.listdir(dir):
path = dir + "/" + file
try :
if os.path.isdir(path):
findcontainer(path, keyword)
else:
if keyword in open(path).read():
print(path)
container_count = container_count +1
except Exception as... | import os
import re
# this script can be used to search a local git repository for static assignments of IP addresses and container images
container_count = 0
ip_count = 0
def findcontainer(dir,keyword): # search all files in a directory for a specific container image keyword
| 61 | 64 | 100 | 21 | 39 | stevenplatt/mina-protocol | tools/dependency_search.py | Python | findcontainer | findcontainer | 8 | 23 | 8 | 8 | 9af7f816eb01edf4b10a05bbedcde38456871326 | bigcode/the-stack | train |
8720480d936dcd160d3ecd56 | train | class | class StockDay(Base):
id = Column(
BigIntegerType,
Sequence("id_seq"),
primary_key=True,
autoincrement=True,
unique=True,
)
close = Column(Float)
date = Column(DateTime)
high = Column(Float)
low = Column(Float)
open = Column(Float)
volume = Column(... | class StockDay(Base):
| id = Column(
BigIntegerType,
Sequence("id_seq"),
primary_key=True,
autoincrement=True,
unique=True,
)
close = Column(Float)
date = Column(DateTime)
high = Column(Float)
low = Column(Float)
open = Column(Float)
volume = Column(BigIntegerType)
s... | .base_class import Base, BigIntegerType
class Stock(Base):
ticker = Column(String(10), primary_key=True)
stock_days = relationship("StockDay", back_populates="stocks")
def __repr__(self):
return f"<Stock {self.ticker}>"
class StockDay(Base):
| 63 | 64 | 136 | 5 | 58 | ccortezaguilera/StockAnalysis | stockanalysis/models/stock.py | Python | StockDay | StockDay | 15 | 34 | 15 | 15 | 5a4af914e28cbab9792811ab4ae75f56168de6ad | bigcode/the-stack | train |
37dd8c2f950460cf40c8c9fb | train | class | class Stock(Base):
ticker = Column(String(10), primary_key=True)
stock_days = relationship("StockDay", back_populates="stocks")
def __repr__(self):
return f"<Stock {self.ticker}>"
| class Stock(Base):
| ticker = Column(String(10), primary_key=True)
stock_days = relationship("StockDay", back_populates="stocks")
def __repr__(self):
return f"<Stock {self.ticker}>"
| from sqlalchemy import Column, DateTime, Float, ForeignKey, Sequence, String
from sqlalchemy.orm import relationship
from stockanalysis.db.base_class import Base, BigIntegerType
class Stock(Base):
| 40 | 64 | 49 | 4 | 35 | ccortezaguilera/StockAnalysis | stockanalysis/models/stock.py | Python | Stock | Stock | 7 | 12 | 7 | 7 | bd30d2220444911b004e0f8b61e21215c2c741e9 | bigcode/the-stack | train |
1445934b1088487fb43015fc | train | class | class QuantumWorkspacePaged(Paged):
"""
A paging container for iterating over a list of :class:`QuantumWorkspace <azure.quantum.models.QuantumWorkspace>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[QuantumWork... | class QuantumWorkspacePaged(Paged):
| """
A paging container for iterating over a list of :class:`QuantumWorkspace <azure.quantum.models.QuantumWorkspace>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[QuantumWorkspace]'}
}
def __init__(sel... | See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.paging import Paged... | 64 | 64 | 112 | 7 | 56 | Mannan2812/azure-cli-extensions | src/quantum/azext_quantum/vendored_sdks/azure_mgmt_quantum/models/quantum_workspace_paged.py | Python | QuantumWorkspacePaged | QuantumWorkspacePaged | 15 | 27 | 15 | 15 | 5f527d3c49ae70ae743cb7c45de8fd7fea7ee773 | bigcode/the-stack | train |
b2928a2c62e0e661554a1939 | train | class | class InternetExplorerFix(object):
"""This middleware fixes a couple of bugs with Microsoft Internet
Explorer. Currently the following fixes are applied:
- removing of `Vary` headers for unsupported mimetypes which
causes troubles with caching. Can be disabled by passing
``fix_vary=Fals... | class InternetExplorerFix(object):
| """This middleware fixes a couple of bugs with Microsoft Internet
Explorer. Currently the following fixes are applied:
- removing of `Vary` headers for unsupported mimetypes which
causes troubles with caching. Can be disabled by passing
``fix_vary=False`` to the constructor.
see... | def __init__(self, app, remove_headers=None, add_headers=None):
warnings.warn(
"'HeaderRewriterFix' is deprecated as of version 0.15 and"
" will be removed in version 1.0.",
DeprecationWarning,
stacklevel=2,
)
self.app = app
self.remove... | 195 | 195 | 650 | 6 | 189 | monicaoyugi/News-Updates | virtual/lib/python3.6/site-packages/werkzeug/contrib/fixers.py | Python | InternetExplorerFix | InternetExplorerFix | 188 | 262 | 188 | 188 | 9b70dbc19ce27c91c8cc374240ef1bf435989f9b | bigcode/the-stack | train |
59969d98c47b42bf66d546aa | train | class | class HeaderRewriterFix(object):
"""This middleware can remove response headers and add others. This
is for example useful to remove the `Date` header from responses if you
are using a server that adds that header, no matter if it's present or
not or to add `X-Powered-By` headers::
app = Heade... | class HeaderRewriterFix(object):
| """This middleware can remove response headers and add others. This
is for example useful to remove the `Date` header from responses if you
are using a server that adds that header, no matter if it's present or
not or to add `X-Powered-By` headers::
app = HeaderRewriterFix(app, remove_headers=... | 1.0.
"""
def __init__(self, *args, **kwargs):
warnings.warn(
"'werkzeug.contrib.fixers.ProxyFix' has moved to 'werkzeug"
".middleware.proxy_fix.ProxyFix'. This import is deprecated"
" as of version 0.15 and will be removed in 1.0.",
DeprecationWarning,
... | 109 | 109 | 365 | 7 | 102 | monicaoyugi/News-Updates | virtual/lib/python3.6/site-packages/werkzeug/contrib/fixers.py | Python | HeaderRewriterFix | HeaderRewriterFix | 146 | 185 | 146 | 146 | 0d1f7f30e493ba087a52be4683bc4e528e4c438f | bigcode/the-stack | train |
0228edb766516fe2ca5f43d3 | train | class | class PathInfoFromRequestUriFix(object):
"""On windows environment variables are limited to the system charset
which makes it impossible to store the `PATH_INFO` variable in the
environment without loss of information on some systems.
This is for example a problem for CGI scripts on a Windows Apache.
... | class PathInfoFromRequestUriFix(object):
| """On windows environment variables are limited to the system charset
which makes it impossible to store the `PATH_INFO` variable in the
environment without loss of information on some systems.
This is for example a problem for CGI scripts on a Windows Apache.
This fixer works by recreating the `P... | ootFix(CGIRootFix):
def __init__(self, *args, **kwargs):
warnings.warn(
"'LighttpdCGIRootFix' is renamed 'CGIRootFix'. Both will be"
" removed in version 1.0.",
DeprecationWarning,
stacklevel=2,
)
super(LighttpdCGIRootFix, self).__init__(*args,... | 99 | 99 | 330 | 9 | 90 | monicaoyugi/News-Updates | virtual/lib/python3.6/site-packages/werkzeug/contrib/fixers.py | Python | PathInfoFromRequestUriFix | PathInfoFromRequestUriFix | 88 | 124 | 88 | 88 | f6012a9a09c27943c00b0148b604fd8e40677a00 | bigcode/the-stack | train |
7534721a89287ef61d146e7a | train | class | class CGIRootFix(object):
"""Wrap the application in this middleware if you are using FastCGI
or CGI and you have problems with your app root being set to the CGI
script's path instead of the path users are going to visit.
:param app: the WSGI application
:param app_root: Defaulting to ``'/'``, you... | class CGIRootFix(object):
| """Wrap the application in this middleware if you are using FastCGI
or CGI and you have problems with your app root being set to the CGI
script's path instead of the path users are going to visit.
:param app: the WSGI application
:param app_root: Defaulting to ``'/'``, you can set this to
s... | ResponseCacheControl
from ..http import parse_cache_control_header
from ..http import parse_options_header
from ..http import parse_set_header
from ..middleware.proxy_fix import ProxyFix as _ProxyFix
from ..useragents import UserAgent
try:
from urllib.parse import unquote
except ImportError:
from urllib impor... | 78 | 78 | 262 | 7 | 70 | monicaoyugi/News-Updates | virtual/lib/python3.6/site-packages/werkzeug/contrib/fixers.py | Python | CGIRootFix | CGIRootFix | 45 | 74 | 45 | 45 | a25557e798614d1d375a1b9ea5de586b4e764533 | bigcode/the-stack | train |
590aa0ce0def25fdcf62fdb5 | train | class | class LighttpdCGIRootFix(CGIRootFix):
def __init__(self, *args, **kwargs):
warnings.warn(
"'LighttpdCGIRootFix' is renamed 'CGIRootFix'. Both will be"
" removed in version 1.0.",
DeprecationWarning,
stacklevel=2,
)
super(LighttpdCGIRootFix, sel... | class LighttpdCGIRootFix(CGIRootFix):
| def __init__(self, *args, **kwargs):
warnings.warn(
"'LighttpdCGIRootFix' is renamed 'CGIRootFix'. Both will be"
" removed in version 1.0.",
DeprecationWarning,
stacklevel=2,
)
super(LighttpdCGIRootFix, self).__init__(*args, **kwargs)
| )
self.app = app
self.app_root = app_root.strip("/")
def __call__(self, environ, start_response):
environ["SCRIPT_NAME"] = self.app_root
return self.app(environ, start_response)
class LighttpdCGIRootFix(CGIRootFix):
| 64 | 64 | 96 | 13 | 51 | monicaoyugi/News-Updates | virtual/lib/python3.6/site-packages/werkzeug/contrib/fixers.py | Python | LighttpdCGIRootFix | LighttpdCGIRootFix | 77 | 85 | 77 | 77 | f24de3dd4e7229058c3b9905ba8ad64f583ba42e | bigcode/the-stack | train |
a89f1aed407475ffcfe701dc | train | class | class ProxyFix(_ProxyFix):
"""
.. deprecated:: 0.15
``werkzeug.contrib.fixers.ProxyFix`` has moved to
:mod:`werkzeug.middleware.proxy_fix`. This import will be
removed in 1.0.
"""
def __init__(self, *args, **kwargs):
warnings.warn(
"'werkzeug.contrib.fixers.P... | class ProxyFix(_ProxyFix):
| """
.. deprecated:: 0.15
``werkzeug.contrib.fixers.ProxyFix`` has moved to
:mod:`werkzeug.middleware.proxy_fix`. This import will be
removed in 1.0.
"""
def __init__(self, *args, **kwargs):
warnings.warn(
"'werkzeug.contrib.fixers.ProxyFix' has moved to 'werk... | _name = unquote(environ.get("SCRIPT_NAME", ""))
if request_uri.startswith(script_name):
environ["PATH_INFO"] = request_uri[len(script_name) :].split("?", 1)[0]
break
return self.app(environ, start_response)
class ProxyFix(_ProxyFix):
| 64 | 64 | 152 | 7 | 57 | monicaoyugi/News-Updates | virtual/lib/python3.6/site-packages/werkzeug/contrib/fixers.py | Python | ProxyFix | ProxyFix | 127 | 143 | 127 | 127 | 708a6d39dd737d7c4be2f4cbc1ec16bedb65ff1c | bigcode/the-stack | train |
74f32d5b56f89d8879e9ff30 | train | function | def make_classification_neural_network(
train_features: np.ndarray,
train_labels: np.ndarray,
test_features: np.ndarray,
test_labels: np.ndarray,
) -> Tuple[nn.Module, float, Tuple[torch.Tensor, torch.Tensor]]:
"""Runs the full classification pipeline with a neural network
Args:
train_f... | def make_classification_neural_network(
train_features: np.ndarray,
train_labels: np.ndarray,
test_features: np.ndarray,
test_labels: np.ndarray,
) -> Tuple[nn.Module, float, Tuple[torch.Tensor, torch.Tensor]]:
| """Runs the full classification pipeline with a neural network
Args:
train_features (np.ndarray): Train features
train_labels (np.ndarray): Train labels
test_features (np.ndarray): Test features
test_labels (np.ndarray): Test labels
Returns:
Tuple[nn.Module, float, ... | = DataLoader(train_dataset, batch_size=32, shuffle=True)
test_dataset = TensorDataset(test_tensor_features, test_tensor_labels)
test_loader = DataLoader(test_dataset, batch_size=1, shuffle=False)
return train_loader, test_loader, (mean, std)
def make_classification_neural_network(
train_features: np.n... | 111 | 111 | 373 | 53 | 58 | maximecharpentierdata/link-prediction | src/classification/nn.py | Python | make_classification_neural_network | make_classification_neural_network | 135 | 177 | 135 | 140 | 3027bca608f2ddce874d260e34dde5463e4ed05b | bigcode/the-stack | train |
9838acf6845bd52af429bee3 | train | function | def _train(
dataloader: DataLoader,
model: nn.Module,
loss_fn: Callable,
optimizer: torch.optim.Optimizer,
) -> List[float]:
"""Train function for one epoch
Args:
dataloader (DataLoader): Dataloader
model (nn.Module): Model
loss_fn (Callable): Loss function
optim... | def _train(
dataloader: DataLoader,
model: nn.Module,
loss_fn: Callable,
optimizer: torch.optim.Optimizer,
) -> List[float]:
| """Train function for one epoch
Args:
dataloader (DataLoader): Dataloader
model (nn.Module): Model
loss_fn (Callable): Loss function
optimizer (torch.optim.Optimizer): Optimizer
Returns:
List[float]: Losses
"""
model.train()
losses = []
for batch, (X... | Dataset
from tqdm import tqdm
from src.classification.utils import _generate_submission_data, _show_roc_and_f1
def _train(
dataloader: DataLoader,
model: nn.Module,
loss_fn: Callable,
optimizer: torch.optim.Optimizer,
) -> List[float]:
| 64 | 64 | 191 | 38 | 25 | maximecharpentierdata/link-prediction | src/classification/nn.py | Python | _train | _train | 12 | 43 | 12 | 17 | 64962b19c8da791ad683cedddc69d48a0b18bac2 | bigcode/the-stack | train |
2bc4005ad65482de6ac987f7 | train | function | def _test(dataloader: DataLoader, model: nn.Module, loss_fn: Callable) -> List[float]:
"""Test function for one epoch
Args:
dataloader (DataLoader): Dataloader
model (nn.Module): Model
loss_fn (Callable): Loss function
Returns:
List[float]: Test losses
"""
model.eva... | def _test(dataloader: DataLoader, model: nn.Module, loss_fn: Callable) -> List[float]:
| """Test function for one epoch
Args:
dataloader (DataLoader): Dataloader
model (nn.Module): Model
loss_fn (Callable): Loss function
Returns:
List[float]: Test losses
"""
model.eval()
losses = []
for batch, (X, y) in tqdm(enumerate(dataloader), total=len(data... | )
# Backpropagation
optimizer.zero_grad()
loss.backward()
optimizer.step()
if batch % 100 == 0:
losses.append(loss.item())
return losses
def _test(dataloader: DataLoader, model: nn.Module, loss_fn: Callable) -> List[float]:
| 64 | 64 | 147 | 24 | 39 | maximecharpentierdata/link-prediction | src/classification/nn.py | Python | _test | _test | 46 | 66 | 46 | 46 | 6b374e6a5a396aec1b3a4a76eb83cb99400d4db0 | bigcode/the-stack | train |
894c30959ee11ee49b891f2c | train | function | def prepare_data_for_neural_networks(
train_features: np.ndarray,
train_labels: np.ndarray,
test_features: np.ndarray,
test_labels: np.ndarray,
) -> Tuple[DataLoader, DataLoader, Tuple[torch.Tensor, torch.Tensor]]:
"""Prepares data for the training of the neural network classifier
Args:
... | def prepare_data_for_neural_networks(
train_features: np.ndarray,
train_labels: np.ndarray,
test_features: np.ndarray,
test_labels: np.ndarray,
) -> Tuple[DataLoader, DataLoader, Tuple[torch.Tensor, torch.Tensor]]:
| """Prepares data for the training of the neural network classifier
Args:
train_features (np.ndarray): Train features
train_labels (np.ndarray): Train labels
test_features (np.ndarray): Test features
test_labels (np.ndarray): Test labels
Returns:
Tuple[DataLoader, Da... | 50),
nn.ReLU(),
nn.Linear(50, 1),
nn.Sigmoid(),
)
optimizer = torch.optim.Adam(model.parameters())
loss_fn = nn.BCELoss()
return model, optimizer, loss_fn
def prepare_data_for_neural_networks(
train_features: np.ndarray,
train_labels: np.ndarray,
test_features: np.nd... | 107 | 107 | 357 | 55 | 51 | maximecharpentierdata/link-prediction | src/classification/nn.py | Python | prepare_data_for_neural_networks | prepare_data_for_neural_networks | 94 | 132 | 94 | 99 | 4f41e07a84e0a7adc1c28f38be91e11e54289366 | bigcode/the-stack | train |
b3eafb79e1a9c6a1fa593b28 | train | function | def generate_submission_data_for_neural_networks(
model: nn.Module,
th: float,
features: np.ndarray,
mean: torch.Tensor,
std: torch.Tensor,
name: str,
):
"""Generate the submission csv for the Kaggle Challenge
Args:
model (nn.Module): Model
th (float): Threshold
... | def generate_submission_data_for_neural_networks(
model: nn.Module,
th: float,
features: np.ndarray,
mean: torch.Tensor,
std: torch.Tensor,
name: str,
):
| """Generate the submission csv for the Kaggle Challenge
Args:
model (nn.Module): Model
th (float): Threshold
features (np.ndarray): Features
mean (torch.Tensor): Mean for the standardization
std (torch.Tensor): Std for the standardization
name (str): Name of the ... | _f1(test_labels, test_preds)
return model, th, (mean, std)
def generate_submission_data_for_neural_networks(
model: nn.Module,
th: float,
features: np.ndarray,
mean: torch.Tensor,
std: torch.Tensor,
name: str,
):
| 64 | 64 | 191 | 45 | 19 | maximecharpentierdata/link-prediction | src/classification/nn.py | Python | generate_submission_data_for_neural_networks | generate_submission_data_for_neural_networks | 180 | 205 | 180 | 187 | f56908a820b1c444da04d0458ff41f330ee5c51a | bigcode/the-stack | train |
e76f2016adfbc16d77ed640e | train | function | def make_classification_model_neural_network(
input_features: np.ndarray,
) -> Tuple[nn.Module, torch.optim.Optimizer, Callable]:
"""Generates Classification Neural Network
Args:
input_features (np.ndarray): Input features
Returns:
Tuple[nn.Module, torch.optim.Optimizer, Callable]: Mod... | def make_classification_model_neural_network(
input_features: np.ndarray,
) -> Tuple[nn.Module, torch.optim.Optimizer, Callable]:
| """Generates Classification Neural Network
Args:
input_features (np.ndarray): Input features
Returns:
Tuple[nn.Module, torch.optim.Optimizer, Callable]: Model,
optimizer and loss function
"""
model = nn.Sequential(
nn.Linear(input_features, 50),
nn.ReLU(),
... | pred = model(X)
loss = loss_fn(pred, y)
if batch % 100 == 0:
losses.append(loss.item())
return losses
def make_classification_model_neural_network(
input_features: np.ndarray,
) -> Tuple[nn.Module, torch.optim.Optimizer, Callable]:
| 64 | 64 | 155 | 30 | 33 | maximecharpentierdata/link-prediction | src/classification/nn.py | Python | make_classification_model_neural_network | make_classification_model_neural_network | 69 | 91 | 69 | 71 | 6c62125c7bb622405b70e30cb84100e9db404657 | bigcode/the-stack | train |
7732def355ccaf6b2aaf0943 | train | function | def plugin(event_tuple, packet=None):
sec, usec, src_ip, src_port, dst_ip, dst_port, proto, type, trail, info, reference = event_tuple
if packet:
localtime = time.strftime(TIME_FORMAT, time.localtime(int(sec)))
output = "\n[%s] %s:%s -> %s:%s:\n" % (localtime, src_ip, src_port, dst_ip, dst_port)... | def plugin(event_tuple, packet=None):
| sec, usec, src_ip, src_port, dst_ip, dst_port, proto, type, trail, info, reference = event_tuple
if packet:
localtime = time.strftime(TIME_FORMAT, time.localtime(int(sec)))
output = "\n[%s] %s:%s -> %s:%s:\n" % (localtime, src_ip, src_port, dst_ip, dst_port)
output += "%s\n" % "".join(_ ... | Copyright (c) 2014-2018 Miroslav Stampar (@stamparm)
See the file 'LICENSE' for copying permission
"""
import sys
import string
import time
TIME_FORMAT = "%Y-%m-%d %H:%M:%S"
def plugin(event_tuple, packet=None):
| 64 | 64 | 131 | 8 | 56 | Jahismighty/maltrail | plugins/peek.py | Python | plugin | plugin | 14 | 21 | 14 | 14 | 76ffcb639ab1d7fb910c943c69658e762b135b6c | bigcode/the-stack | train |
41f06a3436583b470f60e5bf | train | class | class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle a config flow for Somfy MyLink."""
VERSION = 1
def __init__(self):
"""Initialize the somfy_mylink flow."""
self.host = None
self.mac = None
self.ip_address = None
async def async_step_dhcp(self, disc... | class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
| """Handle a config flow for Somfy MyLink."""
VERSION = 1
def __init__(self):
"""Initialize the somfy_mylink flow."""
self.host = None
self.mac = None
self.ip_address = None
async def async_step_dhcp(self, discovery_info: dhcp.DhcpServiceInfo) -> FlowResult:
"""... | .HomeAssistant, data):
"""Validate the user input allows us to connect.
Data has the keys from schema with values provided by the user.
"""
somfy_mylink = SomfyMyLinkSynergy(
data[CONF_SYSTEM_ID], data[CONF_HOST], data[CONF_PORT]
)
try:
status_info = await somfy_mylink.status_i... | 155 | 155 | 519 | 12 | 143 | mib1185/core | homeassistant/components/somfy_mylink/config_flow.py | Python | ConfigFlow | ConfigFlow | 53 | 119 | 53 | 53 | 5ce986eef3bb0dcd4a7bfb23d72e0f2fbbb89b3e | bigcode/the-stack | train |
2f7d549658d229885600e4fc | train | class | class CannotConnect(exceptions.HomeAssistantError):
"""Error to indicate we cannot connect."""
| class CannotConnect(exceptions.HomeAssistantError):
| """Error to indicate we cannot connect."""
| vol.Optional(
CONF_REVERSE,
default=reversed_target_ids.get(target_id, False),
): bool
}
),
description_placeholders={
CONF_TARGET_NAME: self._async_get_target_name(target_id),
},
... | 64 | 64 | 18 | 9 | 55 | mib1185/core | homeassistant/components/somfy_mylink/config_flow.py | Python | CannotConnect | CannotConnect | 198 | 199 | 198 | 198 | bceea90308c9ece5bc4efa71e567c3a4c9d60ab4 | bigcode/the-stack | train |
bb46fa289b9012e4f215be65 | train | class | class InvalidAuth(exceptions.HomeAssistantError):
"""Error to indicate there is invalid auth."""
| class InvalidAuth(exceptions.HomeAssistantError):
| """Error to indicate there is invalid auth."""
| ),
): bool
}
),
description_placeholders={
CONF_TARGET_NAME: self._async_get_target_name(target_id),
},
errors={},
)
class CannotConnect(exceptions.HomeAssistantError):
"""Error to indicate we cannot connec... | 63 | 64 | 19 | 9 | 54 | mib1185/core | homeassistant/components/somfy_mylink/config_flow.py | Python | InvalidAuth | InvalidAuth | 202 | 203 | 202 | 202 | 5891acfb71941773276a2cdb3f14d2f70f187acb | bigcode/the-stack | train |
22ad55f81112006288543318 | train | function | async def validate_input(hass: core.HomeAssistant, data):
"""Validate the user input allows us to connect.
Data has the keys from schema with values provided by the user.
"""
somfy_mylink = SomfyMyLinkSynergy(
data[CONF_SYSTEM_ID], data[CONF_HOST], data[CONF_PORT]
)
try:
status... | async def validate_input(hass: core.HomeAssistant, data):
| """Validate the user input allows us to connect.
Data has the keys from schema with values provided by the user.
"""
somfy_mylink = SomfyMyLinkSynergy(
data[CONF_SYSTEM_ID], data[CONF_HOST], data[CONF_PORT]
)
try:
status_info = await somfy_mylink.status_info()
except asynci... | (
CONF_REVERSE,
CONF_REVERSED_TARGET_IDS,
CONF_SYSTEM_ID,
CONF_TARGET_ID,
CONF_TARGET_NAME,
DEFAULT_PORT,
DOMAIN,
MYLINK_STATUS,
)
_LOGGER = logging.getLogger(__name__)
async def validate_input(hass: core.HomeAssistant, data):
| 64 | 64 | 151 | 13 | 51 | mib1185/core | homeassistant/components/somfy_mylink/config_flow.py | Python | validate_input | validate_input | 32 | 50 | 32 | 32 | 31673dee085db593197d7b7a4bf6109d4dd93627 | bigcode/the-stack | train |
9368a6ee2e558b959bdb66c3 | train | class | class OptionsFlowHandler(config_entries.OptionsFlow):
"""Handle a option flow for somfy_mylink."""
def __init__(self, config_entry: config_entries.ConfigEntry) -> None:
"""Initialize options flow."""
self.config_entry = config_entry
self.options = deepcopy(dict(config_entry.options))
... | class OptionsFlowHandler(config_entries.OptionsFlow):
| """Handle a option flow for somfy_mylink."""
def __init__(self, config_entry: config_entries.ConfigEntry) -> None:
"""Initialize options flow."""
self.config_entry = config_entry
self.options = deepcopy(dict(config_entry.options))
self._target_id = None
@callback
def _a... | .async_show_form(
step_id="user",
data_schema=vol.Schema(
{
vol.Required(CONF_HOST, default=self.ip_address): str,
vol.Required(CONF_SYSTEM_ID): str,
vol.Optional(CONF_PORT, default=DEFAULT_PORT): int,
}
... | 170 | 170 | 568 | 9 | 161 | mib1185/core | homeassistant/components/somfy_mylink/config_flow.py | Python | OptionsFlowHandler | OptionsFlowHandler | 122 | 195 | 122 | 122 | 7f36b2b67cb129b476f90f9bbb06d4473fb94611 | bigcode/the-stack | train |
eb22f31199bdd8e1188c7e65 | train | function | def _collapse_table(table, taxonomy, level, max_observed_level):
table_ids = set(table.ids(axis='observation'))
taxonomy_ids = set(taxonomy.index)
missing_ids = table_ids.difference(taxonomy_ids)
if len(missing_ids) > 0:
raise ValueError('Feature IDs found in the table are missing from the '
... | def _collapse_table(table, taxonomy, level, max_observed_level):
| table_ids = set(table.ids(axis='observation'))
taxonomy_ids = set(taxonomy.index)
missing_ids = table_ids.difference(taxonomy_ids)
if len(missing_ids) > 0:
raise ValueError('Feature IDs found in the table are missing from the '
'taxonomy: {}'.format(missing_ids))
ta... | of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# ----------------------------------------------------------------------------
def _get_max_level(taxonomy):
return taxonomy.apply(lambda x: len(x.split(';'))).max()
def _collapse_table(table, taxonomy, leve... | 64 | 64 | 184 | 15 | 49 | jakereps/q2-taxa | q2_taxa/_util.py | Python | _collapse_table | _collapse_table | 14 | 32 | 14 | 14 | 7d1631794ef8e65fd1a6fc9effda7645aee7222d | bigcode/the-stack | train |
8924dd54baed235b414c976b | train | function | def _get_max_level(taxonomy):
return taxonomy.apply(lambda x: len(x.split(';'))).max()
| def _get_max_level(taxonomy):
| return taxonomy.apply(lambda x: len(x.split(';'))).max()
| # ----------------------------------------------------------------------------
# Copyright (c) 2016-2021, QIIME 2 development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... | 63 | 64 | 24 | 9 | 53 | jakereps/q2-taxa | q2_taxa/_util.py | Python | _get_max_level | _get_max_level | 10 | 11 | 10 | 10 | 30c4334087ad133627782a11e17f77111bf74f46 | bigcode/the-stack | train |
fb0778ad815bf8d3b3933bc0 | train | function | def _extract_to_level(taxonomy, table):
# Assemble the taxonomy data
max_obs_lvl = _get_max_level(taxonomy)
collapsed_tables = []
# Collapse table at specified level
for level in range(1, max_obs_lvl + 1):
collapsed_table = _collapse_table(table, taxonomy, level, max_obs_lvl)
as_df ... | def _extract_to_level(taxonomy, table):
# Assemble the taxonomy data
| max_obs_lvl = _get_max_level(taxonomy)
collapsed_tables = []
# Collapse table at specified level
for level in range(1, max_obs_lvl + 1):
collapsed_table = _collapse_table(table, taxonomy, level, max_obs_lvl)
as_df = collapsed_table.transpose().to_dataframe(dense=True)
collapsed_... | ['__'] * (max_observed_level - len(tax))
tax.extend(padding)
return ';'.join(tax[:level])
return table.collapse(_collapse, axis='observation', norm=False)
def _extract_to_level(taxonomy, table):
# Assemble the taxonomy data
| 64 | 64 | 102 | 18 | 46 | jakereps/q2-taxa | q2_taxa/_util.py | Python | _extract_to_level | _extract_to_level | 35 | 46 | 35 | 36 | 9cc7cfe92ec70bfaee02d7af97f83133385fdca2 | bigcode/the-stack | train |
c951b09fa093bf67ba8fd7eb | train | class | class BaseConfig(object):
PORT = os.getenv("PORT", 25441)
CONNECT_TOR = _get_bool_env_var(os.getenv("CONNECT_TOR", "False"))
SPECTER_DATA_FOLDER = os.path.expanduser(
os.getenv("SPECTER_DATA_FOLDER", "~/.specter")
)
SPECTER_API_ACTIVE = _get_bool_env_var("SPECTER_API_ACTIVE", "False")
# ... | class BaseConfig(object):
| PORT = os.getenv("PORT", 25441)
CONNECT_TOR = _get_bool_env_var(os.getenv("CONNECT_TOR", "False"))
SPECTER_DATA_FOLDER = os.path.expanduser(
os.getenv("SPECTER_DATA_FOLDER", "~/.specter")
)
SPECTER_API_ACTIVE = _get_bool_env_var("SPECTER_API_ACTIVE", "False")
# Logging
# SPECTER_LOGF... | """ A config module contains static configuration """
import configparser
import datetime
import os
import random
import secrets
from pathlib import Path
from dotenv import load_dotenv
# BASEDIR = os.path.abspath(os.path.dirname(__file__))
# Loading env-vars from .flaskenv (4 levels above this file)
env_path = Path(... | 179 | 256 | 1,016 | 5 | 174 | B-396/specter-desktop | src/cryptoadvance/specter/config.py | Python | BaseConfig | BaseConfig | 35 | 128 | 35 | 35 | 19141b394662bbae205262f1e2658e3a2ff115f0 | bigcode/the-stack | train |
9ba1fb7a955934b2226fac50 | train | class | class DevelopmentConfig(BaseConfig):
# https://stackoverflow.com/questions/22463939/demystify-flask-app-secret-key
SECRET_KEY = "development key"
SPECTER_DATA_FOLDER = os.path.expanduser(
os.getenv("SPECTER_DATA_FOLDER", "~/.specter_dev")
)
# API active by default in dev-mode
SPECTER_API... | class DevelopmentConfig(BaseConfig):
# https://stackoverflow.com/questions/22463939/demystify-flask-app-secret-key
| SECRET_KEY = "development key"
SPECTER_DATA_FOLDER = os.path.expanduser(
os.getenv("SPECTER_DATA_FOLDER", "~/.specter_dev")
)
# API active by default in dev-mode
SPECTER_API_ACTIVE = _get_bool_env_var("SPECTER_API_ACTIVE", "True")
| "繁體中文",
}
# Babel integration. List of languages written from right to left for RTL support in the UI
RTL_LANGUAGES = ["he"]
class DevelopmentConfig(BaseConfig):
# https://stackoverflow.com/questions/22463939/demystify-flask-app-secret-key
| 63 | 64 | 97 | 27 | 36 | B-396/specter-desktop | src/cryptoadvance/specter/config.py | Python | DevelopmentConfig | DevelopmentConfig | 131 | 138 | 131 | 132 | e2e2af6e3db74b57877f97079203dbbb087d6d3e | bigcode/the-stack | train |
606345dfbf08132b3dc646f5 | train | class | class ProductionConfig(BaseConfig):
SECRET_KEY = secrets.token_urlsafe(16)
| class ProductionConfig(BaseConfig):
| SECRET_KEY = secrets.token_urlsafe(16)
| TEST_DATA_DIR", "/tmp/specter_cypress_btc_regtest_plain_datadir"
)
BTCD_REGTEST_DATA_DIR = os.getenv(
"BTCD_REGTEST_DATA_DIR", "/tmp/specter_cypress_elm_regtest_plain_datadir"
)
class ProductionConfig(BaseConfig):
| 64 | 64 | 17 | 6 | 58 | B-396/specter-desktop | src/cryptoadvance/specter/config.py | Python | ProductionConfig | ProductionConfig | 170 | 171 | 170 | 170 | e3c0eee444948616ed945362e684be5395942170 | bigcode/the-stack | train |
4de71842c04a1ee42a3ffdb2 | train | class | class CypressTestConfig(TestConfig):
SPECTER_DATA_FOLDER = os.path.expanduser(
os.getenv("SPECTER_DATA_FOLDER", "~/.specter_cypress")
)
PORT = os.getenv("PORT", 25444)
# need to be static in order to (un-)tar bitcoind-dirs reliable
DEFAULT_SPECTER_CONFIG = {"uid": "123456"}
BTCD_REGTES... | class CypressTestConfig(TestConfig):
| SPECTER_DATA_FOLDER = os.path.expanduser(
os.getenv("SPECTER_DATA_FOLDER", "~/.specter_cypress")
)
PORT = os.getenv("PORT", 25444)
# need to be static in order to (un-)tar bitcoind-dirs reliable
DEFAULT_SPECTER_CONFIG = {"uid": "123456"}
BTCD_REGTEST_DATA_DIR = os.getenv(
"BTCD... | _FOLDER = os.path.expanduser(
os.getenv("SPECTER_DATA_FOLDER", "~/.specter_testing")
)
# API active by default in test-mode
SPECTER_API_ACTIVE = _get_bool_env_var("SPECTER_API_ACTIVE", "True")
class CypressTestConfig(TestConfig):
| 64 | 64 | 158 | 7 | 57 | B-396/specter-desktop | src/cryptoadvance/specter/config.py | Python | CypressTestConfig | CypressTestConfig | 152 | 167 | 152 | 152 | 5176aa2d89c39bfcdf1640f8abe319c53c6b28ed | bigcode/the-stack | train |
17ad1afabe1c632117c389f5 | train | function | def _get_bool_env_var(varname, default=None):
value = os.environ.get(varname, default)
if value is None:
return False
elif isinstance(value, str) and value.lower() == "false":
return False
elif bool(value) is False:
return False
else:
return bool(value)
| def _get_bool_env_var(varname, default=None):
| value = os.environ.get(varname, default)
if value is None:
return False
elif isinstance(value, str) and value.lower() == "false":
return False
elif bool(value) is False:
return False
else:
return bool(value)
| env
# BASEDIR = os.path.abspath(os.path.dirname(__file__))
# Loading env-vars from .flaskenv (4 levels above this file)
env_path = Path("../../../..") / ".flaskenv"
load_dotenv(env_path)
def _get_bool_env_var(varname, default=None):
| 64 | 64 | 72 | 12 | 52 | B-396/specter-desktop | src/cryptoadvance/specter/config.py | Python | _get_bool_env_var | _get_bool_env_var | 18 | 29 | 18 | 19 | 26ea97de2bba178cb88759b28ffcd8177d941e8e | bigcode/the-stack | train |
6e0969fae40e6d4b706ee10b | train | class | class TestConfig(BaseConfig):
SECRET_KEY = "test key"
# This should never be used as the data-folder is injected at runtime
# But let's be sure before something horrible happens:
SPECTER_DATA_FOLDER = os.path.expanduser(
os.getenv("SPECTER_DATA_FOLDER", "~/.specter_testing")
)
# API acti... | class TestConfig(BaseConfig):
| SECRET_KEY = "test key"
# This should never be used as the data-folder is injected at runtime
# But let's be sure before something horrible happens:
SPECTER_DATA_FOLDER = os.path.expanduser(
os.getenv("SPECTER_DATA_FOLDER", "~/.specter_testing")
)
# API active by default in test-mode
... | _DATA_FOLDER = os.path.expanduser(
os.getenv("SPECTER_DATA_FOLDER", "~/.specter_dev")
)
# API active by default in dev-mode
SPECTER_API_ACTIVE = _get_bool_env_var("SPECTER_API_ACTIVE", "True")
class TestConfig(BaseConfig):
| 64 | 64 | 103 | 6 | 58 | B-396/specter-desktop | src/cryptoadvance/specter/config.py | Python | TestConfig | TestConfig | 141 | 149 | 141 | 141 | 41e8348838bf6a6b0bd02e9f8140092ad7e724ad | bigcode/the-stack | train |
ac7b2e973a74eb9fa47a4257 | train | class | class NotifyEmail(NotifyBase):
"""
A wrapper to Email Notifications
"""
# The default descriptive name associated with the Notification
service_name = 'E-Mail'
# The default simple (insecure) protocol
protocol = 'mailto'
# The default secure protocol
secure_protocol = 'mailtos'
... | class NotifyEmail(NotifyBase):
| """
A wrapper to Email Notifications
"""
# The default descriptive name associated with the Notification
service_name = 'E-Mail'
# The default simple (insecure) protocol
protocol = 'mailto'
# The default secure protocol
secure_protocol = 'mailtos'
# A URL that takes you to t... | authenticated sender address in the from= settings
# and a valid email in the to= to deliver your emails to
(
'SendGrid',
re.compile(
r'^((?P<label>[^+]+)\+)?(?P<id>[^@]+)@'
r'(?P<domain>(\.smtp)?sendgrid\.(com|net))$', re.I),
{
'port': 465,
... | 256 | 256 | 4,027 | 7 | 249 | loftwah/apprise | apprise/plugins/NotifyEmail.py | Python | NotifyEmail | NotifyEmail | 237 | 797 | 237 | 237 | a28b93125260f10a0ccbfb8d3a6cc08a1e9f6913 | bigcode/the-stack | train |
f2d51e41f02ca1eab4a65f35 | train | class | class SecureMailMode(object):
SSL = "ssl"
STARTTLS = "starttls"
| class SecureMailMode(object):
| SSL = "ssl"
STARTTLS = "starttls"
| of the default emailers
to best formulate a login to it using the data detected
"""
# User Login must be Email Based
EMAIL = 'Email'
# User Login must UserID Based
USERID = 'UserID'
# Secure Email Modes
class SecureMailMode(object):
| 64 | 64 | 20 | 6 | 57 | loftwah/apprise | apprise/plugins/NotifyEmail.py | Python | SecureMailMode | SecureMailMode | 59 | 61 | 59 | 59 | 685ad5dc7dea65d6cff3ff02adac886cc434592a | bigcode/the-stack | train |
7e0dd822ab54b6f1ae6e61da | train | class | class WebBaseLogin(object):
"""
This class is just used in conjunction of the default emailers
to best formulate a login to it using the data detected
"""
# User Login must be Email Based
EMAIL = 'Email'
# User Login must UserID Based
USERID = 'UserID'
| class WebBaseLogin(object):
| """
This class is just used in conjunction of the default emailers
to best formulate a login to it using the data detected
"""
# User Login must be Email Based
EMAIL = 'Email'
# User Login must UserID Based
USERID = 'UserID'
| NotifyBase
from ..URLBase import PrivacyMode
from ..common import NotifyFormat
from ..common import NotifyType
from ..utils import is_email
from ..utils import parse_list
from ..utils import GET_EMAIL_RE
from ..AppriseLocale import gettext_lazy as _
class WebBaseLogin(object):
| 63 | 64 | 69 | 6 | 57 | loftwah/apprise | apprise/plugins/NotifyEmail.py | Python | WebBaseLogin | WebBaseLogin | 46 | 55 | 46 | 46 | ebf3c961d6487ca307cf503a01974d4d197c5115 | bigcode/the-stack | train |
1ccde01a621557d0430357fe | train | class | class SijaxHandler(object):
"""A container class for all Sijax handlers.
Grouping all Sijax handler functions in a class
(or a Python module) allows them all to be registered with
a single line of code.
"""
@staticmethod
def sijax_home(obj_response):
company = Company.qu... | class SijaxHandler(object):
| """A container class for all Sijax handlers.
Grouping all Sijax handler functions in a class
(or a Python module) allows them all to be registered with
a single line of code.
"""
@staticmethod
def sijax_home(obj_response):
company = Company.query.first()
# run th... | from main import app, csrf, db
from flask import render_template, jsonify
from main.models.company import Company
from main.maintenance.company.forms import CompanyMaintenanceForm
from main.models.borrower import Borrower
from main.maintenance.borrower.forms import BorrowerMaintenanceForm
from main.enquiry.borrower.f... | 209 | 256 | 3,898 | 7 | 201 | python-02/flask-spa-CoopApp | main/spa_handler/sijax_handler.py | Python | SijaxHandler | SijaxHandler | 32 | 459 | 32 | 32 | 626014e23d48f86afdbaf4dc7f2d293f74af5ed0 | bigcode/the-stack | train |
c133c163a6576627008a279e | train | class | class Migration(migrations.Migration):
dependencies = [
('form_processor', '0052_auto_20160224_1011'),
]
operations = [
migrations.AddField(
model_name='commcarecasesql',
name='deleted_on',
field=models.DateTimeField(null=True),
preserve_defa... | class Migration(migrations.Migration):
| dependencies = [
('form_processor', '0052_auto_20160224_1011'),
]
operations = [
migrations.AddField(
model_name='commcarecasesql',
name='deleted_on',
field=models.DateTimeField(null=True),
preserve_default=True,
),
migrations.... | from django.db import models, migrations
class Migration(migrations.Migration):
| 15 | 64 | 190 | 7 | 7 | dimagilg/commcare-hq | corehq/form_processor/migrations/0053_add_deletion_fields.py | Python | Migration | Migration | 4 | 35 | 4 | 5 | 5f9501821266d46433786e4a56d9dd09659ce7c8 | bigcode/the-stack | train |
a23d84fb306af92c6c9b7854 | train | function | def inference(inputs,version="xavier",num_classes=1000, is_training=False):
if version=='xavier':
return inference_alexnet_impl(inputs,num_classes, is_training=is_training)
elif version=='he_uniform':
return inference_alexnet_impl_he_uniform(inputs,num_classes, is_training=is_training)
e... | def inference(inputs,version="xavier",num_classes=1000, is_training=False):
| if version=='xavier':
return inference_alexnet_impl(inputs,num_classes, is_training=is_training)
elif version=='he_uniform':
return inference_alexnet_impl_he_uniform(inputs,num_classes, is_training=is_training)
elif version=='he_uniform_custom':
return inference_alexnet_impl_he_uni... | .dense(x, 1000, activation=tf.nn.relu, use_bias=True,
kernel_initializer= tf.variance_scaling_initializer(scale=scale, mode ='fan_in',distribution='uniform'))
return x
def inference(inputs,version="xavier",num_classes=1000, is_training=False):
| 64 | 64 | 126 | 20 | 43 | Huawei-Ascend/modelzoo | built-in/TensorFlow/Official/cv/image_classification/AlexNet_for_TensorFlow/00-access/alexnet/alexnet.py | Python | inference | inference | 156 | 166 | 156 | 158 | 2f369a4b2fdededb80080a9be9ec43b9e14a2a5f | bigcode/the-stack | train |
d50ae3340fd019ef8fc7df24 | train | function | def inference_alexnet_impl(inputs, num_classes=1000, is_training=True):
x = inputs
# conv11*11
x = tf.pad(x, paddings=[[0,0],[2,2],[2,2],[0,0]], mode="CONSTANT")
x = tf.layers.conv2d(x, filters=96, kernel_size=11, strides=(4,4), padding='valid',use_bias=True,activation=tf.nn.relu)
x = tf.layers.max... | def inference_alexnet_impl(inputs, num_classes=1000, is_training=True):
| x = inputs
# conv11*11
x = tf.pad(x, paddings=[[0,0],[2,2],[2,2],[0,0]], mode="CONSTANT")
x = tf.layers.conv2d(x, filters=96, kernel_size=11, strides=(4,4), padding='valid',use_bias=True,activation=tf.nn.relu)
x = tf.layers.max_pooling2d(x,pool_size=(3,3),strides=(2,2), padding='valid')
# conv5... | import tensorflow as tf
from npu_bridge.estimator import npu_ops
def inference_alexnet_impl(inputs, num_classes=1000, is_training=True):
| 34 | 198 | 662 | 18 | 15 | Huawei-Ascend/modelzoo | built-in/TensorFlow/Official/cv/image_classification/AlexNet_for_TensorFlow/00-access/alexnet/alexnet.py | Python | inference_alexnet_impl | inference_alexnet_impl | 6 | 48 | 6 | 7 | ca3b0d6e98fc804b90a8475632f7b39b340ff3f7 | bigcode/the-stack | train |
2d8ddb8c319bbe7ebb957080 | train | function | def inference_alexnet_impl_he_uniform_custom(inputs,num_classes=1000, is_training=True):
'''
to be consistent with ME default weight initialization
'''
scale =1.0/3.0
x = inputs
# conv11*11
x = tf.pad(x, paddings=[[0,0],[2,2],[2,2],[0,0]], mode="CONSTANT")
x = tf.layers.conv2d(x, f... | def inference_alexnet_impl_he_uniform_custom(inputs,num_classes=1000, is_training=True):
| '''
to be consistent with ME default weight initialization
'''
scale =1.0/3.0
x = inputs
# conv11*11
x = tf.pad(x, paddings=[[0,0],[2,2],[2,2],[0,0]], mode="CONSTANT")
x = tf.layers.conv2d(x, filters=96, kernel_size=11, strides=(4,4),
padding='valid',use_bi... | ,kernel_initializer=tf.initializers.he_uniform(5))
x = tf.layers.max_pooling2d(x, pool_size=(3, 3), strides=(2, 2), padding='valid')
x = tf.reshape(x, [-1, 256*6*6])
# fc layers
x = tf.layers.dense(x, 4096, activation=tf.nn.relu, use_bias=True,kernel_initializer=tf.initializers.he_uniform(5))
if... | 256 | 256 | 875 | 20 | 235 | Huawei-Ascend/modelzoo | built-in/TensorFlow/Official/cv/image_classification/AlexNet_for_TensorFlow/00-access/alexnet/alexnet.py | Python | inference_alexnet_impl_he_uniform_custom | inference_alexnet_impl_he_uniform_custom | 98 | 154 | 98 | 98 | 08c9a606443843ef52484836f5c56edb265fdbc8 | bigcode/the-stack | train |
4b20f0ef576e31fd9e4efde5 | train | function | def inference_alexnet_impl_he_uniform(inputs,num_classes=1000, is_training=True):
x = inputs
# conv11*11
x = tf.pad(x, paddings=[[0,0],[2,2],[2,2],[0,0]], mode="CONSTANT")
x = tf.layers.conv2d(x, filters=96, kernel_size=11, strides=(4,4), padding='valid',use_bias=True,activation=tf.nn.relu, kernel_init... | def inference_alexnet_impl_he_uniform(inputs,num_classes=1000, is_training=True):
| x = inputs
# conv11*11
x = tf.pad(x, paddings=[[0,0],[2,2],[2,2],[0,0]], mode="CONSTANT")
x = tf.layers.conv2d(x, filters=96, kernel_size=11, strides=(4,4), padding='valid',use_bias=True,activation=tf.nn.relu, kernel_initializer=tf.initializers.he_uniform(5))
x = tf.layers.max_pooling2d(x,pool_size=... | =True,activation=tf.nn.relu)
x = tf.layers.max_pooling2d(x, pool_size=(3, 3), strides=(2, 2), padding='valid')
x = tf.reshape(x, [-1, 256*6*6])
# fc layers
x = tf.layers.dense(x, 4096, activation=tf.nn.relu, use_bias=True)
if is_training:
x = npu_ops.dropout(x, 0.65)
else:
x =... | 222 | 222 | 742 | 19 | 202 | Huawei-Ascend/modelzoo | built-in/TensorFlow/Official/cv/image_classification/AlexNet_for_TensorFlow/00-access/alexnet/alexnet.py | Python | inference_alexnet_impl_he_uniform | inference_alexnet_impl_he_uniform | 52 | 96 | 52 | 53 | 8452d21fac5957e8e1c11b5379a52750bc9e4d20 | bigcode/the-stack | train |
01e264d1259bccf455a102c3 | train | function | def plot_area(epsg):
img = os.path.basename(__file__).split('.')[0]
title = "Projection {} ".format(epsg)
#Setting output
png = output(
output_formats = ['png'],
output_name = img,
output_name_first_page_number = 'off')
#Setting the geographical area
area = mmap(
subpag... | def plot_area(epsg):
| img = os.path.basename(__file__).split('.')[0]
title = "Projection {} ".format(epsg)
#Setting output
png = output(
output_formats = ['png'],
output_name = img,
output_name_first_page_number = 'off')
#Setting the geographical area
area = mmap(
subpage_map_projection ... | from Magics.macro import *
import os
def plot_area(epsg):
| 17 | 65 | 219 | 7 | 9 | dvuckovic/magics-test | test/proj4/proj-regression-EPSG-32761.py | Python | plot_area | plot_area | 4 | 37 | 4 | 4 | 6cbd44445c84bacb1132ad3644864d72b3eeafd5 | bigcode/the-stack | train |
1fd64588b4d7e0fadf054579 | train | class | class FamilyMemberHistoryCondition(backboneelement.BackboneElement):
""" Condition that the related person had.
The significant Conditions (or condition) that the family member had. This
is a repeating section to allow a system to represent more than one
condition per resource, though there is noth... | class FamilyMemberHistoryCondition(backboneelement.BackboneElement):
| """ Condition that the related person had.
The significant Conditions (or condition) that the family member had. This
is a repeating section to allow a system to represent more than one
condition per resource, though there is nothing stopping multiple resources
- one per condition.
"""
... | .Range, False, "deceased", False),
("deceasedString", "deceasedString", str, False, "deceased", False),
("gender", "gender", str, False, None, False),
("identifier", "identifier", identifier.Identifier, True, None, False),
("name", "name", str, False, None, False),
... | 172 | 172 | 575 | 12 | 159 | all-of-us/raw-data-repository | rdr_service/lib_fhir/fhirclient_1_0_6/models/familymemberhistory.py | Python | FamilyMemberHistoryCondition | FamilyMemberHistoryCondition | 138 | 198 | 138 | 138 | a18fc5bf40824395e844c36ca6bc6fc409395cde | bigcode/the-stack | train |
23883e1575e47db7ea2a1b98 | train | class | class FamilyMemberHistory(domainresource.DomainResource):
""" Information about patient's relatives, relevant for patient.
Significant health events and conditions for a person related to the
patient relevant in the context of care for the patient.
"""
resource_name = "FamilyMemberHistory"... | class FamilyMemberHistory(domainresource.DomainResource):
| """ Information about patient's relatives, relevant for patient.
Significant health events and conditions for a person related to the
patient relevant in the context of care for the patient.
"""
resource_name = "FamilyMemberHistory"
def __init__(self, jsondict=None, strict=True):
... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated from FHIR 1.0.2.7202 (http://hl7.org/fhir/StructureDefinition/FamilyMemberHistory) on 2016-06-23.
# 2016, SMART Health IT.
from . import domainresource
class FamilyMemberHistory(domainresource.DomainResource):
| 80 | 256 | 1,172 | 9 | 70 | all-of-us/raw-data-repository | rdr_service/lib_fhir/fhirclient_1_0_6/models/familymemberhistory.py | Python | FamilyMemberHistory | FamilyMemberHistory | 10 | 133 | 10 | 10 | 293e7edaaa9506d0f6674f50e0fc3a1ddf860afe | bigcode/the-stack | train |
e635a60ad0ad9fd7ffc0ebb6 | train | class | class BeamSearch(object):
""" Defines a beam search object for a single input sentence.
Elements of Queque have shape (score, counter, node)
"""
def __init__(self, beam_size, max_len, pad):
self.beam_size = beam_size
self.max_len = max_len
self.pad = pad
self.nodes... | class BeamSearch(object):
| """ Defines a beam search object for a single input sentence.
Elements of Queque have shape (score, counter, node)
"""
def __init__(self, beam_size, max_len, pad):
self.beam_size = beam_size
self.max_len = max_len
self.pad = pad
self.nodes = PriorityQueue() # beams... | import torch
from itertools import count
from queue import PriorityQueue
import typing
class BeamSearch(object):
| 22 | 196 | 656 | 5 | 16 | PaprikaSteiger/atmt | seq2seq/beam.py | Python | BeamSearch | BeamSearch | 8 | 93 | 8 | 8 | 39e8d585055ef9f76a810be00086ba6b4f3bf259 | bigcode/the-stack | train |
88beed8de808626ecb892e5f | train | class | class BeamSearchNode(object):
""" Defines a search node and stores values important for computation of beam search path"""
def __init__(self, search, emb, lstm_out, final_hidden, final_cell, mask, sequence, logProb, length):
# Attributes needed for computation of decoder states
self.sequence = ... | class BeamSearchNode(object):
| """ Defines a search node and stores values important for computation of beam search path"""
def __init__(self, search, emb, lstm_out, final_hidden, final_cell, mask, sequence, logProb, length):
# Attributes needed for computation of decoder states
self.sequence = sequence
self.emb = em... | ()
for _ in range(self.beam_size-finished):
node = self.nodes.get()
nodes.put(node)
self.nodes = nodes
def prune_n_best(self):
nodes = PriorityQueue()
for _ in range(self.beam_size):
node = self.nodes.get()
nodes.put(node)
self... | 78 | 78 | 262 | 6 | 71 | PaprikaSteiger/atmt | seq2seq/beam.py | Python | BeamSearchNode | BeamSearchNode | 96 | 128 | 96 | 96 | b58645d15441fc640cb06c6c6bdbbb992666c126 | bigcode/the-stack | train |
29e1232879827c9a8227d29c | train | function | def add_post_visible_limit(table):
visitor.add_query_condition(table, post_state_conditions)
user.add_query_condition(table, post_state_conditions)
| def add_post_visible_limit(table):
| visitor.add_query_condition(table, post_state_conditions)
user.add_query_condition(table, post_state_conditions)
| from model.user import POST_STATE
from slim.base.sqlquery import SQLQueryInfo, SQL_OP
from slim.base.permission import Ability
from permissions.roles import *
post_state_conditions = [
('state', '>', POST_STATE.DEL),
]
def add_post_visible_limit(table):
| 56 | 64 | 29 | 7 | 49 | fy0/mapi | slim_cli/template/permissions/tables/_vars.py | Python | add_post_visible_limit | add_post_visible_limit | 12 | 14 | 12 | 12 | 3f61c912bd8c2afabf075631ae92fc7c8c5f072e | bigcode/the-stack | train |
267e06536701382cd8891c58 | train | function | def load(sheets=None, hosts=[]):
rules = {}
if sheets is None:
sheets = open_xlsx(XLSX_PATH)
for i, sheet in enumerate(sheets):
tn4_hostname = sheet.title
if hosts and tn4_hostname not in hosts:
continue
print(f"Loading migration rule: {tn4_hostname} (id:{i})")
try:
lines = sheet.g... | def load(sheets=None, hosts=[]):
| rules = {}
if sheets is None:
sheets = open_xlsx(XLSX_PATH)
for i, sheet in enumerate(sheets):
tn4_hostname = sheet.title
if hosts and tn4_hostname not in hosts:
continue
print(f"Loading migration rule: {tn4_hostname} (id:{i})")
try:
lines = sheet.get_all_values()
except Attrib... | tn3_port": tn3_port,
"description": tn4_desc,
"enable": tn4_noshut,
"poe": tn4_poe,
"lag": tn4_lag,
}
return rule
def load(sheets=None, hosts=[]):
| 64 | 64 | 126 | 9 | 54 | yamaoka-kitaguchi-lab/tn4-edges-deploy | helpers/migrate.py | Python | load | load | 100 | 114 | 100 | 100 | 6758580e12d6807d47b3cd04a7c537330138b331 | bigcode/the-stack | train |
e74eec618dd8328884320942 | train | function | def parse_migration_rule(lines):
rule = {}
for n, l in enumerate(lines):
tn4_port = stringify(l[0]) # Column A
tn3_port = stringify(l[2]) # Column C
tn4_desc = stringify(l[3]).replace(" ", "") # Column D
tn4_noshut = stringify(l[5]) != "down" # Colu... | def parse_migration_rule(lines):
| rule = {}
for n, l in enumerate(lines):
tn4_port = stringify(l[0]) # Column A
tn3_port = stringify(l[2]) # Column C
tn4_desc = stringify(l[3]).replace(" ", "") # Column D
tn4_noshut = stringify(l[5]) != "down" # Column F
tn4_poe = stringify(l... | __), "./port_migration_rules.xlsx")
XLSX_PATH = os.path.join(os.path.dirname(__file__), "./port_migration_rules_part2.xlsx")
def open_worksheets(keyfile, sheetkey):
scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"]
credentials = ServiceAccountCredentials.from_json_keyfile_... | 188 | 188 | 629 | 7 | 180 | yamaoka-kitaguchi-lab/tn4-edges-deploy | helpers/migrate.py | Python | parse_migration_rule | parse_migration_rule | 42 | 97 | 42 | 42 | 8fb4771435ca9e5b7129f9e6a5ae36faa595f63d | bigcode/the-stack | train |
47b5c03b361a8361d0e6eac0 | train | function | def open_worksheets(keyfile, sheetkey):
scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"]
credentials = ServiceAccountCredentials.from_json_keyfile_name(keyfile, scope)
gc = gspread.authorize(credentials)
workbook = gc.open_by_key(sheetkey)
return workbook.worksheets()... | def open_worksheets(keyfile, sheetkey):
| scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"]
credentials = ServiceAccountCredentials.from_json_keyfile_name(keyfile, scope)
gc = gspread.authorize(credentials)
workbook = gc.open_by_key(sheetkey)
return workbook.worksheets()
| "../.secrets/googleapi.json")
#XLSX_PATH = os.path.join(os.path.dirname(__file__), "./port_migration_rules.xlsx")
XLSX_PATH = os.path.join(os.path.dirname(__file__), "./port_migration_rules_part2.xlsx")
def open_worksheets(keyfile, sheetkey):
| 64 | 64 | 77 | 11 | 53 | yamaoka-kitaguchi-lab/tn4-edges-deploy | helpers/migrate.py | Python | open_worksheets | open_worksheets | 21 | 26 | 21 | 21 | 03c4bfdee4295f2b5e880b948aef84f8bb975ef6 | bigcode/the-stack | train |
b04c539e5c7d7b48c6791c73 | train | function | def open_xlsx(xlsx_path):
print("Loading migration rules from Excel...")
book = openpyxl.load_workbook(xlsx_path)
return book.worksheets
| def open_xlsx(xlsx_path):
| print("Loading migration rules from Excel...")
book = openpyxl.load_workbook(xlsx_path)
return book.worksheets
| .com/feeds", "https://www.googleapis.com/auth/drive"]
credentials = ServiceAccountCredentials.from_json_keyfile_name(keyfile, scope)
gc = gspread.authorize(credentials)
workbook = gc.open_by_key(sheetkey)
return workbook.worksheets()
def open_xlsx(xlsx_path):
| 64 | 64 | 37 | 8 | 56 | yamaoka-kitaguchi-lab/tn4-edges-deploy | helpers/migrate.py | Python | open_xlsx | open_xlsx | 29 | 32 | 29 | 29 | b524c67d7c1c7ed1e40af245e2a8bf3cda822a69 | bigcode/the-stack | train |
ea23a8fe9b523979a6826f31 | train | function | def stringify(c):
if c == None: return ""
if c == True: return "TRUE"
if c == False: return "FALSE"
return c
| def stringify(c):
| if c == None: return ""
if c == True: return "TRUE"
if c == False: return "FALSE"
return c
| gspread.authorize(credentials)
workbook = gc.open_by_key(sheetkey)
return workbook.worksheets()
def open_xlsx(xlsx_path):
print("Loading migration rules from Excel...")
book = openpyxl.load_workbook(xlsx_path)
return book.worksheets
def stringify(c):
| 64 | 64 | 36 | 4 | 59 | yamaoka-kitaguchi-lab/tn4-edges-deploy | helpers/migrate.py | Python | stringify | stringify | 35 | 39 | 35 | 35 | f41075d30c86b06cb736b101a1bdeeb51ebe026c | bigcode/the-stack | train |
8ee47fec2ad90c1227f27b4b | train | function | def get_unspent(listunspent, amount):
for utx in listunspent:
if utx['amount'] == amount:
return utx
raise AssertionError('Could not find unspent with amount={}'.format(amount))
| def get_unspent(listunspent, amount):
| for utx in listunspent:
if utx['amount'] == amount:
return utx
raise AssertionError('Could not find unspent with amount={}'.format(amount))
| Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the fundrawtransaction RPC."""
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
def get_unspent(listunspent, ... | 64 | 64 | 51 | 10 | 54 | bitnitdit/bitcoin | test/functional/rpc_fundrawtransaction.py | Python | get_unspent | get_unspent | 11 | 15 | 11 | 11 | 62a9fa8952a3d8293a8619fff2b6be922c8cc56d | bigcode/the-stack | train |
85b85185787014362ef87db5 | train | class | class RawTransactionsTest(BitcoinTestFramework):
def set_test_params(self):
self.num_nodes = 4
self.setup_clean_chain = True
def setup_network(self, split=False):
self.setup_nodes()
connect_nodes_bi(self.nodes, 0, 1)
connect_nodes_bi(self.nodes, 1, 2)
connect_no... | class RawTransactionsTest(BitcoinTestFramework):
| def set_test_params(self):
self.num_nodes = 4
self.setup_clean_chain = True
def setup_network(self, split=False):
self.setup_nodes()
connect_nodes_bi(self.nodes, 0, 1)
connect_nodes_bi(self.nodes, 1, 2)
connect_nodes_bi(self.nodes, 0, 2)
connect_nodes_bi... | #!/usr/bin/env python3
# Copyright (c) 2014-2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the fundrawtransaction RPC."""
from test_framework.test_framework import BitcoinTestFramework
fro... | 134 | 256 | 8,284 | 9 | 125 | bitnitdit/bitcoin | test/functional/rpc_fundrawtransaction.py | Python | RawTransactionsTest | RawTransactionsTest | 17 | 732 | 17 | 17 | 05dc3e92747d5177d72bbef86f9a92ee6455ce20 | bigcode/the-stack | train |
4c884c3c42e200f680834cd4 | train | function | def demosaicing_CFA_Bayer_Malvar2004(
CFA: ArrayLike,
pattern: Union[Literal["RGGB", "BGGR", "GRBG", "GBRG"], str] = "RGGB",
) -> NDArray:
"""
Return the demosaiced *RGB* colourspace array from given *Bayer* CFA using
*Malvar (2004)* demosaicing algorithm.
Parameters
----------
CFA
... | def demosaicing_CFA_Bayer_Malvar2004(
CFA: ArrayLike,
pattern: Union[Literal["RGGB", "BGGR", "GRBG", "GBRG"], str] = "RGGB",
) -> NDArray:
| """
Return the demosaiced *RGB* colourspace array from given *Bayer* CFA using
*Malvar (2004)* demosaicing algorithm.
Parameters
----------
CFA
*Bayer* CFA.
pattern
Arrangement of the colour filters on the pixel array.
Returns
-------
:class:`numpy.ndarray`
... | emosaicing of
Bayer-Patterned Color Images. International Conference of Acoustic, Speech
and Signal Processing, 5-8.
http://research.microsoft.com/apps/pubs/default.aspx?id=102068
"""
from __future__ import annotations
import numpy as np
from scipy.ndimage.filters import convolve
from colour.hints import... | 256 | 256 | 1,886 | 54 | 202 | MengmSun/colour-demosaicing | colour_demosaicing/bayer/demosaicing/malvar2004.py | Python | demosaicing_CFA_Bayer_Malvar2004 | demosaicing_CFA_Bayer_Malvar2004 | 38 | 181 | 38 | 41 | c91b62bdf2bd3eda0aeb54d0fca6a8f2129e802d | bigcode/the-stack | train |
0a9792f9eea15af50249f3dc | train | function | def test_signature():
# literals
with pytest.raises(TypeError):
inspect.signature(1)
with pytest.raises(TypeError):
inspect.signature('')
# builtins are supported on a case-by-case basis, depending on whether
# they define __text_signature__
if getattr(list, '__text_signature__... | def test_signature():
# literals
| with pytest.raises(TypeError):
inspect.signature(1)
with pytest.raises(TypeError):
inspect.signature('')
# builtins are supported on a case-by-case basis, depending on whether
# they define __text_signature__
if getattr(list, '__text_signature__', None):
sig = inspect.strin... | SyslogHandler'
assert type_alias['logging'].Logger == logging.Logger
assert type_alias['logging'].config == logging.config
with pytest.raises(KeyError):
assert type_alias['log']
with pytest.raises(KeyError):
assert type_alias['unknown']
def test_signature():
# literals
| 64 | 64 | 170 | 8 | 56 | rdt12/sphinx | tests/test_util_inspect.py | Python | test_signature | test_signature | 44 | 66 | 44 | 45 | 8344e5506bd520cb6ae746d8992b4a70d7c285e1 | bigcode/the-stack | train |
061faa5fdd1c6ec605ecbef9 | train | function | def test_signature_from_str_invalid():
with pytest.raises(SyntaxError):
inspect.signature_from_str('')
| def test_signature_from_str_invalid():
| with pytest.raises(SyntaxError):
inspect.signature_from_str('')
|
assert sig.parameters['b'].kind == Parameter.POSITIONAL_ONLY
assert sig.parameters['b'].default == '0'
assert sig.parameters['c'].kind == Parameter.POSITIONAL_OR_KEYWORD
assert sig.parameters['c'].default == '1'
def test_signature_from_str_invalid():
| 64 | 64 | 21 | 7 | 57 | rdt12/sphinx | tests/test_util_inspect.py | Python | test_signature_from_str_invalid | test_signature_from_str_invalid | 379 | 381 | 379 | 379 | 3a7b8b8d8f2c19b44da908c0de84277099e15f4c | bigcode/the-stack | train |
88c8fa745bf2018d9cac6163 | train | function | def test_frozenset_sorting_fallback():
frozenset_ = frozenset((None, 1))
description = inspect.object_description(frozenset_)
assert description in ("frozenset({1, None})", "frozenset({None, 1})")
| def test_frozenset_sorting_fallback():
| frozenset_ = frozenset((None, 1))
description = inspect.object_description(frozenset_)
assert description in ("frozenset({1, None})", "frozenset({None, 1})")
| et_ = frozenset("gfedcba")
description = inspect.object_description(frozenset_)
assert description == "frozenset({'a', 'b', 'c', 'd', 'e', 'f', 'g'})"
def test_frozenset_sorting_fallback():
| 64 | 64 | 62 | 11 | 53 | rdt12/sphinx | tests/test_util_inspect.py | Python | test_frozenset_sorting_fallback | test_frozenset_sorting_fallback | 499 | 502 | 499 | 499 | 3eeaa8e95d06877bb72dc2a6c6e272e2f1fbe3f8 | bigcode/the-stack | train |
f76e6710ca74990436ea8cbd | train | function | def test_signature_from_str_complex_annotations():
sig = inspect.signature_from_str('() -> Tuple[str, int, ...]')
assert sig.return_annotation == 'Tuple[str, int, ...]'
sig = inspect.signature_from_str('() -> Callable[[int, int], int]')
assert sig.return_annotation == 'Callable[[int, int], int]'
| def test_signature_from_str_complex_annotations():
| sig = inspect.signature_from_str('() -> Tuple[str, int, ...]')
assert sig.return_annotation == 'Tuple[str, int, ...]'
sig = inspect.signature_from_str('() -> Callable[[int, int], int]')
assert sig.return_annotation == 'Callable[[int, int], int]'
| assert sig.parameters['a'].annotation == "int"
assert sig.parameters['args'].annotation == "bytes"
assert sig.parameters['b'].annotation == "str"
assert sig.parameters['kwargs'].annotation == "float"
assert sig.return_annotation == 'None'
def test_signature_from_str_complex_annotations():
| 64 | 64 | 73 | 8 | 56 | rdt12/sphinx | tests/test_util_inspect.py | Python | test_signature_from_str_complex_annotations | test_signature_from_str_complex_annotations | 349 | 354 | 349 | 349 | 8b67113a5dfda7aeb66095683f9545dbd2f3be82 | bigcode/the-stack | train |
468a1e2ddd663faa19b9b2f0 | train | function | def test_is_builtin_class_method():
class MyInt(int):
def my_method(self):
pass
assert inspect.is_builtin_class_method(MyInt, 'to_bytes')
assert inspect.is_builtin_class_method(MyInt, '__init__')
assert not inspect.is_builtin_class_method(MyInt, 'my_method')
assert not inspect.i... | def test_is_builtin_class_method():
| class MyInt(int):
def my_method(self):
pass
assert inspect.is_builtin_class_method(MyInt, 'to_bytes')
assert inspect.is_builtin_class_method(MyInt, '__init__')
assert not inspect.is_builtin_class_method(MyInt, 'my_method')
assert not inspect.is_builtin_class_method(MyInt, 'does_... | inherited and decorated method
pass
assert inspect.getdoc(Bar.meth, getattr, False, Bar, "meth") is None
assert inspect.getdoc(Bar.meth, getattr, True, Bar, "meth") == Foo.meth.__doc__
def test_is_builtin_class_method():
| 63 | 64 | 156 | 7 | 56 | rdt12/sphinx | tests/test_util_inspect.py | Python | test_is_builtin_class_method | test_is_builtin_class_method | 692 | 707 | 692 | 692 | fbdd308005f4692b66ec29c096ccb4ebc82a6821 | bigcode/the-stack | train |
b3b20d65285ccd190b5c75d6 | train | function | @pytest.mark.sphinx(testroot='ext-autodoc')
def test_isattributedescriptor(app):
from target.methods import Base
class Descriptor:
def __get__(self, obj, typ=None):
pass
testinstancemethod = _testcapi.instancemethod(str.__repr__)
assert inspect.isattributedescriptor(Base.prop) is ... | @pytest.mark.sphinx(testroot='ext-autodoc')
def test_isattributedescriptor(app):
| from target.methods import Base
class Descriptor:
def __get__(self, obj, typ=None):
pass
testinstancemethod = _testcapi.instancemethod(str.__repr__)
assert inspect.isattributedescriptor(Base.prop) is True # property
assert inspect.isattributedescriptor(Base.... | (Base.prop) is True # property of class
assert inspect.isdescriptor(Base().prop) is False # property of instance
assert inspect.isdescriptor(Base.meth) is True # method of class
assert inspect.isdescriptor(Base().meth) is True # method of instance
assert inspect.isdescriptor(func) is True... | 96 | 96 | 323 | 21 | 74 | rdt12/sphinx | tests/test_util_inspect.py | Python | test_isattributedescriptor | test_isattributedescriptor | 616 | 636 | 616 | 617 | baa1d0b33a78b4d2fd2028e22ee61bdb4766defa | bigcode/the-stack | train |
de58a27ddc7332db23914dad | train | function | @pytest.mark.skipif(sys.version_info < (3, 8), reason='python 3.8+ is required.')
@pytest.mark.sphinx(testroot='ext-autodoc')
def test_signature_annotations_py38(app):
from target.pep570 import bar, baz, foo, qux
# case: separator at head
sig = inspect.signature(foo)
assert stringify_signature(sig) == ... | @pytest.mark.skipif(sys.version_info < (3, 8), reason='python 3.8+ is required.')
@pytest.mark.sphinx(testroot='ext-autodoc')
def test_signature_annotations_py38(app):
| from target.pep570 import bar, baz, foo, qux
# case: separator at head
sig = inspect.signature(foo)
assert stringify_signature(sig) == '(*, a, b)'
# case: separator in the middle
sig = inspect.signature(bar)
assert stringify_signature(sig) == '(a, b, /, c, d)'
sig = inspect.signature(... | _annotation=False) == '(x: Optional[int] = None, y: dict = {})'
@pytest.mark.skipif(sys.version_info < (3, 8), reason='python 3.8+ is required.')
@pytest.mark.sphinx(testroot='ext-autodoc')
def test_signature_annotations_py38(app):
| 64 | 64 | 180 | 45 | 19 | rdt12/sphinx | tests/test_util_inspect.py | Python | test_signature_annotations_py38 | test_signature_annotations_py38 | 266 | 284 | 266 | 268 | 1ddc126a15e3a74fa9612e0006b083c0c461b1cf | bigcode/the-stack | train |
c94465a258f3aed6402a93bf | train | function | def test_signature_partial():
def fun(a, b, c=1, d=2):
pass
p = functools.partial(fun, 10, c=11)
sig = inspect.signature(p)
assert stringify_signature(sig) == '(b, *, c=11, d=2)'
| def test_signature_partial():
| def fun(a, b, c=1, d=2):
pass
p = functools.partial(fun, 10, c=11)
sig = inspect.signature(p)
assert stringify_signature(sig) == '(b, *, c=11, d=2)'
| def func(a, b, c=1, d=2, *e, **f):
pass
sig = inspect.stringify_signature(inspect.signature(func))
assert sig == '(a, b, c=1, d=2, *e, **f)'
def test_signature_partial():
| 63 | 64 | 63 | 5 | 58 | rdt12/sphinx | tests/test_util_inspect.py | Python | test_signature_partial | test_signature_partial | 69 | 75 | 69 | 69 | e5cb67e5fe4f44f862254f9123e6691e2b68d576 | bigcode/the-stack | train |
4e2a646eb8f3ab23c22033c7 | train | function | def test_set_sorting_fallback():
set_ = {None, 1}
description = inspect.object_description(set_)
assert description in ("{1, None}", "{None, 1}")
| def test_set_sorting_fallback():
| set_ = {None, 1}
description = inspect.object_description(set_)
assert description in ("{1, None}", "{None, 1}")
| 2}"
def test_set_sorting():
set_ = set("gfedcba")
description = inspect.object_description(set_)
assert description == "{'a', 'b', 'c', 'd', 'e', 'f', 'g'}"
def test_set_sorting_fallback():
| 64 | 64 | 42 | 8 | 56 | rdt12/sphinx | tests/test_util_inspect.py | Python | test_set_sorting_fallback | test_set_sorting_fallback | 487 | 490 | 487 | 487 | 550e01ed7882c7fb7a1ca938e6acc53048887d9b | bigcode/the-stack | train |
09107b436c7c2300943d51f6 | train | function | @pytest.mark.sphinx(testroot='ext-autodoc')
def test_isfunction(app):
from target.functions import builtin_func, func, partial_builtin_func, partial_func
from target.methods import Base
assert inspect.isfunction(func) is True # function
assert inspect.isfunction(partial_func) is Tru... | @pytest.mark.sphinx(testroot='ext-autodoc')
def test_isfunction(app):
| from target.functions import builtin_func, func, partial_builtin_func, partial_func
from target.methods import Base
assert inspect.isfunction(func) is True # function
assert inspect.isfunction(partial_func) is True # partial-ed function
assert inspect.isfunction(Base... | # coroutine-method
# partial-ed coroutine-method
partial_coroutinemeth = Base.__dict__['partial_coroutinemeth']
assert inspect.iscoroutinefunction(partial_coroutinemeth) is True
@pytest.mark.sphinx(testroot='ext-autodoc')
def test_isfunction(app):
| 64 | 64 | 160 | 18 | 45 | rdt12/sphinx | tests/test_util_inspect.py | Python | test_isfunction | test_isfunction | 577 | 588 | 577 | 578 | e783839209543a66025c5db2fa5e4869bd44cd29 | bigcode/the-stack | train |
34ea11fa4ff4b692f821aab8 | train | function | def test_unpartial():
def func1(a, b, c):
pass
func2 = functools.partial(func1, 1)
func2.__doc__ = "func2"
func3 = functools.partial(func2, 2) # nested partial object
assert inspect.unpartial(func2) is func1
assert inspect.unpartial(func3) is func1
| def test_unpartial():
| def func1(a, b, c):
pass
func2 = functools.partial(func1, 1)
func2.__doc__ = "func2"
func3 = functools.partial(func2, 2) # nested partial object
assert inspect.unpartial(func2) is func1
assert inspect.unpartial(func3) is func1
| C, T
from target.methods import Base
assert inspect.isgenericalias(C) is True
assert inspect.isgenericalias(T) is True
assert inspect.isgenericalias(object()) is False
assert inspect.isgenericalias(Base) is False
def test_unpartial():
| 64 | 64 | 83 | 5 | 58 | rdt12/sphinx | tests/test_util_inspect.py | Python | test_unpartial | test_unpartial | 662 | 671 | 662 | 662 | b0452eb35d7b5d0768e708e91d88a4e92fddf4a6 | bigcode/the-stack | train |
4cd2602eee76be5c1537c750 | train | function | @pytest.mark.sphinx(testroot='ext-autodoc')
def test_isdescriptor(app):
from target.functions import func
from target.methods import Base
assert inspect.isdescriptor(Base.prop) is True # property of class
assert inspect.isdescriptor(Base().prop) is False # property of instance
assert inspect... | @pytest.mark.sphinx(testroot='ext-autodoc')
def test_isdescriptor(app):
| from target.functions import func
from target.methods import Base
assert inspect.isdescriptor(Base.prop) is True # property of class
assert inspect.isdescriptor(Base().prop) is False # property of instance
assert inspect.isdescriptor(Base.meth) is True # method of class
assert inspe... | (partial_func) is False # partial-ed function
assert inspect.isbuiltin(Base.meth) is False # method of class
assert inspect.isbuiltin(Base().meth) is False # method of instance
@pytest.mark.sphinx(testroot='ext-autodoc')
def test_isdescriptor(app):
| 64 | 64 | 112 | 18 | 45 | rdt12/sphinx | tests/test_util_inspect.py | Python | test_isdescriptor | test_isdescriptor | 604 | 613 | 604 | 605 | 3940b3bb7e73151fbf7331ddfdefa3960e8c1882 | bigcode/the-stack | train |
cc89082456e2404561ddeba7 | train | function | @pytest.mark.skipif(sys.version_info < (3, 7), reason='python 3.7+ is required.')
@pytest.mark.sphinx(testroot='ext-autodoc')
def test_isgenericalias(app):
from target.genericalias import C, T
from target.methods import Base
assert inspect.isgenericalias(C) is True
assert inspect.isgenericalias(T) is T... | @pytest.mark.skipif(sys.version_info < (3, 7), reason='python 3.7+ is required.')
@pytest.mark.sphinx(testroot='ext-autodoc')
def test_isgenericalias(app):
| from target.genericalias import C, T
from target.methods import Base
assert inspect.isgenericalias(C) is True
assert inspect.isgenericalias(T) is True
assert inspect.isgenericalias(object()) is False
assert inspect.isgenericalias(Base) is False
| # method of instance
assert inspect.isproperty(func) is False # function
@pytest.mark.skipif(sys.version_info < (3, 7), reason='python 3.7+ is required.')
@pytest.mark.sphinx(testroot='ext-autodoc')
def test_isgenericalias(app):
| 64 | 64 | 111 | 45 | 18 | rdt12/sphinx | tests/test_util_inspect.py | Python | test_isgenericalias | test_isgenericalias | 650 | 659 | 650 | 652 | fce47c9044858a0ca52e42b0174dca3aecb0f261 | bigcode/the-stack | train |
af2ae1d1837bbf029e0fb331 | train | function | @pytest.mark.sphinx(testroot='ext-autodoc')
def test_iscoroutinefunction(app):
from target.functions import coroutinefunc, func, partial_coroutinefunc
from target.methods import Base
assert inspect.iscoroutinefunction(func) is False # function
assert inspect.iscoroutinefunction(corout... | @pytest.mark.sphinx(testroot='ext-autodoc')
def test_iscoroutinefunction(app):
| from target.functions import coroutinefunc, func, partial_coroutinefunc
from target.methods import Base
assert inspect.iscoroutinefunction(func) is False # function
assert inspect.iscoroutinefunction(coroutinefunc) is True # coroutine
assert inspect.iscoroutinefunction(p... | ') is False
assert inspect.isstaticmethod(Inherited.staticmeth, Inherited, 'staticmeth') is True
assert inspect.isstaticmethod(Inherited.meth, Inherited, 'meth') is False
@pytest.mark.sphinx(testroot='ext-autodoc')
def test_iscoroutinefunction(app):
| 64 | 64 | 176 | 21 | 42 | rdt12/sphinx | tests/test_util_inspect.py | Python | test_iscoroutinefunction | test_iscoroutinefunction | 561 | 574 | 561 | 562 | 112d7a7338837660dcef8c43c83619f17bcfaa8d | bigcode/the-stack | train |
aab83503ade16be7cfd507e6 | train | function | def test_isproperty(app):
from target.functions import func
from target.methods import Base
assert inspect.isproperty(Base.prop) is True # property of class
assert inspect.isproperty(Base().prop) is False # property of instance
assert inspect.isproperty(Base.meth) is False # method... | def test_isproperty(app):
| from target.functions import func
from target.methods import Base
assert inspect.isproperty(Base.prop) is True # property of class
assert inspect.isproperty(Base().prop) is False # property of instance
assert inspect.isproperty(Base.meth) is False # method of class
assert inspe... | QA
assert inspect.isattributedescriptor(datetime.timedelta.days) is True # MemberDescriptorType # NOQA
assert inspect.isattributedescriptor(testinstancemethod) is False # instancemethod (C-API) # NOQA
def test_isproperty(app):
| 64 | 64 | 100 | 6 | 57 | rdt12/sphinx | tests/test_util_inspect.py | Python | test_isproperty | test_isproperty | 639 | 647 | 639 | 639 | db87fa44cd1ccad2a1caaa98683d01f06a90ffa1 | bigcode/the-stack | train |
d5d0eb4fa18b5b4c9e0d3111 | train | function | def test_signature_methods():
class Foo:
def meth1(self, arg1, **kwargs):
pass
@classmethod
def meth2(cls, arg1, *args, **kwargs):
pass
@staticmethod
def meth3(arg1, *args, **kwargs):
pass
@functools.wraps(Foo().meth1)
def wrappe... | def test_signature_methods():
| class Foo:
def meth1(self, arg1, **kwargs):
pass
@classmethod
def meth2(cls, arg1, *args, **kwargs):
pass
@staticmethod
def meth3(arg1, *args, **kwargs):
pass
@functools.wraps(Foo().meth1)
def wrapped_bound_method(*args, **kwargs... | sig = inspect.stringify_signature(inspect.signature(func))
assert sig == '(a, b, c=1, d=2, *e, **f)'
def test_signature_partial():
def fun(a, b, c=1, d=2):
pass
p = functools.partial(fun, 10, c=11)
sig = inspect.signature(p)
assert stringify_signature(sig) == '(b, *, c=11, d=2)'
def test... | 102 | 103 | 344 | 5 | 97 | rdt12/sphinx | tests/test_util_inspect.py | Python | test_signature_methods | test_signature_methods | 78 | 122 | 78 | 78 | 9b20fe5127b95bba8458ccb7d0a2539938e66989 | bigcode/the-stack | train |
5946f35f233e0129146e6b1a | train | function | def test_dictionary_sorting():
dictionary = {"c": 3, "a": 1, "d": 2, "b": 4}
description = inspect.object_description(dictionary)
assert description == "{'a': 1, 'b': 4, 'c': 3, 'd': 2}"
| def test_dictionary_sorting():
| dictionary = {"c": 3, "a": 1, "d": 2, "b": 4}
description = inspect.object_description(dictionary)
assert description == "{'a': 1, 'b': 4, 'c': 3, 'd': 2}"
| def __dict__(self):
raise Exception
obj = Foo()
try:
inspect.safe_getattr(obj, 'bar')
except AttributeError as exc:
assert exc.args[0] == 'bar'
else:
pytest.fail('AttributeError not raised')
def test_dictionary_sorting():
| 64 | 64 | 70 | 6 | 58 | rdt12/sphinx | tests/test_util_inspect.py | Python | test_dictionary_sorting | test_dictionary_sorting | 475 | 478 | 475 | 475 | 13cff9dc342a6fbe3e8c7a356ca36f58236fe85d | bigcode/the-stack | train |
85de220c5dab46096f16cf65 | train | function | def test_signature_from_str_basic():
signature = '(a, b, *args, c=0, d="blah", **kwargs)'
sig = inspect.signature_from_str(signature)
assert list(sig.parameters.keys()) == ['a', 'b', 'args', 'c', 'd', 'kwargs']
assert sig.parameters['a'].name == 'a'
assert sig.parameters['a'].kind == Parameter.POSIT... | def test_signature_from_str_basic():
| signature = '(a, b, *args, c=0, d="blah", **kwargs)'
sig = inspect.signature_from_str(signature)
assert list(sig.parameters.keys()) == ['a', 'b', 'args', 'c', 'd', 'kwargs']
assert sig.parameters['a'].name == 'a'
assert sig.parameters['a'].kind == Parameter.POSITIONAL_OR_KEYWORD
assert sig.param... | (foo)
assert stringify_signature(sig) == '(*, a, b)'
# case: separator in the middle
sig = inspect.signature(bar)
assert stringify_signature(sig) == '(a, b, /, c, d)'
sig = inspect.signature(baz)
assert stringify_signature(sig) == '(a, /, *, b)'
# case: separator at tail
sig = inspect... | 113 | 114 | 381 | 7 | 106 | rdt12/sphinx | tests/test_util_inspect.py | Python | test_signature_from_str_basic | test_signature_from_str_basic | 287 | 315 | 287 | 287 | 714beeb5ce1b802b92ed04da03bd52c957cdb78b | bigcode/the-stack | train |
fe2ad6e835d61b30624d2931 | train | function | def test_signature_from_str_default_values():
signature = ('(a=0, b=0.0, c="str", d=b"bytes", e=..., f=True, '
'g=[1, 2, 3], h={"a": 1}, i={1, 2, 3}, '
'j=lambda x, y: None, k=None, l=object(), m=foo.bar.CONSTANT)')
sig = inspect.signature_from_str(signature)
assert sig.par... | def test_signature_from_str_default_values():
| signature = ('(a=0, b=0.0, c="str", d=b"bytes", e=..., f=True, '
'g=[1, 2, 3], h={"a": 1}, i={1, 2, 3}, '
'j=lambda x, y: None, k=None, l=object(), m=foo.bar.CONSTANT)')
sig = inspect.signature_from_str(signature)
assert sig.parameters['a'].default == '0'
assert sig.par... | default == "'blah'"
assert sig.parameters['d'].annotation == Parameter.empty
assert sig.parameters['kwargs'].name == 'kwargs'
assert sig.parameters['kwargs'].kind == Parameter.VAR_KEYWORD
assert sig.parameters['kwargs'].default == Parameter.empty
assert sig.parameters['kwargs'].annotation == Paramet... | 85 | 85 | 286 | 8 | 76 | rdt12/sphinx | tests/test_util_inspect.py | Python | test_signature_from_str_default_values | test_signature_from_str_default_values | 318 | 335 | 318 | 318 | 6cc70a753f1cb612042ecf8eac2ca19cec153061 | bigcode/the-stack | train |
5cabe2051dbac9b8a50a7b89 | train | function | def test_signature_from_str_kwonly_args():
sig = inspect.signature_from_str('(a, *, b)')
assert list(sig.parameters.keys()) == ['a', 'b']
assert sig.parameters['a'].kind == Parameter.POSITIONAL_OR_KEYWORD
assert sig.parameters['a'].default == Parameter.empty
assert sig.parameters['b'].kind == Parame... | def test_signature_from_str_kwonly_args():
| sig = inspect.signature_from_str('(a, *, b)')
assert list(sig.parameters.keys()) == ['a', 'b']
assert sig.parameters['a'].kind == Parameter.POSITIONAL_OR_KEYWORD
assert sig.parameters['a'].default == Parameter.empty
assert sig.parameters['b'].kind == Parameter.KEYWORD_ONLY
assert sig.parameters[... | [str, int, ...]')
assert sig.return_annotation == 'Tuple[str, int, ...]'
sig = inspect.signature_from_str('() -> Callable[[int, int], int]')
assert sig.return_annotation == 'Callable[[int, int], int]'
def test_signature_from_str_kwonly_args():
| 63 | 64 | 91 | 9 | 54 | rdt12/sphinx | tests/test_util_inspect.py | Python | test_signature_from_str_kwonly_args | test_signature_from_str_kwonly_args | 357 | 363 | 357 | 357 | 8faeb2e904b2909404eb977533d5fe0a00e3b120 | bigcode/the-stack | train |
2a0e453a2b4ebab3327a6335 | train | function | @pytest.mark.sphinx(testroot='ext-autodoc')
def test_isbuiltin(app):
from target.functions import builtin_func, func, partial_builtin_func, partial_func
from target.methods import Base
assert inspect.isbuiltin(builtin_func) is True # builtin function
assert inspect.isbuiltin(partial_builtin_fu... | @pytest.mark.sphinx(testroot='ext-autodoc')
def test_isbuiltin(app):
| from target.functions import builtin_func, func, partial_builtin_func, partial_func
from target.methods import Base
assert inspect.isbuiltin(builtin_func) is True # builtin function
assert inspect.isbuiltin(partial_builtin_func) is True # partial-ed builtin function
assert inspect.isbuilt... | ().meth) is False # method of instance
assert inspect.isfunction(builtin_func) is False # builtin function
assert inspect.isfunction(partial_builtin_func) is False # partial-ed builtin function
@pytest.mark.sphinx(testroot='ext-autodoc')
def test_isbuiltin(app):
| 64 | 64 | 141 | 18 | 45 | rdt12/sphinx | tests/test_util_inspect.py | Python | test_isbuiltin | test_isbuiltin | 591 | 601 | 591 | 592 | 7faa4d0b176bbc582f7b33ccd98e0028119ab5f0 | bigcode/the-stack | train |
4994414f67148f2b91d5171e | train | function | def test_signature_partialmethod():
from functools import partialmethod
class Foo:
def meth1(self, arg1, arg2, arg3=None, arg4=None):
pass
def meth2(self, arg1, arg2):
pass
foo = partialmethod(meth1, 1, 2)
bar = partialmethod(meth1, 1, arg3=3)
b... | def test_signature_partialmethod():
| from functools import partialmethod
class Foo:
def meth1(self, arg1, arg2, arg3=None, arg4=None):
pass
def meth2(self, arg1, arg2):
pass
foo = partialmethod(meth1, 1, 2)
bar = partialmethod(meth1, 1, arg3=3)
baz = partialmethod(meth2, 1, 2)
... | = inspect.signature(Foo().meth3)
assert stringify_signature(sig) == '(arg1, *args, **kwargs)'
# wrapped bound method
sig = inspect.signature(wrapped_bound_method)
assert stringify_signature(sig) == '(arg1, **kwargs)'
def test_signature_partialmethod():
| 63 | 64 | 181 | 6 | 57 | rdt12/sphinx | tests/test_util_inspect.py | Python | test_signature_partialmethod | test_signature_partialmethod | 125 | 147 | 125 | 125 | 50b9ed7895025e271dd9f0a6c9d8e84fbd7aa94b | bigcode/the-stack | train |
effde055063e3f7552489415 | train | function | def test_getdoc_inherited_decorated_method():
class Foo:
def meth(self):
"""
docstring
indented text
"""
class Bar(Foo):
@functools.lru_cache()
def meth(self):
# inherited and decorated method
pass
assert i... | def test_getdoc_inherited_decorated_method():
| class Foo:
def meth(self):
"""
docstring
indented text
"""
class Bar(Foo):
@functools.lru_cache()
def meth(self):
# inherited and decorated method
pass
assert inspect.getdoc(Bar.meth, getattr, False, Bar, "... | func2.__doc__ = "func2"
func3 = functools.partial(func2, 2) # nested partial object
assert inspect.unpartial(func2) is func1
assert inspect.unpartial(func3) is func1
def test_getdoc_inherited_decorated_method():
| 64 | 64 | 111 | 11 | 52 | rdt12/sphinx | tests/test_util_inspect.py | Python | test_getdoc_inherited_decorated_method | test_getdoc_inherited_decorated_method | 674 | 689 | 674 | 674 | 3e7ac047ca95de8a43daca2ec5cfa7be929850b3 | bigcode/the-stack | train |
ea3d069967ba807761e6ca3e | train | function | def test_signature_annotations():
from .typing_test_data import (Node, f0, f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12,
f13, f14, f15, f16, f17, f18, f19, f20, f21)
# Class annotations
sig = inspect.signature(f0)
assert stringify_signature(sig) == '(x: int, y: n... | def test_signature_annotations():
| from .typing_test_data import (Node, f0, f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12,
f13, f14, f15, f16, f17, f18, f19, f20, f21)
# Class annotations
sig = inspect.signature(f0)
assert stringify_signature(sig) == '(x: int, y: numbers.Integral) -> None'
# G... | arg1, *args, **kwargs)'
sig = inspect.signature(Foo().meth3)
assert stringify_signature(sig) == '(arg1, *args, **kwargs)'
# wrapped bound method
sig = inspect.signature(wrapped_bound_method)
assert stringify_signature(sig) == '(arg1, **kwargs)'
def test_signature_partialmethod():
from functo... | 256 | 256 | 1,112 | 5 | 251 | rdt12/sphinx | tests/test_util_inspect.py | Python | test_signature_annotations | test_signature_annotations | 150 | 263 | 150 | 150 | 8d9eaaf0f8daa7aa10f266591448a1337e4331ca | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.