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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
712632f9c06c7f66a7ff2ac6 | train | function | def unquote_v(nv):
if len(nv) == 1:
return nv
else:
return (nv[0], urllib.parse.unquote(nv[1]))
| def unquote_v(nv):
| if len(nv) == 1:
return nv
else:
return (nv[0], urllib.parse.unquote(nv[1]))
| storageClass is not part of the S3 API.)
'storageClass',
# websiteConfig is a QSA for buckets in Google Cloud
# Storage.
'websiteConfig',
# compose is a QSA for objects in Google Cloud Storage.
'compose']
d... | 64 | 64 | 40 | 7 | 57 | ContextLogic/boto | boto/provider_util.py | Python | unquote_v | unquote_v | 25 | 29 | 25 | 25 | ff94404e5adc3acc8b34d1cd1dd9ec0e2b8ed44d | bigcode/the-stack | train |
f4a97c7ae9137d23e2a8a6c7 | train | function | def canonical_string(method, path, headers, expires=None,
provider=None):
"""
Generates the aws canonical string for the given parameters
"""
if not provider:
provider = boto.provider.get_default()
interesting_headers = {}
for key in headers:
lk = key.lower()... | def canonical_string(method, path, headers, expires=None,
provider=None):
| """
Generates the aws canonical string for the given parameters
"""
if not provider:
provider = boto.provider.get_default()
interesting_headers = {}
for key in headers:
lk = key.lower()
if headers[key] is not None and \
(lk in ['content-md5', 'content-type... | associated to individual keys in S3, but
# having it listed here should cause no problems because
# GET bucket?storageClass is not part of the S3 API.)
'storageClass',
# websiteConfig is a QSA for buckets in Google Cloud
# S... | 140 | 141 | 471 | 16 | 124 | ContextLogic/boto | boto/provider_util.py | Python | canonical_string | canonical_string | 32 | 87 | 32 | 33 | 87752b6f47ac230484dd556af166a4a11873caae | bigcode/the-stack | train |
d2012b2d30a07c6b6889c08f | train | class | class BaseTLDSourceParser(metaclass=Registry):
"""Base TLD source parser."""
uid: Optional[str] = None
source_url: str
local_path: str
include_private: bool = True
@classmethod
def validate(cls):
"""Constructor."""
if not cls.uid:
raise TldImproperlyConfigured(
... | class BaseTLDSourceParser(metaclass=Registry):
| """Base TLD source parser."""
uid: Optional[str] = None
source_url: str
local_path: str
include_private: bool = True
@classmethod
def validate(cls):
"""Constructor."""
if not cls.uid:
raise TldImproperlyConfigured(
"The `uid` property of the TLD ... | None]:
return mcs.REGISTRY.get(key, default)
@classmethod
def items(mcs) -> ItemsView[str, "BaseTLDSourceParser"]:
return mcs.REGISTRY.items()
# @classmethod
# def get_registry(mcs) -> Dict[str, Type]:
# return dict(mcs.REGISTRY)
#
# @classmethod
# def pop(mcs, uid... | 113 | 113 | 377 | 12 | 101 | nrfkhira/dnx-engine | venv/lib64/python3.8/site-packages/tld/base.py | Python | BaseTLDSourceParser | BaseTLDSourceParser | 62 | 118 | 62 | 62 | 8747bac961dd9906b25eb79010c5bd632c841f59 | bigcode/the-stack | train |
16042f70de13dc5111750a7e | train | class | class Registry(type):
REGISTRY: Dict[str, "BaseTLDSourceParser"] = {}
def __new__(mcs, name, bases, attrs):
new_cls = type.__new__(mcs, name, bases, attrs)
# Here the name of the class is used as key but it could be any class
# parameter.
if getattr(new_cls, "_uid", None):
... | class Registry(type):
| REGISTRY: Dict[str, "BaseTLDSourceParser"] = {}
def __new__(mcs, name, bases, attrs):
new_cls = type.__new__(mcs, name, bases, attrs)
# Here the name of the class is used as key but it could be any class
# parameter.
if getattr(new_cls, "_uid", None):
mcs.REGISTRY[ne... | 3-2021 Artur Barseghyan"
__license__ = "MPL-1.1 OR GPL-2.0-only OR LGPL-2.1-or-later"
__all__ = (
"BaseTLDSourceParser",
"Registry",
)
LOGGER = logging.getLogger(__name__)
class Registry(type):
| 69 | 69 | 231 | 4 | 65 | nrfkhira/dnx-engine | venv/lib64/python3.8/site-packages/tld/base.py | Python | Registry | Registry | 23 | 51 | 23 | 24 | af4b4d610f8d1cd45ad222c25ec552e8264730ae | bigcode/the-stack | train |
98aa688bd64282437b14a909 | train | class | class SlackTreesDialogTest(unittest.TestCase):
"""Test dialog works."""
def setUp(self):
"""Runs before each test."""
self.dialog = SlackTreesDialog(None)
def tearDown(self):
"""Runs after each test."""
self.dialog = None
@unittest.skip('Button does not exists any more... | class SlackTreesDialogTest(unittest.TestCase):
| """Test dialog works."""
def setUp(self):
"""Runs before each test."""
self.dialog = SlackTreesDialog(None)
def tearDown(self):
"""Runs after each test."""
self.dialog = None
@unittest.skip('Button does not exists any more')
def test_dialog_ok(self):
"""Tes... | '
import unittest
from PyQt4.QtGui import QDialogButtonBox, QDialog
from slack_trees_dialog import SlackTreesDialog
from utilities import get_qgis_app
QGIS_APP, CANVAS, IFACE, PARENT = get_qgis_app()
class SlackTreesDialogTest(unittest.TestCase):
| 64 | 64 | 213 | 9 | 55 | tobijjah/SlackTrees | test/test_slack_trees_dialog.py | Python | SlackTreesDialogTest | SlackTreesDialogTest | 24 | 55 | 24 | 24 | c53a921b4c4e1066f704f7ae730942a9a97a379f | bigcode/the-stack | train |
684a84cdc083893c94d35b2e | train | function | def set_log_file(filepath):
globals()['log_file'] = filepath
with open(filepath, 'w') as f:
f.write('pelicun\n')
| def set_log_file(filepath):
| globals()['log_file'] = filepath
with open(filepath, 'w') as f:
f.write('pelicun\n')
| python_file = '/'.join(file_path[-3:])
print('WARNING in {} at line {}\n{}\n'.format(python_file, lineno, message))
warnings.showwarning = _warning
def show_warning(warning_msg):
warnings.warn(UserWarning(warning_msg))
def set_log_file(filepath):
| 64 | 64 | 35 | 6 | 58 | 13273781142/pelicun1 | pelicun/base.py | Python | set_log_file | set_log_file | 92 | 95 | 92 | 92 | 65cef91c703e9f60c5417e70e99b486a1c421690 | bigcode/the-stack | train |
e0050de1f7ae46ab270751a9 | train | function | def str2bool(v):
# courtesy of Maxim @ stackoverflow
if isinstance(v, bool):
return v
if v.lower() in ('yes', 'true', 'True', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'False', 'f', 'n', '0'):
return False
else:
raise argparse.ArgumentTypeError('Bo... | def str2bool(v):
# courtesy of Maxim @ stackoverflow
| if isinstance(v, bool):
return v
if v.lower() in ('yes', 'true', 'True', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'False', 'f', 'n', '0'):
return False
else:
raise argparse.ArgumentTypeError('Boolean value expected.')
| %': df_10,
'50%': df_50,
'90%': df_90,
'max': np.nanmax(vals, axis=0),
}, index=cols).T
return desc
def str2bool(v):
# courtesy of Maxim @ stackoverflow
| 64 | 64 | 96 | 15 | 48 | 13273781142/pelicun1 | pelicun/base.py | Python | str2bool | str2bool | 161 | 171 | 161 | 163 | 995d83b9eff1669350752635a098b899a172cbdb | bigcode/the-stack | train |
63646662b46eac7569d24f6d | train | function | def describe(df):
if isinstance(df, (pd.Series, pd.DataFrame)):
vals = df.values
if isinstance(df, pd.DataFrame):
cols = df.columns
elif df.name is not None:
cols = df.name
else:
cols = 0
else:
vals = df
cols = np.arange(vals.s... | def describe(df):
| if isinstance(df, (pd.Series, pd.DataFrame)):
vals = df.values
if isinstance(df, pd.DataFrame):
cols = df.columns
elif df.name is not None:
cols = df.name
else:
cols = 0
else:
vals = df
cols = np.arange(vals.shape[1]) if vals.nd... |
----------
msg: string
Message to print.
"""
if prepend_timestamp:
formatted_msg = '{} {}'.format(datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S:%fZ')[:-4], msg)
else:
formatted_msg = msg
#print(formatted_msg)
if globals()['log_file'] is not None:
with open(... | 108 | 108 | 361 | 4 | 104 | 13273781142/pelicun1 | pelicun/base.py | Python | describe | describe | 120 | 159 | 120 | 121 | f829976e35044b9ea2f2d516f2d9c6e7912006ce | bigcode/the-stack | train |
04912461ff99158cc20e5750 | train | function | def show_warning(warning_msg):
warnings.warn(UserWarning(warning_msg))
| def show_warning(warning_msg):
| warnings.warn(UserWarning(warning_msg))
| ('\\')
elif '/' in filename:
file_path = filename.split('/')
python_file = '/'.join(file_path[-3:])
print('WARNING in {} at line {}\n{}\n'.format(python_file, lineno, message))
warnings.showwarning = _warning
def show_warning(warning_msg):
| 64 | 64 | 16 | 7 | 56 | 13273781142/pelicun1 | pelicun/base.py | Python | show_warning | show_warning | 89 | 90 | 89 | 89 | c12177727196914fa2d75067f6845db8648e202b | bigcode/the-stack | train |
5b1edb94d26bf0078d4cd824 | train | function | def show_matrix(data, describe=False):
if describe:
pp.pprint(pd.DataFrame(data).describe(percentiles=[0.01,0.1,0.5,0.9,0.99]))
else:
pp.pprint(pd.DataFrame(data))
| def show_matrix(data, describe=False):
| if describe:
pp.pprint(pd.DataFrame(data).describe(percentiles=[0.01,0.1,0.5,0.9,0.99]))
else:
pp.pprint(pd.DataFrame(data))
| # 21 to have a total length of 80 with the time added
# get the absolute path of the pelicun directory
pelicun_path = os.path.dirname(os.path.abspath(__file__))
# print a matrix in a nice way using a DataFrame
def show_matrix(data, describe=False):
| 64 | 64 | 57 | 8 | 55 | 13273781142/pelicun1 | pelicun/base.py | Python | show_matrix | show_matrix | 73 | 77 | 73 | 73 | d81683020669be5636e837dd4de5493458ab73ec | bigcode/the-stack | train |
a9f76268dd7da64108121bf9 | train | function | def log_msg(msg='', prepend_timestamp=True):
"""
Print a message to the screen with the current time as prefix
The time is in ISO-8601 format, e.g. 2018-06-16T20:24:04Z
Parameters
----------
msg: string
Message to print.
"""
if prepend_timestamp:
formatted_msg = '{} {}'... | def log_msg(msg='', prepend_timestamp=True):
| """
Print a message to the screen with the current time as prefix
The time is in ISO-8601 format, e.g. 2018-06-16T20:24:04Z
Parameters
----------
msg: string
Message to print.
"""
if prepend_timestamp:
formatted_msg = '{} {}'.format(datetime.utcnow().strftime('%Y-%m-%dT... | = _warning
def show_warning(warning_msg):
warnings.warn(UserWarning(warning_msg))
def set_log_file(filepath):
globals()['log_file'] = filepath
with open(filepath, 'w') as f:
f.write('pelicun\n')
def log_msg(msg='', prepend_timestamp=True):
| 64 | 64 | 160 | 9 | 55 | 13273781142/pelicun1 | pelicun/base.py | Python | log_msg | log_msg | 97 | 118 | 97 | 97 | 6c9882c3291895eb158d5525110e28d359c51472 | bigcode/the-stack | train |
aa111688605fdcf2d64a718d | train | function | def _warning(message, category, filename, lineno, file=None, line=None):
if '\\' in filename:
file_path = filename.split('\\')
elif '/' in filename:
file_path = filename.split('/')
python_file = '/'.join(file_path[-3:])
print('WARNING in {} at line {}\n{}\n'.format(python_file, lineno, m... | def _warning(message, category, filename, lineno, file=None, line=None):
| if '\\' in filename:
file_path = filename.split('\\')
elif '/' in filename:
file_path = filename.split('/')
python_file = '/'.join(file_path[-3:])
print('WARNING in {} at line {}\n{}\n'.format(python_file, lineno, message))
| ).describe(percentiles=[0.01,0.1,0.5,0.9,0.99]))
else:
pp.pprint(pd.DataFrame(data))
# Monkeypatch warnings to get prettier messages
def _warning(message, category, filename, lineno, file=None, line=None):
| 64 | 64 | 81 | 18 | 45 | 13273781142/pelicun1 | pelicun/base.py | Python | _warning | _warning | 80 | 86 | 80 | 80 | 66c7430dd7d4c84872c264605d44c8a58bfa4d93 | bigcode/the-stack | train |
0a10d5ea7d0fac9002205b13 | train | function | def mp2(hamiltonian, orbs, orbe, nocc, nvirt, verbose=False):
ints = hamiltonian.i2
moints = ints.transform_mp2(orbs, nocc)
Evirt, Eocc = orbe[nocc:], orbe[:nocc]
denominator = 1/(Eocc.reshape(-1, 1, 1, 1) - Evirt.reshape(1, -1, 1, 1) +
Eocc.reshape(1, 1, -1, 1) - Evirt.reshape(1, ... | def mp2(hamiltonian, orbs, orbe, nocc, nvirt, verbose=False):
| ints = hamiltonian.i2
moints = ints.transform_mp2(orbs, nocc)
Evirt, Eocc = orbe[nocc:], orbe[:nocc]
denominator = 1/(Eocc.reshape(-1, 1, 1, 1) - Evirt.reshape(1, -1, 1, 1) +
Eocc.reshape(1, 1, -1, 1) - Evirt.reshape(1, 1, 1, -1))
MP2corr_OS = np.einsum('iajb,iajb,iajb->', moi... | import numpy as np
def mp2(hamiltonian, orbs, orbe, nocc, nvirt, verbose=False):
| 29 | 64 | 214 | 24 | 4 | Konjkov/pyquante2 | pyquante2/pt/mp2.py | Python | mp2 | mp2 | 4 | 14 | 4 | 4 | 86873fbdbae4ef6c2237b40ffc58a50846d4f6c1 | bigcode/the-stack | train |
2872acecb95126e5447002a7 | train | function | def I106_SetRelTime(handle, irig_time, rel_time):
# handle - IRIG file handle
# irig_time - Py106 time object holding absolute time
# rel_time - 6 byte ctypes array with relative time count (usually from the packet header)
ctype_irig_time = _ctIrig106Time()
ctype_irig_time.set_from_IrigTime(iri... | def I106_SetRelTime(handle, irig_time, rel_time):
# handle - IRIG file handle
# irig_time - Py106 time object holding absolute time
# rel_time - 6 byte ctypes array with relative time count (usually from the packet header)
| ctype_irig_time = _ctIrig106Time()
ctype_irig_time.set_from_IrigTime(irig_time)
ret_status = packet.irig_data_dll.enI106_SetRelTime(handle, ctypes.byref(ctype_irig_time), rel_time)
return ret_status
|
# ---------------------------------------------------------------------------
def I106_SetRelTime(handle, irig_time, rel_time):
# handle - IRIG file handle
# irig_time - Py106 time object holding absolute time
# rel_time - 6 byte ctypes array with relative time count (usually from the packet header)
| 63 | 64 | 123 | 59 | 4 | SethRobertson/irig106lib | python/Py106/time.py | Python | I106_SetRelTime | I106_SetRelTime | 49 | 56 | 49 | 52 | 4a3cb9e8fd41974bc24f71cca0c1a7d94e2b36d1 | bigcode/the-stack | train |
b4a24727d82721ecf08ee02e | train | class | class Time(object):
""" IRIG time handling for an open file """
def __init__(self, packet_io):
self.packet_io = packet_io
def set_rel_time(self):
"""Set relative time to clock time"""
# This routine assumes a time packet has been read and is sitting in
... | class Time(object):
| """ IRIG time handling for an open file """
def __init__(self, packet_io):
self.packet_io = packet_io
def set_rel_time(self):
"""Set relative time to clock time"""
# This routine assumes a time packet has been read and is sitting in
# the packet_io ... | class IrigTime(object):
""" Py106 native IRIG time value """
def __init___(self):
self.time = datetime()
self.dt_format = DateFmt.DAY
def __str__(self):
return I106_IrigTime2String(self)
def set_from_ctIrig106Time(self, ctype_irig_time):
self.time ... | 148 | 148 | 496 | 4 | 143 | SethRobertson/irig106lib | python/Py106/time.py | Python | Time | Time | 136 | 197 | 136 | 136 | cd7072d342ca78929dc3df09ff479c15f970e100 | bigcode/the-stack | train |
5762d035df99a27c4f11c669 | train | function | def I106_RelInt2IrigTime(handle, rel_time):
""" Convert a 64 bit integer relative time to absolute time """
# handle - IRIG file handle
# rel_time - 64 integer with relative time count (usually from a message header)
# irig_time - Py106 time object holding absolute time
ctype_rel_time = ctypes... | def I106_RelInt2IrigTime(handle, rel_time):
| """ Convert a 64 bit integer relative time to absolute time """
# handle - IRIG file handle
# rel_time - 64 integer with relative time count (usually from a message header)
# irig_time - Py106 time object holding absolute time
ctype_rel_time = ctypes.c_uint64(rel_time)
ctype_irig_time = _c... | (handle, rel_time, ctypes.byref(ctype_irig_time))
irig_time = IrigTime()
irig_time.set_from_ctIrig106Time(ctype_irig_time)
return ret_status, irig_time
def I106_RelInt2IrigTime(handle, rel_time):
| 64 | 64 | 170 | 15 | 48 | SethRobertson/irig106lib | python/Py106/time.py | Python | I106_RelInt2IrigTime | I106_RelInt2IrigTime | 79 | 89 | 79 | 79 | cb895085d817f81d67ab7551c26d2b287bec41eb | bigcode/the-stack | train |
c70e5d805f787f8d75f97950 | train | function | def I106_IrigTime2String(irig_time_in):
""" Convert a Py106 IRIG time to a string """
# irig_time_in - Py106 time object holding absolute time
# Returns a string representation of time in either Day or DMY format
try:
assert type(irig_time_in) is IrigTime
iTime = _ctIrig... | def I106_IrigTime2String(irig_time_in):
| """ Convert a Py106 IRIG time to a string """
# irig_time_in - Py106 time object holding absolute time
# Returns a string representation of time in either Day or DMY format
try:
assert type(irig_time_in) is IrigTime
iTime = _ctIrig106Time()
iTime.Secs = cal... | (handle, ctype_rel_time, ctypes.byref(ctype_irig_time))
irig_time = IrigTime()
irig_time.set_from_ctIrig106Time(ctype_irig_time)
return ret_status, irig_time
def I106_IrigTime2String(irig_time_in):
| 64 | 64 | 199 | 13 | 50 | SethRobertson/irig106lib | python/Py106/time.py | Python | I106_IrigTime2String | I106_IrigTime2String | 92 | 108 | 92 | 92 | 0817855ce42a714ab05f6b4b66d514fbfb2980bb | bigcode/the-stack | train |
0b94f881743796e50a75e292 | train | class | class _ctIrig106Time(ctypes.Structure):
""" Ctypes data structure for IRIG library time representation """
_pack_ = 1
_fields_ = [("Secs", ctypes.c_uint64), # This is a time_t
("Fracs", ctypes.c_uint32), # LSB = 100ns
("DateFormat", ctypes... | class _ctIrig106Time(ctypes.Structure):
| """ Ctypes data structure for IRIG library time representation """
_pack_ = 1
_fields_ = [("Secs", ctypes.c_uint64), # This is a time_t
("Fracs", ctypes.c_uint32), # LSB = 100ns
("DateFormat", ctypes.c_uint32)] # Day or DMY format
... | """ Packet Message Types """
DAY = 0x00 # Day of Year format
DMY = 0x01 # Day, Month, Year format
# ---------------------------------------------------------------------------
# IRIG time structures
# ---------------------------------------------------------------------------
class _... | 63 | 64 | 158 | 12 | 51 | SethRobertson/irig106lib | python/Py106/time.py | Python | _ctIrig106Time | _ctIrig106Time | 31 | 42 | 31 | 31 | 3c064466758d04c451477e2e17f158e0bac22fdf | bigcode/the-stack | train |
841545416f284a23f59d6943 | train | function | def I106_Rel2IrigTime(handle, rel_time):
""" Convert a 6 byte relative time to absolute time """
# handle - IRIG file handle
# rel_time - 6 byte ctypes array with relative time count (usually from the packet header)
# irig_time - Py106 time object holding absolute time
ctype_irig_time = _ctIrig... | def I106_Rel2IrigTime(handle, rel_time):
| """ Convert a 6 byte relative time to absolute time """
# handle - IRIG file handle
# rel_time - 6 byte ctypes array with relative time count (usually from the packet header)
# irig_time - Py106 time object holding absolute time
ctype_irig_time = _ctIrig106Time()
ret_status = packet.irig_da... | source must be externally sync'ed to be valid
# time_limit = Maximum amount of time in seconds to scan forward in the file
return packet.irig_data_dll.enI106_SyncTime(handle, require_sync, time_limit)
def I106_Rel2IrigTime(handle, rel_time):
| 64 | 64 | 153 | 14 | 50 | SethRobertson/irig106lib | python/Py106/time.py | Python | I106_Rel2IrigTime | I106_Rel2IrigTime | 67 | 76 | 67 | 67 | 164ab98fd0883645faec7af23a1877fe100c8867 | bigcode/the-stack | train |
601182976485bd33ac11bfc9 | train | class | class DateFmt(object):
""" Packet Message Types """
DAY = 0x00 # Day of Year format
DMY = 0x01 # Day, Month, Year format
| class DateFmt(object):
| """ Packet Message Types """
DAY = 0x00 # Day of Year format
DMY = 0x01 # Day, Month, Year format
| import traceback
import datetime
import calendar
#from datetime import date
#from time import time
import Py106.packet as packet
import Py106.status as status
import Py106.MsgDecodeTime as MsgDecodeTime
# ---------------------------------------------------------------------------
# IRIG time cons... | 63 | 64 | 44 | 5 | 58 | SethRobertson/irig106lib | python/Py106/time.py | Python | DateFmt | DateFmt | 21 | 24 | 21 | 21 | 8cc43c783ed51d7bdbc66a75b3a2b989195449d9 | bigcode/the-stack | train |
595fb92dc6a38470f3721d1c | train | class | class IrigTime(object):
""" Py106 native IRIG time value """
def __init___(self):
self.time = datetime()
self.dt_format = DateFmt.DAY
def __str__(self):
return I106_IrigTime2String(self)
def set_from_ctIrig106Time(self, ctype_irig_time):
self.time ... | class IrigTime(object):
| """ Py106 native IRIG time value """
def __init___(self):
self.time = datetime()
self.dt_format = DateFmt.DAY
def __str__(self):
return I106_IrigTime2String(self)
def set_from_ctIrig106Time(self, ctype_irig_time):
self.time = datetime.datetime.... | except AssertionError:
print ("Not class IrigTime - %s" % (type(irig_time_in)))
return ""
except:
return ""
# ---------------------------------------------------------------------------
# IRIG time classes
# ------------------------------------------------... | 64 | 64 | 128 | 6 | 57 | SethRobertson/irig106lib | python/Py106/time.py | Python | IrigTime | IrigTime | 117 | 129 | 117 | 117 | 400c89f0e02bf3787b93e47b5a7235de23940be6 | bigcode/the-stack | train |
45ee90ca7af8b3f91f164966 | train | function | def I106_SyncTime(handle, require_sync, time_limit):
""" Search for time and set relative to absolute time reference"""
# handle - IRIG file handle
# require_sync - Bool indicating whether time source must be externally sync'ed to be valid
# time_limit = Maximum amount of time in seconds to scan for... | def I106_SyncTime(handle, require_sync, time_limit):
| """ Search for time and set relative to absolute time reference"""
# handle - IRIG file handle
# require_sync - Bool indicating whether time source must be externally sync'ed to be valid
# time_limit = Maximum amount of time in seconds to scan forward in the file
return packet.irig_data_dll.enI... | ctype_irig_time.set_from_IrigTime(irig_time)
ret_status = packet.irig_data_dll.enI106_SetRelTime(handle, ctypes.byref(ctype_irig_time), rel_time)
return ret_status
def I106_SyncTime(handle, require_sync, time_limit):
| 64 | 64 | 95 | 14 | 49 | SethRobertson/irig106lib | python/Py106/time.py | Python | I106_SyncTime | I106_SyncTime | 59 | 64 | 59 | 59 | 3c245779b9974df0385a13b84c2aeb2c3f9900fe | bigcode/the-stack | train |
dd9c342696a759586c2cee7f | train | function | def main() -> None:
load_dotenv()
"""Start the bot."""
# Create the Updater and pass it to your bot's token.
updater = Updater(os.getenv('BOT_TOKEN'), use_context=True)
# Get the dispatcher to register handlers
dispatcher = updater.dispatcher
conv_handler = ConversationHandler(
# i... | def main() -> None:
| load_dotenv()
"""Start the bot."""
# Create the Updater and pass it to your bot's token.
updater = Updater(os.getenv('BOT_TOKEN'), use_context=True)
# Get the dispatcher to register handlers
dispatcher = updater.dispatcher
conv_handler = ConversationHandler(
# initiate the conversa... | import logging
import os
from dotenv import load_dotenv
from models.TradingBot import TradingBot
from telegram.ext import (
Updater,
CommandHandler,
MessageHandler,
Filters,
ConversationHandler,
)
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
... | 89 | 171 | 572 | 6 | 83 | snelj/content-telegram-bot | main.py | Python | main | main | 21 | 72 | 21 | 21 | 343a9db663bd602386b9bd509c43010beb62fa1a | bigcode/the-stack | train |
a16436e41a0bfcd01fdf9848 | train | class | class StreetCivicPolicySelectorMixin(HasTunableSingletonFactory, AutoFactoryInit):
FACTORY_TUNABLES = {'street': TunableVariant(description='\n Select what street to test.\n ', literal=TunablePackSafeReference(description='\n Identify a specific Street.\n ', manag... | class StreetCivicPolicySelectorMixin(HasTunableSingletonFactory, AutoFactoryInit):
| FACTORY_TUNABLES = {'street': TunableVariant(description='\n Select what street to test.\n ', literal=TunablePackSafeReference(description='\n Identify a specific Street.\n ', manager=services.get_instance_manager(sims4.resources.Types.STREET)), via_zone_source=Tu... | SingletonFactory, AutoFactoryInit):
def get_expected_args(self):
return {'subjects': ParticipantType.Street}
def get_street(self, *, subjects):
street_service = services.street_service()
if street_service is None:
return
if not subjects:
logger.error('Fa... | 103 | 103 | 344 | 18 | 85 | NeonOcean/Environment | S4/S4 Library/simulation/civic_policies/street_civic_policy_tuning.py | Python | StreetCivicPolicySelectorMixin | StreetCivicPolicySelectorMixin | 22 | 45 | 22 | 22 | 2f5cfad5e265b1adfdbb149e18813b5dc1fd6770 | bigcode/the-stack | train |
181cb38a4d350a5bf501fe3a | train | class | class StreetParticipant(HasTunableSingletonFactory, AutoFactoryInit):
def get_expected_args(self):
return {'subjects': ParticipantType.Street}
def get_street(self, *, subjects):
street_service = services.street_service()
if street_service is None:
return
if not subj... | class StreetParticipant(HasTunableSingletonFactory, AutoFactoryInit):
| def get_expected_args(self):
return {'subjects': ParticipantType.Street}
def get_street(self, *, subjects):
street_service = services.street_service()
if street_service is None:
return
if not subjects:
logger.error('Failed to resolve participant Participa... | AutoFactoryInit
from zone_tests import ActiveZone, PickInfoZone, PickedZoneIds, ParticipantHomeZone
from interactions import ParticipantType
import services
import sims4
logger = sims4.log.Logger('Street Civic Policy Tuning')
class StreetParticipant(HasTunableSingletonFactory, AutoFactoryInit):
| 64 | 64 | 92 | 14 | 50 | NeonOcean/Environment | S4/S4 Library/simulation/civic_policies/street_civic_policy_tuning.py | Python | StreetParticipant | StreetParticipant | 8 | 20 | 8 | 9 | 47acb20c5ee76f2673139620f1058c12aae4c851 | bigcode/the-stack | train |
631a982d7520181cae94e929 | train | function | def generate(pattern, replace="X", chars=string.digits):
return "".join(
(random.choice(chars) if ch == replace else ch)
for ch in pattern
)
| def generate(pattern, replace="X", chars=string.digits):
| return "".join(
(random.choice(chars) if ch == replace else ch)
for ch in pattern
)
| UMERIC_ALL = string.digits + string.ascii_letters
ALPHANUMERIC_LOWER = string.digits + string.ascii_lowercase
ALPHANUMERIC_UPPER = string.digits + string.ascii_uppercase
def generate(pattern, replace="X", chars=string.digits):
| 64 | 64 | 40 | 14 | 49 | ammongit/scripts | fun/random-pattern.py | Python | generate | generate | 26 | 30 | 26 | 26 | fc1711118202f61a50c131d0860dce435d48dd20 | bigcode/the-stack | train |
389aa093a33e2c81a9a725a6 | train | function | def test_hpfilter_pandas():
dta = macrodata.load_pandas().data
index = DatetimeIndex(start='1959-01-01', end='2009-10-01', freq='Q')
dta.index = index
cycle, trend = hpfilter(dta["realgdp"])
ndcycle, ndtrend = hpfilter(dta['realgdp'].values)
assert_equal(cycle.values, ndcycle)
assert_equal(c... | def test_hpfilter_pandas():
| dta = macrodata.load_pandas().data
index = DatetimeIndex(start='1959-01-01', end='2009-10-01', freq='Q')
dta.index = index
cycle, trend = hpfilter(dta["realgdp"])
ndcycle, ndtrend = hpfilter(dta['realgdp'].values)
assert_equal(cycle.values, ndcycle)
assert_equal(cycle.index[0], datetime(1959... | 14)
assert_equal(cycle.index[0], datetime(1959, 3, 31))
assert_equal(cycle.index[-1], datetime(2009, 9, 30))
assert_equal(cycle.columns.values, ["infl", "unemp"])
def test_hpfilter_pandas():
| 64 | 64 | 148 | 7 | 57 | larsoner/statsmodels | statsmodels/tsa/filters/tests/test_filters.py | Python | test_hpfilter_pandas | test_hpfilter_pandas | 582 | 591 | 582 | 582 | 8cb5557aae1874154f41f6e31102ddda62e98ab7 | bigcode/the-stack | train |
9866a9b989c4a68a7d4ed14d | train | function | def test_bking1d():
# Test Baxter King band-pass filter. Results are taken from Stata
bking_results = array([7.320813, 2.886914, -6.818976, -13.49436,
-13.27936, -9.405913, -5.691091, -5.133076, -7.273468,
-9.243364, -8.482916, -4.447764, 2.406559, 10.68433,
19.46... | def test_bking1d():
# Test Baxter King band-pass filter. Results are taken from Stata
| bking_results = array([7.320813, 2.886914, -6.818976, -13.49436,
-13.27936, -9.405913, -5.691091, -5.133076, -7.273468,
-9.243364, -8.482916, -4.447764, 2.406559, 10.68433,
19.46414, 28.09749, 34.11066, 33.48468, 24.64598, 9.952399,
-4.265528, -12.5947... | from datetime import datetime
import numpy as np
from numpy.testing import (assert_almost_equal, assert_equal, assert_allclose,
assert_raises, assert_)
from numpy import array, column_stack
from statsmodels.datasets import macrodata
from pandas import Index, DataFrame, DatetimeIndex, concat
f... | 113 | 256 | 1,172 | 23 | 90 | larsoner/statsmodels | statsmodels/tsa/filters/tests/test_filters.py | Python | test_bking1d | test_bking1d | 12 | 52 | 12 | 13 | 106608f8599da2a20c7e66092c5cce76366ccdd1 | bigcode/the-stack | train |
af7561ecff4a70c8924d9a98 | train | function | def test_hpfilter():
# Test Hodrick-Prescott Filter. Results taken from Stata.
hpfilt_res = array([[3.951191484487844718e+01,2.670837085155121713e+03],
[8.008853245681075350e+01,2.698712467543189177e+03],
[4.887545512195401898e+01,2.726612544878045810e+03],
[3.059193256079834100e+01,2.75... | def test_hpfilter():
# Test Hodrick-Prescott Filter. Results taken from Stata.
| hpfilt_res = array([[3.951191484487844718e+01,2.670837085155121713e+03],
[8.008853245681075350e+01,2.698712467543189177e+03],
[4.887545512195401898e+01,2.726612544878045810e+03],
[3.059193256079834100e+01,2.754612067439201837e+03],
[6.488266733421960453e+01,2.782816332665780465e+03],... | .11596,-.390683], [-104.2051,-.5647846],
[-114.0125,-.9397582], [-113.3475,-1.341633], [-92.98669,-1.567337],
[-51.91707,-1.504943], [-.7313812,-1.30576], [43.22938,-1.17151],
[64.62762,-1.136151], [64.07226,-1.050555], [59.35707,-.7308369],
[67.06026,-.1766731], [91.87247,.3898467], [12... | 256 | 256 | 5,350 | 21 | 235 | larsoner/statsmodels | statsmodels/tsa/filters/tests/test_filters.py | Python | test_hpfilter | test_hpfilter | 121 | 328 | 121 | 122 | dbf02effc0dc371060ff1388d7f77e667f39a2d7 | bigcode/the-stack | train |
9efb63d63d27d7cfb1886c5e | train | function | def test_cfitz_pandas():
# 1d
dta = macrodata.load_pandas().data
index = DatetimeIndex(start='1959-01-01', end='2009-10-01', freq='Q')
dta.index = index
cycle, trend = cffilter(dta["infl"])
ndcycle, ndtrend = cffilter(dta['infl'].values)
assert_allclose(cycle.values, ndcycle, rtol=1e-14)
... | def test_cfitz_pandas():
# 1d
| dta = macrodata.load_pandas().data
index = DatetimeIndex(start='1959-01-01', end='2009-10-01', freq='Q')
dta.index = index
cycle, trend = cffilter(dta["infl"])
ndcycle, ndtrend = cffilter(dta['infl'].values)
assert_allclose(cycle.values, ndcycle, rtol=1e-14)
assert_equal(cycle.index[0], date... | ', 'unemp']].values)
assert_equal(filtered.values, nd_filtered)
assert_equal(filtered.index[0], datetime(1962, 3, 31))
assert_equal(filtered.index[-1], datetime(2006, 9, 30))
assert_equal(filtered.columns.values, ["infl", "unemp"])
def test_cfitz_pandas():
# 1d
| 83 | 83 | 279 | 14 | 69 | larsoner/statsmodels | statsmodels/tsa/filters/tests/test_filters.py | Python | test_cfitz_pandas | test_cfitz_pandas | 562 | 580 | 562 | 563 | 173d138b64a279931a17eb1841b304dec1e548be | bigcode/the-stack | train |
c2857696fbf96c20bd157c47 | train | class | class TestFilters(object):
@classmethod
def setupClass(cls):
# even
data = [-50, 175, 149, 214, 247, 237, 225, 329, 729, 809,
530, 489, 540, 457, 195, 176, 337, 239, 128, 102,
232, 429, 3, 98, 43, -141, -77, -13, 125, 361, -45, 184]
cls.data = DataFrame(da... | class TestFilters(object):
@classmethod
| def setupClass(cls):
# even
data = [-50, 175, 149, 214, 247, 237, 225, 329, 729, 809,
530, 489, 540, 457, 195, 176, 337, 239, 128, 102,
232, 429, 3, 98, 43, -141, -77, -13, 125, 361, -45, 184]
cls.data = DataFrame(data, DatetimeIndex(start='1/1/1951',
... | emp"]])
ndcycle, ndtrend = cffilter(dta[['infl', 'unemp']].values)
assert_allclose(cycle.values, ndcycle, rtol=1e-14)
assert_equal(cycle.index[0], datetime(1959, 3, 31))
assert_equal(cycle.index[-1], datetime(2009, 9, 30))
assert_equal(cycle.columns.values, ["infl", "unemp"])
def test_hpfilter_pand... | 256 | 256 | 1,402 | 9 | 247 | larsoner/statsmodels | statsmodels/tsa/filters/tests/test_filters.py | Python | TestFilters | TestFilters | 594 | 728 | 594 | 595 | b9b8fff93f9dcb08813d63c1227c50054e5b8755 | bigcode/the-stack | train |
65b61a5a86d6b885a9d69634 | train | function | def test_bking_pandas():
# 1d
dta = macrodata.load_pandas().data
index = DatetimeIndex(start='1959-01-01', end='2009-10-01', freq='Q')
dta.index = index
filtered = bkfilter(dta["infl"])
nd_filtered = bkfilter(dta['infl'].values)
assert_equal(filtered.values, nd_filtered)
assert_equal(fil... | def test_bking_pandas():
# 1d
| dta = macrodata.load_pandas().data
index = DatetimeIndex(start='1959-01-01', end='2009-10-01', freq='Q')
dta.index = index
filtered = bkfilter(dta["infl"])
nd_filtered = bkfilter(dta['infl'].values)
assert_equal(filtered.values, nd_filtered)
assert_equal(filtered.index[0], datetime(1962, 3, ... | cffilter(dta)
assert_almost_equal(cyc, cfilt_res, 8)
#do 1d
cyc, trend = cffilter(dta[:,1])
assert_almost_equal(cyc, cfilt_res[:,1], 8)
def test_bking_pandas():
# 1d
| 71 | 71 | 238 | 13 | 58 | larsoner/statsmodels | statsmodels/tsa/filters/tests/test_filters.py | Python | test_bking_pandas | test_bking_pandas | 542 | 560 | 542 | 543 | cafb923d579a5ae6ca157885542b1fa1373cfe2c | bigcode/the-stack | train |
77a7fd0f0e3e264073751874 | train | function | def test_cfitz_filter():
# Test Christiano-Fitzgerald Filter. Results taken from R.
# NOTE: The Stata mata code and the matlab code it's based on are wrong.
cfilt_res = array([[0.712599537179426,0.439563468233128],
[1.06824041304411,0.352886666575907],
[1.1942... | def test_cfitz_filter():
# Test Christiano-Fitzgerald Filter. Results taken from R.
# NOTE: The Stata mata code and the matlab code it's based on are wrong.
| cfilt_res = array([[0.712599537179426,0.439563468233128],
[1.06824041304411,0.352886666575907],
[1.19422467791128,0.257297004260607],
[0.970845473140327,0.114504692143872],
[0.467026976628563,-0.070734782329146],
... | 02,1.316244290342607383e+04],
[2.213739418903714977e+02,1.319389205810962812e+04],
[1.020184547767112235e+02,1.322258154522328914e+04],
[-1.072694716663390864e+02,1.324918947166633916e+04],
[-3.490477058718843182e+02,1.327445770587188417e+04],
[-3.975570728533530200e+02,1.3299061... | 256 | 256 | 3,787 | 41 | 215 | larsoner/statsmodels | statsmodels/tsa/filters/tests/test_filters.py | Python | test_cfitz_filter | test_cfitz_filter | 330 | 540 | 330 | 332 | 5ca5f3988ed7f285fe0ad8f8bdb16fc22ef23ed3 | bigcode/the-stack | train |
ff667dbc8260c3b3fceb5659 | train | function | def test_bking2d():
# Test Baxter-King band-pass filter with 2d input
bking_results = array([[7.320813,-.0374475], [2.886914,-.0430094],
[-6.818976,-.053456], [-13.49436,-.0620739], [-13.27936,-.0626929],
[-9.405913,-.0603022], [-5.691091,-.0630016], [-5.133076,-.0832268],
[-7.273468,-.1... | def test_bking2d():
# Test Baxter-King band-pass filter with 2d input
| bking_results = array([[7.320813,-.0374475], [2.886914,-.0430094],
[-6.818976,-.053456], [-13.49436,-.0620739], [-13.27936,-.0626929],
[-9.405913,-.0603022], [-5.691091,-.0630016], [-5.133076,-.0832268],
[-7.273468,-.1186448], [-9.243364,-.1619868], [-8.482916,-.2116604],
[-4.447764,... | 47801, 49.05027,
59.02925,
72.88999, 95.08865, 125.8983, 154.4283, 160.7638, 130.6092,
67.84406, -7.070272, -68.08128, -99.39944, -104.911,
-100.2372, -98.11596, -104.2051, -114.0125, -113.3475,
-92.98669, -51.91707, -.7313812, 43.22938, 64... | 256 | 256 | 2,036 | 22 | 234 | larsoner/statsmodels | statsmodels/tsa/filters/tests/test_filters.py | Python | test_bking2d | test_bking2d | 54 | 119 | 54 | 55 | b92a44b16efb05078c83f54d20b7c8c4be85e9f1 | bigcode/the-stack | train |
2c5af8d58811f108c134d6fd | train | class | class DeviotSelectPortCommand(WindowCommand):
def run(self):
Quick = QuickMenu()
items = Quick.serial_list()
callback = Quick.callback_serial_ports
Quick.set_list(items)
Quick.show_quick_panel(callback)
| class DeviotSelectPortCommand(WindowCommand):
| def run(self):
Quick = QuickMenu()
items = Quick.serial_list()
callback = Quick.callback_serial_ports
Quick.set_list(items)
Quick.show_quick_panel(callback)
| from sublime_plugin import WindowCommand
from ..libraries.quick_menu import QuickMenu
class DeviotSelectPortCommand(WindowCommand):
| 25 | 64 | 49 | 9 | 15 | Rod-O/Deviot | commands/deviot_select_port.py | Python | DeviotSelectPortCommand | DeviotSelectPortCommand | 5 | 12 | 5 | 5 | 85b78d2f2bed510b1ee862deaf7d4e3b133f4a51 | bigcode/the-stack | train |
d58a90037e5ec356fa0c993e | train | class | class Entry(GraphicsObject):
def __init__(self, p, width):
GraphicsObject.__init__(self, [])
self.anchor = p.clone()
#print self.anchor
self.width = width
self.text = tk.StringVar(_root)
self.text.set("")
self.fill = "gray"
self.color = "black"
... | class Entry(GraphicsObject):
| def __init__(self, p, width):
GraphicsObject.__init__(self, [])
self.anchor = p.clone()
#print self.anchor
self.width = width
self.text = tk.StringVar(_root)
self.text.set("")
self.fill = "gray"
self.color = "black"
self.font = DEFAULT_CONFIG['... | roman']:
f,s,b = self.config['font']
self._reconfig("font",(face,s,b))
else:
raise GraphicsError(BAD_OPTION)
def setSize(self, size):
if 5 <= size <= 36:
f,s,b = self.config['font']
self._reconfig("font", (f,size,b))
else:
... | 165 | 165 | 550 | 5 | 160 | andrsharov/python-study | mipt_cs_on_python3/lab4/graphics.py | Python | Entry | Entry | 783 | 871 | 783 | 784 | fdf6eb46b745e2754551987c96ccb19cd5641a87 | bigcode/the-stack | train |
caafb90a78a79cda68d34c35 | train | class | class Oval(_BBox):
def __init__(self, p1, p2):
_BBox.__init__(self, p1, p2)
def __repr__(self):
return "Oval({}, {})".format(str(self.p1), str(self.p2))
def clone(self):
other = Oval(self.p1, self.p2)
other.config = self.config.copy()
return other
... | class Oval(_BBox):
| def __init__(self, p1, p2):
_BBox.__init__(self, p1, p2)
def __repr__(self):
return "Oval({}, {})".format(str(self.p1), str(self.p2))
def clone(self):
other = Oval(self.p1, self.p2)
other.config = self.config.copy()
return other
def _draw(self, canv... | 2 = canvas.toScreen(p2.x,p2.y)
return canvas.create_rectangle(x1,y1,x2,y2,options)
def clone(self):
other = Rectangle(self.p1, self.p2)
other.config = self.config.copy()
return other
class Oval(_BBox):
| 64 | 64 | 163 | 6 | 57 | andrsharov/python-study | mipt_cs_on_python3/lab4/graphics.py | Python | Oval | Oval | 622 | 641 | 622 | 623 | ef3aea732c749809c041aae721bd72e588a5840d | bigcode/the-stack | train |
2f68b831f7b6e5ac2b40d934 | train | function | def test():
win = GraphWin()
win.setCoords(0,0,10,10)
t = Text(Point(5,5), "Centered Text")
t.draw(win)
p = Polygon(Point(1,1), Point(5,3), Point(2,7))
p.draw(win)
e = Entry(Point(5,6), 10)
e.draw(win)
win.getMouse()
p.setFill("red")
p.setOutline("blue")
p.setWidth(2)
... | def test():
| win = GraphWin()
win.setCoords(0,0,10,10)
t = Text(Point(5,5), "Centered Text")
t.draw(win)
p = Polygon(Point(1,1), Point(5,3), Point(2,7))
p.draw(win)
e = Entry(Point(5,6), 10)
e.draw(win)
win.getMouse()
p.setFill("red")
p.setOutline("blue")
p.setWidth(2)
s = ""
... | determined from the filname extension.
"""
path, name = os.path.split(filename)
ext = name.split(".")[-1]
self.img.write( filename, format=ext)
def color_rgb(r,g,b):
"""r,g,b are intensities of red, green, and blue in range(256)
Returns color specifier string... | 102 | 102 | 342 | 3 | 99 | andrsharov/python-study | mipt_cs_on_python3/lab4/graphics.py | Python | test | test | 964 | 1,006 | 964 | 964 | aa55b553e350824055085604ec5912661e850a72 | bigcode/the-stack | train |
cf80f479915b1df9b09e7073 | train | class | class _BBox(GraphicsObject):
# Internal base class for objects represented by bounding box
# (opposite corners) Line segment is a degenerate case.
def __init__(self, p1, p2, options=["outline","width","fill"]):
GraphicsObject.__init__(self, options)
self.p1 = p1.clone()
self.p2 ... | class _BBox(GraphicsObject):
# Internal base class for objects represented by bounding box
# (opposite corners) Line segment is a degenerate case.
| def __init__(self, p1, p2, options=["outline","width","fill"]):
GraphicsObject.__init__(self, options)
self.p1 = p1.clone()
self.p2 = p2.clone()
def _move(self, dx, dy):
self.p1.x = self.p1.x + dx
self.p1.y = self.p1.y + dy
self.p2.x = self.p2.x + dx
self... | other.config = self.config.copy()
return other
def getX(self): return self.x
def getY(self): return self.y
class _BBox(GraphicsObject):
# Internal base class for objects represented by bounding box
# (opposite corners) Line segment is a degenerate case.
| 66 | 66 | 223 | 34 | 31 | andrsharov/python-study | mipt_cs_on_python3/lab4/graphics.py | Python | _BBox | _BBox | 576 | 598 | 576 | 579 | a158a5ccfb9803dcc317b7197b4555240a09e69b | bigcode/the-stack | train |
70cdf6f51bbf6e3fa556e31a | train | function | def update(rate=None):
global _update_lasttime
if rate:
now = time.time()
pauseLength = 1/rate-(now-_update_lasttime)
if pauseLength > 0:
time.sleep(pauseLength)
_update_lasttime = now + pauseLength
else:
_update_lasttime = now
_root.updat... | def update(rate=None):
| global _update_lasttime
if rate:
now = time.time()
pauseLength = 1/rate-(now-_update_lasttime)
if pauseLength > 0:
time.sleep(pauseLength)
_update_lasttime = now + pauseLength
else:
_update_lasttime = now
_root.update()
| exceptions."""
pass
OBJ_ALREADY_DRAWN = "Object currently drawn"
UNSUPPORTED_METHOD = "Object doesn't support operation"
BAD_OPTION = "Illegal option value"
##########################################################################
# global variables and funtions
_root = tk.Tk()
_root.withdraw()
_update_lastti... | 64 | 64 | 79 | 5 | 59 | andrsharov/python-study | mipt_cs_on_python3/lab4/graphics.py | Python | update | update | 190 | 201 | 190 | 190 | b10815eccfa0bf34b205607ad181e3b1b4eb7e00 | bigcode/the-stack | train |
06d3795ea4186504711e45c4 | train | class | class GraphicsObject:
"""Generic base class for all of the drawable objects"""
# A subclass of GraphicsObject should override _draw and
# and _move methods.
def __init__(self, options):
# options is a list of strings indicating which options are
# legal for this object.
... | class GraphicsObject:
| """Generic base class for all of the drawable objects"""
# A subclass of GraphicsObject should override _draw and
# and _move methods.
def __init__(self, options):
# options is a list of strings indicating which options are
# legal for this object.
# When an objec... | yhigh
self.xscale = xspan/float(w-1)
self.yscale = yspan/float(h-1)
def screen(self,x,y):
# Returns x,y in screen (actually window) coordinates
xs = (x-self.xbase) / self.xscale
ys = (self.ybase-y) / self.yscale
return int(xs+0.5),int(ys+0.5)
de... | 228 | 229 | 766 | 4 | 224 | andrsharov/python-study | mipt_cs_on_python3/lab4/graphics.py | Python | GraphicsObject | GraphicsObject | 440 | 547 | 440 | 441 | cf7fc98d8316836a03bd9ac6f52e3ee3d114ec9e | bigcode/the-stack | train |
6f550ee3d9b5b52f6823740a | train | class | class Image(GraphicsObject):
idCount = 0
imageCache = {} # tk photoimages go here to avoid GC while drawn
def __init__(self, p, *pixmap):
GraphicsObject.__init__(self, [])
self.anchor = p.clone()
self.imageId = Image.idCount
Image.idCount = Image.idCount + 1
if... | class Image(GraphicsObject):
| idCount = 0
imageCache = {} # tk photoimages go here to avoid GC while drawn
def __init__(self, p, *pixmap):
GraphicsObject.__init__(self, [])
self.anchor = p.clone()
self.imageId = Image.idCount
Image.idCount = Image.idCount + 1
if len(pixmap) == 1: # file name... | ] = value
self.font = tuple(font)
if self.entry:
self.entry.config(font=self.font)
def setFace(self, face):
if face in ['helvetica','arial','courier','times roman']:
self._setFontComponent(0, face)
else:
raise GraphicsError(BAD_OPTION)
def s... | 186 | 186 | 621 | 5 | 181 | andrsharov/python-study | mipt_cs_on_python3/lab4/graphics.py | Python | Image | Image | 874 | 956 | 874 | 875 | 9982cc79b0860d3efe5981ecbd31392848a93336 | bigcode/the-stack | train |
28884d76eb07ad4de45dc2f1 | train | function | def color_rgb(r,g,b):
"""r,g,b are intensities of red, green, and blue in range(256)
Returns color specifier string for the resulting color"""
return "#%02x%02x%02x" % (r,g,b)
| def color_rgb(r,g,b):
| """r,g,b are intensities of red, green, and blue in range(256)
Returns color specifier string for the resulting color"""
return "#%02x%02x%02x" % (r,g,b)
| the pixmap image to filename.
The format for the save image is determined from the filname extension.
"""
path, name = os.path.split(filename)
ext = name.split(".")[-1]
self.img.write( filename, format=ext)
def color_rgb(r,g,b):
| 63 | 64 | 57 | 7 | 56 | andrsharov/python-study | mipt_cs_on_python3/lab4/graphics.py | Python | color_rgb | color_rgb | 959 | 962 | 959 | 959 | d3c1c378d47fedf742e39d235513ae9982ac044b | bigcode/the-stack | train |
dae51d8d24689d8cbbfe1fb3 | train | class | class GraphWin(tk.Canvas):
"""A GraphWin is a toplevel window for displaying graphics."""
def __init__(self, title="Graphics Window",
width=200, height=200, autoflush=True):
assert type(title) == type(""), "Title must be a string"
master = tk.Toplevel(_root)
master.pro... | class GraphWin(tk.Canvas):
| """A GraphWin is a toplevel window for displaying graphics."""
def __init__(self, title="Graphics Window",
width=200, height=200, autoflush=True):
assert type(title) == type(""), "Title must be a string"
master = tk.Toplevel(_root)
master.protocol("WM_DELETE_WINDOW", se... |
# a fixed root (called _root).
# Version 1.4
# Fixed Garbage collection of Tkinter images bug.
# Added ability to set text atttributes.
# Added Entry boxes.
import time, os, sys
try: # import as appropriate for 2.x vs. 3.x
import tkinter as tk
except:
import Tkinter as tk
##################... | 256 | 256 | 1,311 | 7 | 248 | andrsharov/python-study | mipt_cs_on_python3/lab4/graphics.py | Python | GraphWin | GraphWin | 206 | 399 | 206 | 207 | d36ab15a1fcbd1e4042921b716c331bd46b1f985 | bigcode/the-stack | train |
745711006752c70b2863113d | train | class | class Point(GraphicsObject):
def __init__(self, x, y):
GraphicsObject.__init__(self, ["outline", "fill"])
self.setFill = self.setOutline
self.x = float(x)
self.y = float(y)
def __repr__(self):
return "Point({}, {})".format(self.x, self.y)
def _draw(self, can... | class Point(GraphicsObject):
| def __init__(self, x, y):
GraphicsObject.__init__(self, ["outline", "fill"])
self.setFill = self.setOutline
self.x = float(x)
self.y = float(y)
def __repr__(self):
return "Point({}, {})".format(self.x, self.y)
def _draw(self, canvas, options):
x,y = ... | s appropriate figure on canvas with options provided
Returns Tk id of item drawn"""
pass # must override in subclass
def _move(self, dx, dy):
"""updates internal state of object to move it dx,dy units"""
pass # must override in subclass
class Point(GraphicsObject):
| 63 | 64 | 188 | 5 | 57 | andrsharov/python-study | mipt_cs_on_python3/lab4/graphics.py | Python | Point | Point | 550 | 574 | 550 | 550 | 35df89c23ec4f49c19a13705b89396bc3d1653ed | bigcode/the-stack | train |
4f7a85fdc2201304abccdf59 | train | class | class Line(_BBox):
def __init__(self, p1, p2):
_BBox.__init__(self, p1, p2, ["arrow","fill","width"])
self.setFill(DEFAULT_CONFIG['outline'])
self.setOutline = self.setFill
def __repr__(self):
return "Line({}, {})".format(str(self.p1), str(self.p2))
def clone(self):
... | class Line(_BBox):
| def __init__(self, p1, p2):
_BBox.__init__(self, p1, p2, ["arrow","fill","width"])
self.setFill(DEFAULT_CONFIG['outline'])
self.setOutline = self.setFill
def __repr__(self):
return "Line({}, {})".format(str(self.p1), str(self.p2))
def clone(self):
other = Line(self.... | repr__(self):
return "Circle({}, {})".format(str(self.getCenter()), str(self.radius))
def clone(self):
other = Circle(self.getCenter(), self.radius)
other.config = self.config.copy()
return other
def getRadius(self):
return self.radius
class Line(_BBox):... | 67 | 68 | 227 | 6 | 60 | andrsharov/python-study | mipt_cs_on_python3/lab4/graphics.py | Python | Line | Line | 663 | 688 | 663 | 664 | 303e4ddfe660eee97e08fe0b2938c4113311f160 | bigcode/the-stack | train |
fce436ef0ed562711c390826 | train | class | class Rectangle(_BBox):
def __init__(self, p1: object, p2: object) -> object:
_BBox.__init__(self, p1, p2)
def __repr__(self):
return "Rectangle({}, {})".format(str(self.p1), str(self.p2))
def _draw(self, canvas, options):
p1 = self.p1
p2 = self.p2
x1,y1 = ... | class Rectangle(_BBox):
| def __init__(self, p1: object, p2: object) -> object:
_BBox.__init__(self, p1, p2)
def __repr__(self):
return "Rectangle({}, {})".format(str(self.p1), str(self.p2))
def _draw(self, canvas, options):
p1 = self.p1
p2 = self.p2
x1,y1 = canvas.toScreen(p1.x,p1.y)
... | ): return self.p2.clone()
def getCenter(self):
p1 = self.p1
p2 = self.p2
return Point((p1.x+p2.x)/2.0, (p1.y+p2.y)/2.0)
class Rectangle(_BBox):
| 63 | 64 | 170 | 6 | 57 | andrsharov/python-study | mipt_cs_on_python3/lab4/graphics.py | Python | Rectangle | Rectangle | 601 | 619 | 601 | 602 | 1c7aab632e4ce2998e9e71d357c10fc967d5079b | bigcode/the-stack | train |
5157916c6317140eca2b7450 | train | class | class Polygon(GraphicsObject):
def __init__(self, *points):
# if points passed as a list, extract it
if len(points) == 1 and type(points[0]) == type([]):
points = points[0]
self.points = list(map(Point.clone, points))
GraphicsObject.__init__(self, ["outline", "width"... | class Polygon(GraphicsObject):
| def __init__(self, *points):
# if points passed as a list, extract it
if len(points) == 1 and type(points[0]) == type([]):
points = points[0]
self.points = list(map(Point.clone, points))
GraphicsObject.__init__(self, ["outline", "width", "fill"])
def __repr__(self):
... | ,p2.y)
return canvas.create_line(x1,y1,x2,y2,options)
def setArrow(self, option):
if not option in ["first","last","both","none"]:
raise GraphicsError(BAD_OPTION)
self._reconfig("arrow", option)
class Polygon(GraphicsObject):
| 67 | 68 | 229 | 6 | 61 | andrsharov/python-study | mipt_cs_on_python3/lab4/graphics.py | Python | Polygon | Polygon | 691 | 722 | 691 | 692 | 1f694a5fbe714e8c9670ca352e2015bdbdf66b43 | bigcode/the-stack | train |
6cb28888563e60cdcc257d25 | train | class | class Transform:
"""Internal class for 2-D coordinate transformations"""
def __init__(self, w, h, xlow, ylow, xhigh, yhigh):
# w, h are width and height of window
# (xlow,ylow) coordinates of lower-left [raw (0,h-1)]
# (xhigh,yhigh) coordinates of upper-right [raw (w-1,0)]
... | class Transform:
| """Internal class for 2-D coordinate transformations"""
def __init__(self, w, h, xlow, ylow, xhigh, yhigh):
# w, h are width and height of window
# (xlow,ylow) coordinates of lower-left [raw (0,h-1)]
# (xhigh,yhigh) coordinates of upper-right [raw (w-1,0)]
xspan = (xhigh-xlo... |
if self._mouseCallback:
self._mouseCallback(Point(e.x, e.y))
def addItem(self, item):
self.items.append(item)
def delItem(self, item):
self.items.remove(item)
def redraw(self):
for item in self.items[:]:
item.undraw()
item.draw(self)
... | 79 | 81 | 273 | 3 | 76 | andrsharov/python-study | mipt_cs_on_python3/lab4/graphics.py | Python | Transform | Transform | 402 | 427 | 402 | 403 | d53b7e458b630a4ca4620c96156972a98004e3ff | bigcode/the-stack | train |
1a63a5653548373685f1cfff | train | class | class Circle(Oval):
def __init__(self, center, radius):
p1 = Point(center.x-radius, center.y-radius)
p2 = Point(center.x+radius, center.y+radius)
Oval.__init__(self, p1, p2)
self.radius = radius
def __repr__(self):
return "Circle({}, {})".format(str(self.getCenter()... | class Circle(Oval):
| def __init__(self, center, radius):
p1 = Point(center.x-radius, center.y-radius)
p2 = Point(center.x+radius, center.y+radius)
Oval.__init__(self, p1, p2)
self.radius = radius
def __repr__(self):
return "Circle({}, {})".format(str(self.getCenter()), str(self.radius))
... | p2 = self.p2
x1,y1 = canvas.toScreen(p1.x,p1.y)
x2,y2 = canvas.toScreen(p2.x,p2.y)
return canvas.create_oval(x1,y1,x2,y2,options)
class Circle(Oval):
| 63 | 64 | 128 | 6 | 57 | andrsharov/python-study | mipt_cs_on_python3/lab4/graphics.py | Python | Circle | Circle | 643 | 660 | 643 | 644 | 451148768fbe312fd4407f4df8dee473f1c19d46 | bigcode/the-stack | train |
c7a3aebf1c819666429e92aa | train | class | class Text(GraphicsObject):
def __init__(self, p, text):
GraphicsObject.__init__(self, ["justify","fill","text","font"])
self.setText(text)
self.anchor = p.clone()
self.setFill(DEFAULT_CONFIG['outline'])
self.setOutline = self.setFill
def __repr__(self):
ret... | class Text(GraphicsObject):
| def __init__(self, p, text):
GraphicsObject.__init__(self, ["justify","fill","text","font"])
self.setText(text)
self.anchor = p.clone()
self.setFill(DEFAULT_CONFIG['outline'])
self.setOutline = self.setFill
def __repr__(self):
return "Text({}, '{}')".format(self.... | )
other.config = self.config.copy()
return other
def getPoints(self):
return list(map(Point.clone, self.points))
def _move(self, dx, dy):
for p in self.points:
p.move(dx,dy)
def _draw(self, canvas, options):
args = [canvas]
for p in self.poin... | 119 | 120 | 402 | 6 | 113 | andrsharov/python-study | mipt_cs_on_python3/lab4/graphics.py | Python | Text | Text | 724 | 780 | 724 | 725 | dd9eb89adbb5a81813a5ab8f56aeb44a14298924 | bigcode/the-stack | train |
b7cdad7d63d7068b8df11621 | train | class | class GraphicsError(Exception):
"""Generic error class for graphics module exceptions."""
pass
| class GraphicsError(Exception):
| """Generic error class for graphics module exceptions."""
pass
| Added ability to set text atttributes.
# Added Entry boxes.
import time, os, sys
try: # import as appropriate for 2.x vs. 3.x
import tkinter as tk
except:
import Tkinter as tk
##########################################################################
# Module Exceptions
class GraphicsError(Exception):
| 64 | 64 | 18 | 5 | 58 | andrsharov/python-study | mipt_cs_on_python3/lab4/graphics.py | Python | GraphicsError | GraphicsError | 174 | 176 | 174 | 174 | 4e83fce014649a61942b7619ceb8b7006eae24cb | bigcode/the-stack | train |
320a06421eb872e08e429ce8 | train | class | class ControlFiles():
"""
Call for reading and validating all Control Files
"""
def __init__(self, control_file = 'TCA_input.xml', TCA_version = 'standalone' ):
"""
Set all key default values for Control and Strategy file
:param control_file: string of master control file
... | class ControlFiles():
| """
Call for reading and validating all Control Files
"""
def __init__(self, control_file = 'TCA_input.xml', TCA_version = 'standalone' ):
"""
Set all key default values for Control and Strategy file
:param control_file: string of master control file
:param TCA_version:... | #standard
import time
import unittest
import os
import sys
import xml.etree.ElementTree as ET
from copy import deepcopy
#TCA
from TCACore import logger, curdir, control_values, strategy_values
class ControlFiles():
| 53 | 256 | 4,246 | 4 | 48 | OSADP/AMS-TCA-Aimsun | TCALoadControl.py | Python | ControlFiles | ControlFiles | 14 | 349 | 14 | 14 | 8759c7a7587e7c588ceaf087cd4351c7f55cb816 | bigcode/the-stack | train |
8dce2aeb9d701ba52df30727 | train | class | class LoadControlTest(unittest.TestCase):
def setUp(self):
with open('tca_delete_me_test_file_good.xml', 'wb') as f_out:
f_out.write("""<?xml version="1.0" encoding="UTF-8"?>
<ControlFile>
<OutputLevel>0</OutputLevel>
<Title>T... | class LoadControlTest(unittest.TestCase):
| def setUp(self):
with open('tca_delete_me_test_file_good.xml', 'wb') as f_out:
f_out.write("""<?xml version="1.0" encoding="UTF-8"?>
<ControlFile>
<OutputLevel>0</OutputLevel>
<Title>Test File</Title>
<S... | _input_summary_file(self, file_name='TCA_Input_Summary.csv'):
"""
Creates a summary input file
:param file_name: string value for file
"""
dir_path = os.path.dirname( os.path.realpath( __file__ ) )
file_name = self.file_check(dir_path + '/' + file_name)
w... | 256 | 256 | 1,877 | 8 | 248 | OSADP/AMS-TCA-Aimsun | TCALoadControl.py | Python | LoadControlTest | LoadControlTest | 352 | 552 | 352 | 353 | 0ecc835f72afa1e8b9d1653e5afff60d1d98f4ba | bigcode/the-stack | train |
7d7d44700ab62375aad583b5 | train | class | class LoadStrategyTest(unittest.TestCase):
def setUp(self):
with open('test_control_delete_me.xml', 'wb') as f_out:
f_out.write("""<?xml version="1.0" encoding="UTF-8" ?>
<ControlFile>
<OutputLevel>0</OutputLevel>
<InputFiles>
... | class LoadStrategyTest(unittest.TestCase):
| def setUp(self):
with open('test_control_delete_me.xml', 'wb') as f_out:
f_out.write("""<?xml version="1.0" encoding="UTF-8" ?>
<ControlFile>
<OutputLevel>0</OutputLevel>
<InputFiles>
<TrajectoryFile>
<C... |
assert CF.control_values["YColumn"][2] !=''
assert CF.control_values["PDMMarketPenetration"][2] !=''
def test_load_bad2(self):
CF = ControlFiles('tca_delete_me_test_file_bad2.xml')
CF.Load_Control()
assert CF.Error_count() == 5
def test_load_bad3(self):
CF ... | 256 | 256 | 2,743 | 8 | 248 | OSADP/AMS-TCA-Aimsun | TCALoadControl.py | Python | LoadStrategyTest | LoadStrategyTest | 556 | 843 | 556 | 557 | f589ee2b7ab7fdddffa4cba74ad4ea710538a55d | bigcode/the-stack | train |
ae1877ae70d0f3908df8a8ce | train | class | class InvalidGrantException(PermitionException):
pass
| class InvalidGrantException(PermitionException):
| pass
| .message = message
super(PermitionException, self).__init__(result)
def __str__(self):
return '%s %s (%r)' % (self.code, self.error, self.message)
class UnauthorizedUrl(PermitionException):
pass
class InvalidGrantException(PermitionException):
| 64 | 64 | 12 | 9 | 54 | czervenka/gapi | gapi/exceptions.py | Python | InvalidGrantException | InvalidGrantException | 71 | 72 | 71 | 71 | 40964c6b5158a212e102283eababe2a4739e74de | bigcode/the-stack | train |
8d4ae101b0bdaf0b34f7d48e | train | class | class RateLimitExceededException(GoogleApiHttpException):
def __init__(self, result, url):
self.url = url
super(self.__class__, self).__init__(result)
| class RateLimitExceededException(GoogleApiHttpException):
| def __init__(self, result, url):
self.url = url
super(self.__class__, self).__init__(result)
| class NotFoundException(GoogleApiHttpException):
pass
class DailyLimitExceededException(GoogleApiHttpException):
def __init__(self, result, url):
self.url = url
super(self.__class__, self).__init__(result)
class RateLimitExceededException(GoogleApiHttpException):
| 64 | 64 | 40 | 11 | 53 | czervenka/gapi | gapi/exceptions.py | Python | RateLimitExceededException | RateLimitExceededException | 51 | 54 | 51 | 51 | 20890f920046cd77917d2946ff9aa71f3fd658e2 | bigcode/the-stack | train |
2e277deab5a872e718a7b976 | train | class | class GapiException(Exception):
pass
| class GapiException(Exception):
| pass
| " BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
__author__ = 'Robin Gottfried <google@kebet.cz>'
from json import loads
class GapiException(Exception):
| 64 | 64 | 9 | 6 | 57 | czervenka/gapi | gapi/exceptions.py | Python | GapiException | GapiException | 20 | 21 | 20 | 20 | e9dd0077abe4549537e4f65b5c41321e9b9f66db | bigcode/the-stack | train |
2ed771ba8a7f664a551e3c28 | train | class | class DailyLimitExceededException(GoogleApiHttpException):
def __init__(self, result, url):
self.url = url
super(self.__class__, self).__init__(result)
| class DailyLimitExceededException(GoogleApiHttpException):
| def __init__(self, result, url):
self.url = url
super(self.__class__, self).__init__(result)
| self.error = self.content['error']
except:
self.error = result.content
def __str__(self):
return '%s %s' % (self.code, self.error)
class NotFoundException(GoogleApiHttpException):
pass
class DailyLimitExceededException(GoogleApiHttpException):
| 64 | 64 | 40 | 11 | 52 | czervenka/gapi | gapi/exceptions.py | Python | DailyLimitExceededException | DailyLimitExceededException | 45 | 48 | 45 | 45 | 7221bd563bafd33842c0d8decb427057f1a99332 | bigcode/the-stack | train |
3491c6e275286f7254da1f76 | train | class | class PermitionException(GoogleApiHttpException):
def __init__(self, result, message):
self.message = message
super(PermitionException, self).__init__(result)
def __str__(self):
return '%s %s (%r)' % (self.code, self.error, self.message)
| class PermitionException(GoogleApiHttpException):
| def __init__(self, result, message):
self.message = message
super(PermitionException, self).__init__(result)
def __str__(self):
return '%s %s (%r)' % (self.code, self.error, self.message)
| url
super(self.__class__, self).__init__(result)
class RateLimitExceededException(GoogleApiHttpException):
def __init__(self, result, url):
self.url = url
super(self.__class__, self).__init__(result)
class PermitionException(GoogleApiHttpException):
| 64 | 64 | 67 | 10 | 54 | czervenka/gapi | gapi/exceptions.py | Python | PermitionException | PermitionException | 57 | 63 | 57 | 57 | f864dbda348ff0db1c847775e0560a0625d416d3 | bigcode/the-stack | train |
c9f1533ec08841f65e6be02c | train | class | class InvalidCredentialsException(PermitionException):
pass
| class InvalidCredentialsException(PermitionException):
| pass
| return '%s %s (%r)' % (self.code, self.error, self.message)
class UnauthorizedUrl(PermitionException):
pass
class InvalidGrantException(PermitionException):
pass
class AccessDeniedException(PermitionException):
pass
class InvalidCredentialsException(PermitionException):
| 64 | 64 | 12 | 9 | 54 | czervenka/gapi | gapi/exceptions.py | Python | InvalidCredentialsException | InvalidCredentialsException | 78 | 79 | 78 | 78 | bfead1fbe3023c5836e69d898742fba33a037552 | bigcode/the-stack | train |
92a60c5fdcc2d268ff813ed3 | train | class | class GoogleApiHttpException(GapiException):
def __init__(self, result):
self.code = result.status_code
self.error = ''
self.content = ''
try:
self.content = loads(result.content)
if 'error' in self.content:
self.error = self.content['error']
... | class GoogleApiHttpException(GapiException):
| def __init__(self, result):
self.code = result.status_code
self.error = ''
self.content = ''
try:
self.content = loads(result.content)
if 'error' in self.content:
self.error = self.content['error']
except:
self.error = resul... | either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
__author__ = 'Robin Gottfried <google@kebet.cz>'
from json import loads
class GapiException(Exception):
pass
class GoogleApiHttpException(GapiException):
| 64 | 64 | 97 | 9 | 54 | czervenka/gapi | gapi/exceptions.py | Python | GoogleApiHttpException | GoogleApiHttpException | 24 | 38 | 24 | 25 | 32d3e568f657a941af48d7ca965e8bb2fcdf63ea | bigcode/the-stack | train |
a1c34a306689100f85742089 | train | class | class UnauthorizedException(GoogleApiHttpException):
def __init__(self, result, url):
self.url = url
super(self.__class__, self).__init__(result)
| class UnauthorizedException(GoogleApiHttpException):
| def __init__(self, result, url):
self.url = url
super(self.__class__, self).__init__(result)
| .code, self.error, self.message)
class UnauthorizedUrl(PermitionException):
pass
class InvalidGrantException(PermitionException):
pass
class AccessDeniedException(PermitionException):
pass
class InvalidCredentialsException(PermitionException):
pass
class UnauthorizedException(GoogleApiHttpExcept... | 64 | 64 | 38 | 9 | 54 | czervenka/gapi | gapi/exceptions.py | Python | UnauthorizedException | UnauthorizedException | 82 | 85 | 82 | 82 | 2c92ef3cec70fb6f6efce709a073106dba3e223a | bigcode/the-stack | train |
a8273bf89861674e47077f2c | train | class | class UnauthorizedUrl(PermitionException):
pass
| class UnauthorizedUrl(PermitionException):
| pass
| def __init__(self, result, message):
self.message = message
super(PermitionException, self).__init__(result)
def __str__(self):
return '%s %s (%r)' % (self.code, self.error, self.message)
class UnauthorizedUrl(PermitionException):
| 64 | 64 | 11 | 8 | 56 | czervenka/gapi | gapi/exceptions.py | Python | UnauthorizedUrl | UnauthorizedUrl | 67 | 68 | 67 | 67 | 1d6ad8cd76eef54a88019aff4b50045312c1f263 | bigcode/the-stack | train |
607f05a60c7a1ce42e268bcb | train | class | class NotFoundException(GoogleApiHttpException):
pass
| class NotFoundException(GoogleApiHttpException):
| pass
| loads(result.content)
if 'error' in self.content:
self.error = self.content['error']
except:
self.error = result.content
def __str__(self):
return '%s %s' % (self.code, self.error)
class NotFoundException(GoogleApiHttpException):
| 64 | 64 | 13 | 10 | 54 | czervenka/gapi | gapi/exceptions.py | Python | NotFoundException | NotFoundException | 41 | 42 | 41 | 41 | 7f8a78d51546267df30a3665c6570047ae9623ac | bigcode/the-stack | train |
aaec3e8f9701f7f167604843 | train | class | class AccessDeniedException(PermitionException):
pass
| class AccessDeniedException(PermitionException):
| pass
| ).__init__(result)
def __str__(self):
return '%s %s (%r)' % (self.code, self.error, self.message)
class UnauthorizedUrl(PermitionException):
pass
class InvalidGrantException(PermitionException):
pass
class AccessDeniedException(PermitionException):
| 64 | 64 | 12 | 9 | 54 | czervenka/gapi | gapi/exceptions.py | Python | AccessDeniedException | AccessDeniedException | 74 | 75 | 74 | 74 | 58736e08d0613407dff4040d177df72c0d2f7a0c | bigcode/the-stack | train |
c7a919d19df927e024d4172d | train | function | def downsample(x, stride):
"""
Downsample x by decimation.
"""
return x[:, :, ::stride]
| def downsample(x, stride):
| """
Downsample x by decimation.
"""
return x[:, :, ::stride]
| =th.float) / stride
x = x.view(batch, channels, time, 1)
out = x[..., :-1, :] * (1 - weight) + x[..., 1:, :] * weight
return out.reshape(batch, channels, -1)
def downsample(x, stride):
| 64 | 64 | 27 | 7 | 57 | ragatti/demucs | demucs/model.py | Python | downsample | downsample | 54 | 58 | 54 | 54 | 0498d4c581c91a91bccef06a266abfd5d37b00c0 | bigcode/the-stack | train |
b5d7c005e3fac9eef8936e7b | train | class | class BLSTM(nn.Module):
def __init__(self, dim, layers=1):
super().__init__()
self.lstm = nn.LSTM(bidirectional=True, num_layers=layers, hidden_size=dim, input_size=dim)
self.linear = nn.Linear(2 * dim, dim)
def forward(self, x):
x = x.permute(2, 0, 1)
x = self.lstm(x)[0... | class BLSTM(nn.Module):
| def __init__(self, dim, layers=1):
super().__init__()
self.lstm = nn.LSTM(bidirectional=True, num_layers=layers, hidden_size=dim, input_size=dim)
self.linear = nn.Linear(2 * dim, dim)
def forward(self, x):
x = x.permute(2, 0, 1)
x = self.lstm(x)[0]
x = self.linea... | and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import math
import torch as th
from torch import nn
from .utils import capture_init, center_trim
class BLSTM(nn.Module):
| 64 | 64 | 123 | 6 | 57 | ragatti/demucs | demucs/model.py | Python | BLSTM | BLSTM | 15 | 26 | 15 | 15 | cf97ec24f8d29096f3b7c43efc27f5617c0d8f54 | bigcode/the-stack | train |
4b9e7cc352b7ae6b57008ffd | train | function | def rescale_module(module, reference):
for sub in module.modules():
if isinstance(sub, (nn.Conv1d, nn.ConvTranspose1d)):
rescale_conv(sub, reference)
| def rescale_module(module, reference):
| for sub in module.modules():
if isinstance(sub, (nn.Conv1d, nn.ConvTranspose1d)):
rescale_conv(sub, reference)
| )
return x
def rescale_conv(conv, reference):
std = conv.weight.std().detach()
scale = (std / reference)**0.5
conv.weight.data /= scale
if conv.bias is not None:
conv.bias.data /= scale
def rescale_module(module, reference):
| 64 | 64 | 40 | 8 | 55 | ragatti/demucs | demucs/model.py | Python | rescale_module | rescale_module | 37 | 40 | 37 | 37 | dd9a21618675b2d00200b2b45033eaa16e9f4f91 | bigcode/the-stack | train |
78fc45764b05c30e04dde6de | train | function | def rescale_conv(conv, reference):
std = conv.weight.std().detach()
scale = (std / reference)**0.5
conv.weight.data /= scale
if conv.bias is not None:
conv.bias.data /= scale
| def rescale_conv(conv, reference):
| std = conv.weight.std().detach()
scale = (std / reference)**0.5
conv.weight.data /= scale
if conv.bias is not None:
conv.bias.data /= scale
| forward(self, x):
x = x.permute(2, 0, 1)
x = self.lstm(x)[0]
x = self.linear(x)
x = x.permute(1, 2, 0)
return x
def rescale_conv(conv, reference):
| 64 | 64 | 51 | 8 | 55 | ragatti/demucs | demucs/model.py | Python | rescale_conv | rescale_conv | 29 | 34 | 29 | 29 | 8431c496d4b7193aa2c07760214c2e8a3d87752e | bigcode/the-stack | train |
876a06380207dba8f3c21586 | train | class | class Demucs(nn.Module):
@capture_init
def __init__(self,
sources=4,
audio_channels=2,
channels=64,
depth=6,
rewrite=True,
glu=True,
upsample=False,
rescale=0.1,
... | class Demucs(nn.Module):
@capture_init
| def __init__(self,
sources=4,
audio_channels=2,
channels=64,
depth=6,
rewrite=True,
glu=True,
upsample=False,
rescale=0.1,
kernel_size=8,
stride=4... | (x)
x = x.permute(1, 2, 0)
return x
def rescale_conv(conv, reference):
std = conv.weight.std().detach()
scale = (std / reference)**0.5
conv.weight.data /= scale
if conv.bias is not None:
conv.bias.data /= scale
def rescale_module(module, reference):
for sub in module.modu... | 256 | 256 | 1,239 | 11 | 245 | ragatti/demucs | demucs/model.py | Python | Demucs | Demucs | 61 | 216 | 61 | 62 | 4029a0aa557bb198e6110779f0d4f7f0785d28a7 | bigcode/the-stack | train |
756cdb216a70b82900331609 | train | function | def upsample(x, stride):
"""
Linear upsampling, the output will be `stride` times longer.
"""
batch, channels, time = x.size()
weight = th.arange(stride, device=x.device, dtype=th.float) / stride
x = x.view(batch, channels, time, 1)
out = x[..., :-1, :] * (1 - weight) + x[..., 1:, :] * weigh... | def upsample(x, stride):
| """
Linear upsampling, the output will be `stride` times longer.
"""
batch, channels, time = x.size()
weight = th.arange(stride, device=x.device, dtype=th.float) / stride
x = x.view(batch, channels, time, 1)
out = x[..., :-1, :] * (1 - weight) + x[..., 1:, :] * weight
return out.reshape(... | scale
if conv.bias is not None:
conv.bias.data /= scale
def rescale_module(module, reference):
for sub in module.modules():
if isinstance(sub, (nn.Conv1d, nn.ConvTranspose1d)):
rescale_conv(sub, reference)
def upsample(x, stride):
| 64 | 64 | 106 | 7 | 57 | ragatti/demucs | demucs/model.py | Python | upsample | upsample | 43 | 51 | 43 | 43 | b799437b528e340db2ae6e247ad7c0c386ab92b6 | bigcode/the-stack | train |
552ec17a7f3782858c8c524f | train | function | @router.get("", response_model=List[schemas.EmailAddress], status_code=HTTP_200_OK)
def read_many(
skip: int = 0,
limit: int = 100,
db_session: Session = Depends(get_db),
current_user: schemas.Account = Depends(get_current_account),
):
return get_email_addresses(
db_session, account_id=curre... | @router.get("", response_model=List[schemas.EmailAddress], status_code=HTTP_200_OK)
def read_many(
skip: int = 0,
limit: int = 100,
db_session: Session = Depends(get_db),
current_user: schemas.Account = Depends(get_current_account),
):
| return get_email_addresses(
db_session, account_id=current_user.id, skip=skip, limit=limit
)
| @router.get("", response_model=List[schemas.EmailAddress], status_code=HTTP_200_OK)
def read_many(
skip: int = 0,
limit: int = 100,
db_session: Session = Depends(get_db),
current_user: schemas.Account = Depends(get_current_account),
):
| 64 | 64 | 90 | 64 | 0 | jaisenbe58r/SaasFastApi | app/routers/email_addresses.py | Python | read_many | read_many | 43 | 52 | 43 | 49 | e9edf4552380428d36623e4b0fca4fd1e0b5971c | bigcode/the-stack | train |
f9333c1d3f8e608526cbbd1c | train | function | @router.post("/verify", status_code=HTTP_200_OK)
def verify_email(token: str = "", db_session: Session = Depends(get_db)):
verify_email_address(db_session, token)
return
| @router.post("/verify", status_code=HTTP_200_OK)
def verify_email(token: str = "", db_session: Session = Depends(get_db)):
| verify_email_address(db_session, token)
return
| ,
create_email_address,
get_account_by_email,
verify_email_address,
)
from app.dependencies.auth import get_current_account
router = APIRouter()
@router.post("/verify", status_code=HTTP_200_OK)
def verify_email(token: str = "", db_session: Session = Depends(get_db)):
| 64 | 64 | 43 | 31 | 33 | jaisenbe58r/SaasFastApi | app/routers/email_addresses.py | Python | verify_email | verify_email | 20 | 23 | 20 | 21 | 414b59f94965be4a929986b48e5f4cbc4895545b | bigcode/the-stack | train |
fd8731293fd534a590ea93d7 | train | function | @router.post("", response_model=schemas.EmailAddress, status_code=HTTP_201_CREATED)
def create_one(
email: schemas.EmailAddressCreate,
db_session: Session = Depends(get_db),
current_user: schemas.Account = Depends(get_current_account),
):
# Can not add an email address that is already in use.
db_ema... | @router.post("", response_model=schemas.EmailAddress, status_code=HTTP_201_CREATED)
def create_one(
email: schemas.EmailAddressCreate,
db_session: Session = Depends(get_db),
current_user: schemas.Account = Depends(get_current_account),
):
# Can not add an email address that is already in use.
| db_email = get_account_by_email(db_session, email=email.email)
if db_email:
raise HTTPException(status_code=400, detail="Email already registered")
# Set the account_id from the current logged in user.
account_id = current_user.id
return create_email_address(db_session, email.email, accoun... | @router.post("", response_model=schemas.EmailAddress, status_code=HTTP_201_CREATED)
def create_one(
email: schemas.EmailAddressCreate,
db_session: Session = Depends(get_db),
current_user: schemas.Account = Depends(get_current_account),
):
# Can not add an email address that is already in use.
| 68 | 64 | 138 | 68 | 0 | jaisenbe58r/SaasFastApi | app/routers/email_addresses.py | Python | create_one | create_one | 26 | 40 | 26 | 32 | 052557f42b0885f3442da6dfc5fb780775db7be1 | bigcode/the-stack | train |
faad0abd350506fa4e069a02 | train | class | class Orders(models.Model):
order_id = models.AutoField(primary_key=True)
items_json = models.CharField(max_length=5000)
name = models.CharField(max_length=90)
email = models.CharField(max_length=111)
address = models.CharField(max_length=111)
city = models.CharField(max_length=111)
state = ... | class Orders(models.Model):
| order_id = models.AutoField(primary_key=True)
items_json = models.CharField(max_length=5000)
name = models.CharField(max_length=90)
email = models.CharField(max_length=111)
address = models.CharField(max_length=111)
city = models.CharField(max_length=111)
state = models.CharField(max_length=... | .CharField(max_length=50)
email = models.CharField(max_length=70, default="")
phone = models.CharField(max_length=70, default="")
desc = models.CharField(max_length=500, default="")
def __str__(self):
return self.name
class Orders(models.Model):
| 64 | 64 | 109 | 5 | 58 | priyanshgupta1998/Kharidari--A-Shopping-Site | kharidari/shop/models.py | Python | Orders | Orders | 33 | 42 | 33 | 33 | 0573d9cf42d3ca80eecd1d0b9380cb25b1904e3c | bigcode/the-stack | train |
7a652f752a52d01045ceb940 | train | class | class Contact(models.Model):
msg_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=50)
email = models.CharField(max_length=70, default="")
phone = models.CharField(max_length=70, default="")
desc = models.CharField(max_length=500, default="")
def __str__(self):
... | class Contact(models.Model):
| msg_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=50)
email = models.CharField(max_length=70, default="")
phone = models.CharField(max_length=70, default="")
desc = models.CharField(max_length=500, default="")
def __str__(self):
return self.name
| default="")
price = models.IntegerField(default=0)
desc = models.CharField(max_length=300)
pub_date = models.DateField()
image = models.ImageField(upload_to='shop/images', default="")
def __str__(self):
return self.product_name
class Contact(models.Model):
| 64 | 64 | 79 | 5 | 58 | priyanshgupta1998/Kharidari--A-Shopping-Site | kharidari/shop/models.py | Python | Contact | Contact | 21 | 30 | 21 | 21 | 6b77225ee93155d50c8b55e06d2741972d3b2d9e | bigcode/the-stack | train |
b575caf87ac4b529fe074963 | train | class | class Product(models.Model):
product_id = models.AutoField
product_name = models.CharField(max_length=50)
category = models.CharField(max_length=50, default="")
subcategory = models.CharField(max_length=50, default="")
price = models.IntegerField(default=0)
desc = models.CharField(max_length=300... | class Product(models.Model):
| product_id = models.AutoField
product_name = models.CharField(max_length=50)
category = models.CharField(max_length=50, default="")
subcategory = models.CharField(max_length=50, default="")
price = models.IntegerField(default=0)
desc = models.CharField(max_length=300)
pub_date = models.DateF... | from django.db import models
class Product(models.Model):
| 11 | 64 | 109 | 5 | 5 | priyanshgupta1998/Kharidari--A-Shopping-Site | kharidari/shop/models.py | Python | Product | Product | 5 | 16 | 5 | 5 | 0a67a9cf764c430cb6f7918fef790926de216c28 | bigcode/the-stack | train |
9d2e5b1ca9425d792376a50e | train | class | class OrderUpdate(models.Model):
update_id = models.AutoField(primary_key=True)
order_id = models.IntegerField(default="")
update_desc = models.CharField(max_length=5000)
timestamp = models.DateField(auto_now_add=True)
def __str__(self):
return self.update_desc[0:7] + "..."
| class OrderUpdate(models.Model):
| update_id = models.AutoField(primary_key=True)
order_id = models.IntegerField(default="")
update_desc = models.CharField(max_length=5000)
timestamp = models.DateField(auto_now_add=True)
def __str__(self):
return self.update_desc[0:7] + "..."
| = models.CharField(max_length=111)
city = models.CharField(max_length=111)
state = models.CharField(max_length=111)
zip_code = models.CharField(max_length=111)
phone = models.CharField(max_length=111, default="")
class OrderUpdate(models.Model):
| 62 | 64 | 71 | 6 | 57 | priyanshgupta1998/Kharidari--A-Shopping-Site | kharidari/shop/models.py | Python | OrderUpdate | OrderUpdate | 46 | 53 | 46 | 46 | 316e544b8cca05584e30ba6a1d50b286905042c8 | bigcode/the-stack | train |
d27ccd6e0941a33a9a0a10f4 | train | class | class Pygments(Directive):
""" Source code syntax hightlighting.
"""
required_arguments = 1
optional_arguments = 0
final_argument_whitespace = True
option_spec = dict([(key, directives.flag) for key in VARIANTS])
has_content = True
def run(self):
self.assert_has_content()
... | class Pygments(Directive):
| """ Source code syntax hightlighting.
"""
required_arguments = 1
optional_arguments = 0
final_argument_whitespace = True
option_spec = dict([(key, directives.flag) for key in VARIANTS])
has_content = True
def run(self):
self.assert_has_content()
try:
lexer = ... | linenos': HtmlFormatter(noclasses=INLINESTYLES, linenos=True),
}
from docutils import nodes
from docutils.parsers.rst import directives, Directive
from pygments import highlight
from pygments.lexers import get_lexer_by_name, TextLexer
class Pygments(Directive):
| 64 | 64 | 176 | 7 | 56 | kenny-thomas/pygments-main | external/rst-directive.py | Python | Pygments | Pygments | 61 | 80 | 61 | 61 | 3eb60fe1e9d023922d8cc73fde9f0ec2bb928767 | bigcode/the-stack | train |
bfa1b2be8b513a06febf6800 | train | class | class Solution:
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return None
i = head.next
pre = head
while i:
if pre.val == i.val:
pre.next = i.next
i ... | class Solution:
| def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return None
i = head.next
pre = head
while i:
if pre.val == i.val:
pre.next = i.next
i = i.next
... | # Definition for singly-linked list.
import json
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
| 38 | 64 | 93 | 3 | 34 | sonymoon/algorithm | src/main/python/leetcode-python/easy/deleteDuplicates.py | Python | Solution | Solution | 11 | 28 | 11 | 11 | 03340eb5032658b386c27296190afdc102d9f825 | bigcode/the-stack | train |
2301a8ee0819e89de85f40e3 | train | function | def stringToListNode(input):
# Generate list from the input
numbers = stringToIntegerList(input)
# Now convert that list into linked list
dummyRoot = ListNode(0)
ptr = dummyRoot
for number in numbers:
ptr.next = ListNode(number)
ptr = ptr.next
ptr = dummyRoot.next
retur... | def stringToListNode(input):
# Generate list from the input
| numbers = stringToIntegerList(input)
# Now convert that list into linked list
dummyRoot = ListNode(0)
ptr = dummyRoot
for number in numbers:
ptr.next = ListNode(number)
ptr = ptr.next
ptr = dummyRoot.next
return ptr
| .val == i.val:
pre.next = i.next
i = i.next
continue
pre = i
i = i.next
return head
def stringToIntegerList(input):
return json.loads(input)
def stringToListNode(input):
# Generate list from the input
| 64 | 64 | 80 | 15 | 49 | sonymoon/algorithm | src/main/python/leetcode-python/easy/deleteDuplicates.py | Python | stringToListNode | stringToListNode | 35 | 47 | 35 | 36 | 7d679c04893c49ef8ee8abdd037ea4cec1a5fabe | bigcode/the-stack | train |
e10816de9fce32a7a4e358e8 | train | function | def stringToIntegerList(input):
return json.loads(input)
| def stringToIntegerList(input):
| return json.loads(input)
| return None
i = head.next
pre = head
while i:
if pre.val == i.val:
pre.next = i.next
i = i.next
continue
pre = i
i = i.next
return head
def stringToIntegerList(input):
| 64 | 64 | 13 | 7 | 56 | sonymoon/algorithm | src/main/python/leetcode-python/easy/deleteDuplicates.py | Python | stringToIntegerList | stringToIntegerList | 31 | 32 | 31 | 31 | 5bef5b942ababec3cc8465d315c54a81367db680 | bigcode/the-stack | train |
dfde5a9f4cae8d6595dba3eb | train | class | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
| class ListNode:
| def __init__(self, x):
self.val = x
self.next = None
| # Definition for singly-linked list.
import json
class ListNode:
| 14 | 64 | 25 | 4 | 9 | sonymoon/algorithm | src/main/python/leetcode-python/easy/deleteDuplicates.py | Python | ListNode | ListNode | 5 | 8 | 5 | 5 | b304fd0b516bc03440a350450e054ed063e946db | bigcode/the-stack | train |
d8787fd754b4689b1fe76673 | train | function | def main():
import sys
def readlines():
for line in sys.stdin:
yield line.strip('\n')
lines = readlines()
while True:
try:
line = next(lines)
head = stringToListNode(line)
ret = Solution().deleteDuplicates(head)
out = listNo... | def main():
| import sys
def readlines():
for line in sys.stdin:
yield line.strip('\n')
lines = readlines()
while True:
try:
line = next(lines)
head = stringToListNode(line)
ret = Solution().deleteDuplicates(head)
out = listNodeToString(r... | = dummyRoot.next
return ptr
def listNodeToString(node):
if not node:
return "[]"
result = ""
while node:
result += str(node.val) + ", "
node = node.next
return "[" + result[:-2] + "]"
def main():
| 64 | 64 | 84 | 3 | 61 | sonymoon/algorithm | src/main/python/leetcode-python/easy/deleteDuplicates.py | Python | main | main | 61 | 79 | 61 | 61 | 047d67875835cd960f5a86f2681ae7287d5c1d95 | bigcode/the-stack | train |
234a825eeb4b875b58407f8e | train | function | def listNodeToString(node):
if not node:
return "[]"
result = ""
while node:
result += str(node.val) + ", "
node = node.next
return "[" + result[:-2] + "]"
| def listNodeToString(node):
| if not node:
return "[]"
result = ""
while node:
result += str(node.val) + ", "
node = node.next
return "[" + result[:-2] + "]"
| )
# Now convert that list into linked list
dummyRoot = ListNode(0)
ptr = dummyRoot
for number in numbers:
ptr.next = ListNode(number)
ptr = ptr.next
ptr = dummyRoot.next
return ptr
def listNodeToString(node):
| 64 | 64 | 52 | 7 | 56 | sonymoon/algorithm | src/main/python/leetcode-python/easy/deleteDuplicates.py | Python | listNodeToString | listNodeToString | 50 | 58 | 50 | 50 | 91824c8131fe69ed43d32219b526a2d05a134ff5 | bigcode/the-stack | train |
49ba3c4d787fd20191315880 | train | function | def import_module_and_submodules(
package_name: str, exclude: Optional[Set[str]] = None
) -> None:
"""
Import all submodules under the given package.
Primarily useful so that people using classy as a library
can specify their own custom packages and have their custom
classes get loaded and regis... | def import_module_and_submodules(
package_name: str, exclude: Optional[Set[str]] = None
) -> None:
| """
Import all submodules under the given package.
Primarily useful so that people using classy as a library
can specify their own custom packages and have their custom
classes get loaded and registered.
"""
if exclude and package_name in exclude:
return
importlib.invalidate_cac... | github.com/allenai/allennlp/blob/dcd8d9e9671da5a87de51f2bb42ceb3abdce8b3b/allennlp/common/util.py#L334
def import_module_and_submodules(
package_name: str, exclude: Optional[Set[str]] = None
) -> None:
| 72 | 72 | 243 | 27 | 44 | sunglasses-ai/classy | classy/scripts/cli/utils.py | Python | import_module_and_submodules | import_module_and_submodules | 174 | 201 | 174 | 176 | 9415e2bc421202566bcb49a7e7131404f27696eb | bigcode/the-stack | train |
aafe33183cd49a10d706194a | train | function | @contextmanager
def push_python_path(path):
"""
Prepends the given path to `sys.path`.
This method is intended to use with `with`, so after its usage, its value willbe removed from
`sys.path`.
"""
# In some environments, such as TC, it fails when sys.path contains a relative path, such as ".".
... | @contextmanager
def push_python_path(path):
| """
Prepends the given path to `sys.path`.
This method is intended to use with `with`, so after its usage, its value willbe removed from
`sys.path`.
"""
# In some environments, such as TC, it fails when sys.path contains a relative path, such as ".".
path = Path(path).resolve()
path = st... | run
tentative_path = p / ".hydra/config.yaml"
if tentative_path.exists():
ckpt = Run.from_hydra_config(tentative_path).default_checkpoint
return str(ckpt) if ckpt is not None else None
@contextmanager
def push_python_path(path):
| 64 | 64 | 134 | 10 | 53 | sunglasses-ai/classy | classy/scripts/cli/utils.py | Python | push_python_path | push_python_path | 155 | 170 | 155 | 156 | b542898b96c1c13bf4389835d739054a5ba1e79c | bigcode/the-stack | train |
f31a8ac08e3c5721820e16b6 | train | function | def get_device(device):
if device == "gpu" or device == "cuda":
return 0
if device == "cpu":
return -1
try:
return int(device)
except ValueError:
pass
return device # TODO: raise NotImplemented?
| def get_device(device):
| if device == "gpu" or device == "cuda":
return 0
if device == "cpu":
return -1
try:
return int(device)
except ValueError:
pass
return device # TODO: raise NotImplemented?
| import pkgutil
import sys
from contextlib import contextmanager
from pathlib import Path
from typing import Optional, Set
from argcomplete.completers import FilesCompleter
from classy.utils.experiment import Experiment, Run
from classy.utils.file import CLASSY_MODELS_CACHE_PATH
def get_device(device):
| 64 | 64 | 62 | 5 | 58 | sunglasses-ai/classy | classy/scripts/cli/utils.py | Python | get_device | get_device | 15 | 27 | 15 | 15 | ea648173ccc0087504880d90d151950c666f3cff | bigcode/the-stack | train |
5a04c071414729190c5da382 | train | function | def maybe_find_directory(possible_names) -> Optional[str]:
for possible_path in map(Path, possible_names):
if possible_path.exists() and possible_path.is_dir():
return str(possible_path)
return None
| def maybe_find_directory(possible_names) -> Optional[str]:
| for possible_path in map(Path, possible_names):
if possible_path.exists() and possible_path.is_dir():
return str(possible_path)
return None
| ` returns those too, so we need to skip them.
if path_string and module_finder.path != path_string:
continue
subpackage = f"{package_name}.{name}"
import_module_and_submodules(subpackage, exclude=exclude)
def maybe_find_directory(possible_names) -> Optional[str]:
| 64 | 64 | 46 | 12 | 52 | sunglasses-ai/classy | classy/scripts/cli/utils.py | Python | maybe_find_directory | maybe_find_directory | 204 | 209 | 204 | 204 | 167c30771aff48e0647f3168a9a42d1898c1346f | bigcode/the-stack | train |
34e4604d367fb6fe55c15250 | train | function | def autocomplete_model_path(prefix: str, **kwargs):
# from argcomplete import warn
if "/" in prefix:
fc = FilesCompleter()
# try standard file completion first
tentative_files = fc(prefix)
if tentative_files:
# warn(tentative_files)
return tentative_file... | def autocomplete_model_path(prefix: str, **kwargs):
# from argcomplete import warn
| if "/" in prefix:
fc = FilesCompleter()
# try standard file completion first
tentative_files = fc(prefix)
if tentative_files:
# warn(tentative_files)
return tentative_files
# then iteratively go from most to least specific path
# so we start ... | Path
from typing import Optional, Set
from argcomplete.completers import FilesCompleter
from classy.utils.experiment import Experiment, Run
from classy.utils.file import CLASSY_MODELS_CACHE_PATH
def get_device(device):
if device == "gpu" or device == "cuda":
return 0
if device == "cpu":
re... | 123 | 123 | 413 | 19 | 104 | sunglasses-ai/classy | classy/scripts/cli/utils.py | Python | autocomplete_model_path | autocomplete_model_path | 30 | 87 | 30 | 32 | 00ac956be54ef6252adf23947d2d71dc4afec983 | bigcode/the-stack | train |
47d9ae5ed4a754e9a0677131 | train | function | def checkpoint_path_from_user_input(model_path: str) -> str:
try:
path = try_get_checkpoint_path_from_user_input(model_path)
except Exception as e:
print(
f"Unexpected exception occurred when converting your model argument"
f" (`{model_path}`) to an actual checkpoint"
... | def checkpoint_path_from_user_input(model_path: str) -> str:
| try:
path = try_get_checkpoint_path_from_user_input(model_path)
except Exception as e:
print(
f"Unexpected exception occurred when converting your model argument"
f" (`{model_path}`) to an actual checkpoint"
)
print("Exception:", e)
print(
... | ()
)
# give the user the option to continue with a specific path of the experiment
if os.path.exists("experiments") and os.path.isdir("experiments"):
exps.append("experiments/")
return exps
def checkpoint_path_from_user_input(model_path: str) -> str:
| 64 | 64 | 154 | 14 | 49 | sunglasses-ai/classy | classy/scripts/cli/utils.py | Python | checkpoint_path_from_user_input | checkpoint_path_from_user_input | 90 | 109 | 90 | 90 | f7ec487075e69a5f7c7a661762e0d30b2a81e088 | bigcode/the-stack | train |
9210dd4fe55c765ed9cfec69 | train | function | def try_get_checkpoint_path_from_user_input(model_path: str) -> Optional[str]:
# immediately check if the path exists and is a checkpoint, in which case we return it
if model_path.endswith(".ckpt") and Path(model_path).exists():
return model_path
# downloaded model!
if "@" in model_path:
... | def try_get_checkpoint_path_from_user_input(model_path: str) -> Optional[str]:
# immediately check if the path exists and is a checkpoint, in which case we return it
| if model_path.endswith(".ckpt") and Path(model_path).exists():
return model_path
# downloaded model!
if "@" in model_path:
exp = Experiment.from_name(model_path, CLASSY_MODELS_CACHE_PATH)
if exp is None:
print(
f"No pretrained model called {model_path} w... | on GitHub."
)
print("https://github.com/sunglasses-ai/classy/issues/new")
exit(1)
if path is None:
print(f"Unable to convert {model_path} to its actual checkpoint, exiting.")
exit(1)
return path
def try_get_checkpoint_path_from_user_input(model_path: str) -> Optional[s... | 97 | 97 | 325 | 37 | 59 | sunglasses-ai/classy | classy/scripts/cli/utils.py | Python | try_get_checkpoint_path_from_user_input | try_get_checkpoint_path_from_user_input | 112 | 152 | 112 | 114 | 51f671041ded4f40b58be215f10133676d42ce44 | bigcode/the-stack | train |
b43bc12470de190d3c5820ac | train | function | def get_distr_normal(mean, variance):
'''Wrapper that returns a function for drawing `n`
fitness values from a normal distribution.'''
def distr_normal(n):
return np.random.normal(mean, scale=np.sqrt(variance), size=n)
return distr_normal
| def get_distr_normal(mean, variance):
| '''Wrapper that returns a function for drawing `n`
fitness values from a normal distribution.'''
def distr_normal(n):
return np.random.normal(mean, scale=np.sqrt(variance), size=n)
return distr_normal
| import numpy as np
def get_distr_normal(mean, variance):
| 14 | 64 | 59 | 9 | 4 | YvonneKrumbeck/Mating-Type-Model | code/MatingTypeModel.py | Python | get_distr_normal | get_distr_normal | 3 | 9 | 3 | 3 | 1a5489bf4a01950cadad01ecfa1d44f66dbad947 | bigcode/the-stack | train |
60360ff24d3b12b80cec18c2 | train | class | class Model(object):
def __init__(self, **params):
# Model parameters
# (default values will be updated if params given)
self.m0 = 2
self.c = 0.8
self.distr_r = get_distr_normal(0,0.001)
self.r0 = None
self.__dict__.update(params)
self.initialise()... | class Model(object):
| def __init__(self, **params):
# Model parameters
# (default values will be updated if params given)
self.m0 = 2
self.c = 0.8
self.distr_r = get_distr_normal(0,0.001)
self.r0 = None
self.__dict__.update(params)
self.initialise()
#===============... | import numpy as np
def get_distr_normal(mean, variance):
'''Wrapper that returns a function for drawing `n`
fitness values from a normal distribution.'''
def distr_normal(n):
return np.random.normal(mean, scale=np.sqrt(variance), size=n)
return distr_normal
class Model(object):
| 68 | 158 | 528 | 4 | 63 | YvonneKrumbeck/Mating-Type-Model | code/MatingTypeModel.py | Python | Model | Model | 11 | 99 | 11 | 12 | 84c08ed74eb29edebbf0b363fe0701e09c396d7e | bigcode/the-stack | train |
8e09bd5f2c9c253b530d7afd | train | function | @pytest.mark.jsoc
def test_query_basic(jsoc_client):
keys, segs = jsoc_client.query(
'hmi.v_45s[2013.07.03_08:42_TAI/3m]',
key='T_REC, CRLT_OBS', seg='Dopplergram')
assert len(keys) == 4
for k in ['T_REC', 'CRLT_OBS']:
assert k in keys.columns
assert len(segs) == 4
assert 'Do... | @pytest.mark.jsoc
def test_query_basic(jsoc_client):
| keys, segs = jsoc_client.query(
'hmi.v_45s[2013.07.03_08:42_TAI/3m]',
key='T_REC, CRLT_OBS', seg='Dopplergram')
assert len(keys) == 4
for k in ['T_REC', 'CRLT_OBS']:
assert k in keys.columns
assert len(segs) == 4
assert 'Dopplergram' in segs.columns
assert ((keys.CRLT_OBS... | from __future__ import absolute_import, division, print_function
import pytest
import drms
@pytest.mark.jsoc
def test_query_basic(jsoc_client):
| 33 | 64 | 146 | 13 | 19 | harshmathur1990/drms | drms/tests/online/test_jsoc_query.py | Python | test_query_basic | test_query_basic | 7 | 17 | 7 | 8 | 287ef23cae4379487c28c45f41d3f157c11401fb | bigcode/the-stack | train |
982fe0def42a7b8b93883d3c | train | class | class LossCallBack(Callback):
"""
Monitor the loss in training.
If the loss is NAN or INF terminating training.
Note:
If per_print_times is 0 do not print loss.
Args:
per_print_times (int): Print loss every times. Default: 1.
"""
def __init__(self, per_print_times=1, rank_id=... | class LossCallBack(Callback):
| """
Monitor the loss in training.
If the loss is NAN or INF terminating training.
Note:
If per_print_times is 0 do not print loss.
Args:
per_print_times (int): Print loss every times. Default: 1.
"""
def __init__(self, per_print_times=1, rank_id=0):
super(LossCallBack... | , GRUTrainOneStepWithLossScaleCell
from src.dataset import create_gru_dataset
from src.lr_schedule import dynamic_lr
from model_utils.config import config
from model_utils.moxing_adapter import moxing_wrapper
from model_utils.device_adapter import get_rank_id, get_device_id, get_device_num
set_seed(1)
def get_ms_tim... | 112 | 112 | 375 | 7 | 104 | Vincent34/mindspore | model_zoo/official/nlp/gru/train.py | Python | LossCallBack | LossCallBack | 45 | 82 | 45 | 45 | 4f7ca2bf246f6a97fad8597d52a952f71eb615d8 | bigcode/the-stack | train |
4ec56dbe295da38e4c3424cd | train | function | def modelarts_pre_process():
'''modelarts pre process function.'''
def unzip(zip_file, save_dir):
import zipfile
s_time = time.time()
if not os.path.exists(os.path.join(save_dir, config.modelarts_dataset_unzip_name)):
zip_isexist = zipfile.is_zipfile(zip_file)
if ... | def modelarts_pre_process():
| '''modelarts pre process function.'''
def unzip(zip_file, save_dir):
import zipfile
s_time = time.time()
if not os.path.exists(os.path.join(save_dir, config.modelarts_dataset_unzip_name)):
zip_isexist = zipfile.is_zipfile(zip_file)
if zip_isexist:
... | {}, outputs are {}".format(time_stamp_current - time_stamp_first,
cb_params.cur_epoch_num,
cb_params.cur_step_num,
... | 150 | 150 | 501 | 6 | 144 | Vincent34/mindspore | model_zoo/official/nlp/gru/train.py | Python | modelarts_pre_process | modelarts_pre_process | 85 | 136 | 85 | 85 | d7e3a2a51a55193b7cab949f634f864e5be18b7c | bigcode/the-stack | train |
52e398def6e7fb881eb36ca5 | train | function | @moxing_wrapper(pre_process=modelarts_pre_process)
def run_train():
"""run train."""
context.set_context(mode=context.GRAPH_MODE, device_target="Ascend", device_id=get_device_id(), save_graphs=False)
rank = get_rank_id()
device_num = get_device_num()
if config.run_distribute:
context.set_aut... | @moxing_wrapper(pre_process=modelarts_pre_process)
def run_train():
| """run train."""
context.set_context(mode=context.GRAPH_MODE, device_target="Ascend", device_id=get_device_id(), save_graphs=False)
rank = get_rank_id()
device_num = get_device_num()
if config.run_distribute:
context.set_auto_parallel_context(device_num=device_num, parallel_mode=ParallelMode... | : ", zip_file_1)
print("Unzip file save dir: ", save_dir_1)
unzip(zip_file_1, save_dir_1)
print("===Finish extract data synchronization===")
try:
os.mknod(sync_lock)
except IOError:
pass
while True:
if os.pa... | 144 | 144 | 481 | 15 | 129 | Vincent34/mindspore | model_zoo/official/nlp/gru/train.py | Python | run_train | run_train | 139 | 181 | 139 | 140 | 557c519bc06bd5ddf301cfdc264cb534b4879248 | bigcode/the-stack | train |
6750f58c8c55d2ee4eb1929c | train | function | def get_ms_timestamp():
t = time.time()
return int(round(t * 1000))
| def get_ms_timestamp():
| t = time.time()
return int(round(t * 1000))
| src.dataset import create_gru_dataset
from src.lr_schedule import dynamic_lr
from model_utils.config import config
from model_utils.moxing_adapter import moxing_wrapper
from model_utils.device_adapter import get_rank_id, get_device_id, get_device_num
set_seed(1)
def get_ms_timestamp():
| 64 | 64 | 21 | 5 | 59 | Vincent34/mindspore | model_zoo/official/nlp/gru/train.py | Python | get_ms_timestamp | get_ms_timestamp | 38 | 40 | 38 | 38 | 22299c9a596feb7920dc0472ecebc45f21948154 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.