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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
799a6416cf489d265cb0f415 | train | class | class ResDecoder(nn.Module):
def __init__(self, output_ch, base_ch, num_up, num_residual,
conv="con2d", pad='reflect2d', res_norm='instance2d', up_norm='layer'):
super(ResDecoder, self).__init__()
input_ch = base_ch * 2 ** num_up
input_chs = []
for i in range(num_re... | class ResDecoder(nn.Module):
| def __init__(self, output_ch, base_ch, num_up, num_residual,
conv="con2d", pad='reflect2d', res_norm='instance2d', up_norm='layer'):
super(ResDecoder, self).__init__()
input_ch = base_ch * 2 ** num_up
input_chs = []
for i in range(num_residual):
setattr(... | (num_residual):
setattr(self, "res{}".format(i),
ResidualBlock(output_ch, conv=conv, pad=pad, norm=res_norm, activ='relu'))
self.layers = [getattr(self, "conv{}".format(i)) for i in range(num_down + 1)] + \
[getattr(self, "res{}".format(i)) for i in range(n... | 114 | 114 | 381 | 6 | 107 | cpeng93/XraySyn | xraysyn/networks/common.py | Python | ResDecoder | ResDecoder | 36 | 70 | 36 | 36 | 58db1cafcada51ed5109885397113dca4fde65fa | bigcode/the-stack | train |
7abe234b6e217472321640c2 | train | function | def write_figures():
for config_name, config in configs_getter.get_configs():
representations = list(config.representations)
print(config_name, config, representations)
for representation in representations:
if len(representations) > 1:
figure_name = f"{config_name}_{representation}"
e... | def write_figures():
| for config_name, config in configs_getter.get_configs():
representations = list(config.representations)
print(config_name, config, representations)
for representation in representations:
if len(representations) > 1:
figure_name = f"{config_name}_{representation}"
else:
figure_n... | Writes all figures and PDF, based on configs and available data."""
import atexit
import os
from absl import app
from optimal_stopping.utilities import configs_getter
from optimal_stopping.utilities import comparison_table
from optimal_stopping.utilities import plot_hurst
from optimal_stopping.utilities import plot_c... | 73 | 73 | 246 | 5 | 67 | AYUSH-ISHAN/OptStopRandNN | optimal_stopping/run/write_figures.py | Python | write_figures | write_figures | 13 | 41 | 13 | 13 | 4d21cb917d4305b8a2c638b9f4c377230b24c12e | bigcode/the-stack | train |
6be078b26c3942c5dfb1f1d7 | train | function | def generate_pdf():
cmd = "pdflatex -synctex=1 -interaction=nonstopmode amc2.tex > /dev/null"
wd = os.getcwd()
latex_dir_path = os.path.join(os.path.dirname(__file__), "../../../latex")
os.chdir(latex_dir_path)
atexit.register(os.chdir, wd)
status = os.system(cmd)
if status == 0:
pdf_path = os.path.ab... | def generate_pdf():
| cmd = "pdflatex -synctex=1 -interaction=nonstopmode amc2.tex > /dev/null"
wd = os.getcwd()
latex_dir_path = os.path.join(os.path.dirname(__file__), "../../../latex")
os.chdir(latex_dir_path)
atexit.register(os.chdir, wd)
status = os.system(cmd)
if status == 0:
pdf_path = os.path.abspath(os.path.join(l... | ConvergenceStudy":
methods[representation](config, x_axis="nb_paths")
methods[representation](config, x_axis="hidden_size")
else:
methods[representation](figure_name, config)
except BaseException as err:
print("Error:", err)
raise
def generate_pdf():
| 64 | 64 | 131 | 4 | 59 | AYUSH-ISHAN/OptStopRandNN | optimal_stopping/run/write_figures.py | Python | generate_pdf | generate_pdf | 44 | 55 | 44 | 44 | e3905c9f0ee2004569b9938058e8187c23aa7173 | bigcode/the-stack | train |
2efe6202cb73210631ea6743 | train | function | def main(argv):
del argv
write_figures()
generate_pdf()
| def main(argv):
| del argv
write_figures()
generate_pdf()
| wd)
status = os.system(cmd)
if status == 0:
pdf_path = os.path.abspath(os.path.join(latex_dir_path, "amc2.pdf"))
print(f"{pdf_path} written")
else:
print("Error while generating amc2.pdf")
def main(argv):
| 64 | 64 | 17 | 4 | 60 | AYUSH-ISHAN/OptStopRandNN | optimal_stopping/run/write_figures.py | Python | main | main | 58 | 61 | 58 | 58 | 094c9d7c32e34e8cff19efdbbe37fe026ee0740a | bigcode/the-stack | train |
51465b7f5a5769b9b3ddda18 | train | class | class _OverlappedFuture(futures.Future):
"""Subclass of Future which represents an overlapped operation.
Cancelling it will immediately cancel the overlapped operation.
"""
def __init__(self, ov, *, loop=None):
super().__init__(loop=loop)
if self._source_traceback:
del self... | class _OverlappedFuture(futures.Future):
| """Subclass of Future which represents an overlapped operation.
Cancelling it will immediately cancel the overlapped operation.
"""
def __init__(self, ov, *, loop=None):
super().__init__(loop=loop)
if self._source_traceback:
del self._source_traceback[-1]
self._ov =... | LoopPolicy',
]
NULL = 0
INFINITE = 0xffffffff
ERROR_CONNECTION_REFUSED = 1225
ERROR_CONNECTION_ABORTED = 1236
# Initial delay in seconds for connect_pipe() before retrying to connect
CONNECT_PIPE_INIT_DELAY = 0.001
# Maximum delay in seconds for connect_pipe() before retrying to connect
CONNECT_PIPE_MAX_... | 96 | 96 | 322 | 10 | 85 | hroncok/cpython | Lib/asyncio/windows_events.py | Python | _OverlappedFuture | _OverlappedFuture | 39 | 84 | 39 | 39 | 9bdfff2a7f80a8226b2543d43572d6c35ab6c20f | bigcode/the-stack | train |
923129d63b2d9ef46b19e242 | train | class | class ProactorEventLoop(proactor_events.BaseProactorEventLoop):
"""Windows version of proactor event loop using IOCP."""
def __init__(self, proactor=None):
if proactor is None:
proactor = IocpProactor()
super().__init__(proactor)
@coroutine
def create_pipe_connection(self, ... | class ProactorEventLoop(proactor_events.BaseProactorEventLoop):
| """Windows version of proactor event loop using IOCP."""
def __init__(self, proactor=None):
if proactor is None:
proactor = IocpProactor()
super().__init__(proactor)
@coroutine
def create_pipe_connection(self, protocol_factory, address):
f = self._proactor.connect_p... | api.NULL)
pipe = windows_utils.PipeHandle(h)
self._free_instances.add(pipe)
return pipe
def closed(self):
return (self._address is None)
def close(self):
if self._accept_pipe_future is not None:
self._accept_pipe_future.cancel()
self._accept_pipe... | 173 | 174 | 580 | 14 | 159 | hroncok/cpython | Lib/asyncio/windows_events.py | Python | ProactorEventLoop | ProactorEventLoop | 300 | 387 | 300 | 300 | dcad5e6ff45b8d3c170f6551f8b78cfd3085a5fa | bigcode/the-stack | train |
849d2df98846a7757a51e82d | train | class | class _WindowsDefaultEventLoopPolicy(events.BaseDefaultEventLoopPolicy):
_loop_factory = SelectorEventLoop
| class _WindowsDefaultEventLoopPolicy(events.BaseDefaultEventLoopPolicy):
| _loop_factory = SelectorEventLoop
| self._proc.poll()
self._process_exited(returncode)
f = self._loop._proactor.wait_for_handle(int(self._proc._handle))
f.add_done_callback(callback)
SelectorEventLoop = _WindowsSelectorEventLoop
class _WindowsDefaultEventLoopPolicy(events.BaseDefaultEventLoopPolicy):
| 64 | 64 | 23 | 14 | 49 | hroncok/cpython | Lib/asyncio/windows_events.py | Python | _WindowsDefaultEventLoopPolicy | _WindowsDefaultEventLoopPolicy | 791 | 792 | 791 | 791 | 29874fd0c447b21da15c7996093637ac128a944a | bigcode/the-stack | train |
ebc42328bfcc6d480f2dc5ff | train | class | class _WindowsSelectorEventLoop(selector_events.BaseSelectorEventLoop):
"""Windows version of selector event loop."""
| class _WindowsSelectorEventLoop(selector_events.BaseSelectorEventLoop):
| """Windows version of selector event loop."""
| .
if self._address is not None:
for pipe in self._free_instances:
pipe.close()
self._pipe = None
self._address = None
self._free_instances.clear()
__del__ = close
class _WindowsSelectorEventLoop(selector_events.BaseSelectorEventLoop):
| 64 | 64 | 22 | 13 | 50 | hroncok/cpython | Lib/asyncio/windows_events.py | Python | _WindowsSelectorEventLoop | _WindowsSelectorEventLoop | 296 | 297 | 296 | 296 | 536beaf81406f39bc0b9e9e43143ee7311e483a9 | bigcode/the-stack | train |
88227f21af04e704999070bf | train | class | class _WaitCancelFuture(_BaseWaitHandleFuture):
"""Subclass of Future which represents a wait for the cancellation of a
_WaitHandleFuture using an event.
"""
def __init__(self, ov, event, wait_handle, *, loop=None):
super().__init__(ov, event, wait_handle, loop=loop)
self._done_callbac... | class _WaitCancelFuture(_BaseWaitHandleFuture):
| """Subclass of Future which represents a wait for the cancellation of a
_WaitHandleFuture using an event.
"""
def __init__(self, ov, event, wait_handle, *, loop=None):
super().__init__(ov, event, wait_handle, loop=loop)
self._done_callback = None
def cancel(self):
raise Ru... | register_wait()
return super().cancel()
def set_exception(self, exception):
self._unregister_wait()
super().set_exception(exception)
def set_result(self, result):
self._unregister_wait()
super().set_result(result)
class _WaitCancelFuture(_BaseWaitHandleFuture):
| 64 | 64 | 161 | 11 | 53 | hroncok/cpython | Lib/asyncio/windows_events.py | Python | _WaitCancelFuture | _WaitCancelFuture | 161 | 182 | 161 | 161 | 4d495f40d72596de0a5b2ae365c622c209ea1530 | bigcode/the-stack | train |
95066ea3d3eeeb5b10b99173 | train | class | class IocpProactor:
"""Proactor implementation using IOCP."""
def __init__(self, concurrency=0xffffffff):
self._loop = None
self._results = []
self._iocp = _overlapped.CreateIoCompletionPort(
_overlapped.INVALID_HANDLE_VALUE, NULL, 0, concurrency)
self._cache = {}
... | class IocpProactor:
| """Proactor implementation using IOCP."""
def __init__(self, concurrency=0xffffffff):
self._loop = None
self._results = []
self._iocp = _overlapped.CreateIoCompletionPort(
_overlapped.INVALID_HANDLE_VALUE, NULL, 0, concurrency)
self._cache = {}
self._register... | pipe.close()
elif self._debug:
logger.warning("Accept pipe failed on pipe %r",
pipe, exc_info=True)
except futures.CancelledError:
if pipe:
pipe.close()
else:
... | 256 | 256 | 3,097 | 7 | 248 | hroncok/cpython | Lib/asyncio/windows_events.py | Python | IocpProactor | IocpProactor | 390 | 770 | 390 | 390 | 53860c514603cf80ef047aa49e5d6339dfa21d1e | bigcode/the-stack | train |
41a884447cfc0d31e1f0ceea | train | class | class PipeServer(object):
"""Class representing a pipe server.
This is much like a bound, listening socket.
"""
def __init__(self, address):
self._address = address
self._free_instances = weakref.WeakSet()
# initialize the pipe attribute before calling _server_pipe_handle()
... | class PipeServer(object):
| """Class representing a pipe server.
This is much like a bound, listening socket.
"""
def __init__(self, address):
self._address = address
self._free_instances = weakref.WeakSet()
# initialize the pipe attribute before calling _server_pipe_handle()
# because this functio... | overlapped.UnregisterWaitEx(wait_handle, self._event)
except OSError as exc:
if exc.winerror != _overlapped.ERROR_IO_PENDING:
context = {
'message': 'Failed to unregister the wait handle',
'exception': exc,
'future': self,
... | 146 | 146 | 488 | 5 | 141 | hroncok/cpython | Lib/asyncio/windows_events.py | Python | PipeServer | PipeServer | 237 | 293 | 237 | 237 | 1db747dd649c172b3e396f69f3fc548457edbba1 | bigcode/the-stack | train |
ecedf793e0f0f6f03a432b04 | train | class | class _WaitHandleFuture(_BaseWaitHandleFuture):
def __init__(self, ov, handle, wait_handle, proactor, *, loop=None):
super().__init__(ov, handle, wait_handle, loop=loop)
self._proactor = proactor
self._unregister_proactor = True
self._event = _overlapped.CreateEvent(None, True, False... | class _WaitHandleFuture(_BaseWaitHandleFuture):
| def __init__(self, ov, handle, wait_handle, proactor, *, loop=None):
super().__init__(ov, handle, wait_handle, loop=loop)
self._proactor = proactor
self._unregister_proactor = True
self._event = _overlapped.CreateEvent(None, True, False, None)
self._event_fut = None
def ... | """
def __init__(self, ov, event, wait_handle, *, loop=None):
super().__init__(ov, event, wait_handle, loop=loop)
self._done_callback = None
def cancel(self):
raise RuntimeError("_WaitCancelFuture must not be cancelled")
def set_result(self, result):
super().set_resul... | 137 | 137 | 458 | 11 | 126 | hroncok/cpython | Lib/asyncio/windows_events.py | Python | _WaitHandleFuture | _WaitHandleFuture | 185 | 234 | 185 | 185 | 1b6820f0350dfac735861e5803efef88bba45173 | bigcode/the-stack | train |
4ebf77da008264d343b20c13 | train | class | class _WindowsSubprocessTransport(base_subprocess.BaseSubprocessTransport):
def _start(self, args, shell, stdin, stdout, stderr, bufsize, **kwargs):
self._proc = windows_utils.Popen(
args, shell=shell, stdin=stdin, stdout=stdout, stderr=stderr,
bufsize=bufsize, **kwargs)
de... | class _WindowsSubprocessTransport(base_subprocess.BaseSubprocessTransport):
| def _start(self, args, shell, stdin, stdout, stderr, bufsize, **kwargs):
self._proc = windows_utils.Popen(
args, shell=shell, stdin=stdin, stdout=stdout, stderr=stderr,
bufsize=bufsize, **kwargs)
def callback(f):
returncode = self._proc.poll()
self._p... | close proactor')
self._results = []
if self._iocp is not None:
_winapi.CloseHandle(self._iocp)
self._iocp = None
def __del__(self):
self.close()
class _WindowsSubprocessTransport(base_subprocess.BaseSubprocessTransport):
| 64 | 64 | 123 | 14 | 50 | hroncok/cpython | Lib/asyncio/windows_events.py | Python | _WindowsSubprocessTransport | _WindowsSubprocessTransport | 773 | 785 | 773 | 774 | 1489dc3b49e99b7a25a61752001eb23842ade28f | bigcode/the-stack | train |
b1d4c8f31ae3ccb22d2927e6 | train | class | class _BaseWaitHandleFuture(futures.Future):
"""Subclass of Future which represents a wait handle."""
def __init__(self, ov, handle, wait_handle, *, loop=None):
super().__init__(loop=loop)
if self._source_traceback:
del self._source_traceback[-1]
# Keep a reference to the Ov... | class _BaseWaitHandleFuture(futures.Future):
| """Subclass of Future which represents a wait handle."""
def __init__(self, ov, handle, wait_handle, *, loop=None):
super().__init__(loop=loop)
if self._source_traceback:
del self._source_traceback[-1]
# Keep a reference to the Overlapped object to keep it alive until the
... | :
return
try:
self._ov.cancel()
except OSError as exc:
context = {
'message': 'Cancelling an overlapped future failed',
'exception': exc,
'future': self,
}
if self._source_traceback:
... | 163 | 163 | 545 | 10 | 152 | hroncok/cpython | Lib/asyncio/windows_events.py | Python | _BaseWaitHandleFuture | _BaseWaitHandleFuture | 87 | 158 | 87 | 87 | ff9a731eeea3ca4745a7d9472aa77650589a06ea | bigcode/the-stack | train |
fc2d5c74cd15d549ffa7fd53 | train | class | class TestScheduledJobRegistry(RQTestCase):
def test_get_jobs_to_enqueue(self):
"""Getting job ids to enqueue from ScheduledJobRegistry."""
queue = Queue(connection=self.testconn)
registry = ScheduledJobRegistry(queue=queue)
timestamp = current_timestamp()
self.testconn.zad... | class TestScheduledJobRegistry(RQTestCase):
| def test_get_jobs_to_enqueue(self):
"""Getting job ids to enqueue from ScheduledJobRegistry."""
queue = Queue(connection=self.testconn)
registry = ScheduledJobRegistry(queue=queue)
timestamp = current_timestamp()
self.testconn.zadd(registry.key, {'foo': 1})
self.test... | import os
from datetime import datetime, timedelta, timezone
from multiprocessing import Process
import mock
from rq import Queue
from rq.compat import PY2
from rq.exceptions import NoSuchJobError
from rq.job import Job, Retry
from rq.registry import FinishedJobRegistry, ScheduledJobRegistry
from rq.scheduler import R... | 120 | 256 | 1,087 | 10 | 109 | dralley/rq | tests/test_scheduler.py | Python | TestScheduledJobRegistry | TestScheduledJobRegistry | 20 | 119 | 20 | 21 | 837e13fc78d155d62210849769788f497ceb7b7f | bigcode/the-stack | train |
ec9c23920585ff1486802fa6 | train | class | class TestScheduler(RQTestCase):
def test_init(self):
"""Scheduler can be instantiated with queues or queue names"""
foo_queue = Queue('foo', connection=self.testconn)
scheduler = RQScheduler([foo_queue, 'bar'], connection=self.testconn)
self.assertEqual(scheduler._queue_names, {'fo... | class TestScheduler(RQTestCase):
| def test_init(self):
"""Scheduler can be instantiated with queues or queue names"""
foo_queue = Queue('foo', connection=self.testconn)
scheduler = RQScheduler([foo_queue, 'bar'], connection=self.testconn)
self.assertEqual(scheduler._queue_names, {'foo', 'bar'})
self.assertEqu... | .timezone = 18000
# time.daylight = 1
# time.altzone = 14400
mock_day = mock.patch('time.daylight', 1)
mock_tz = mock.patch('time.timezone', 18000)
mock_atz = mock.patch('time.altzone', 14400)
with mock_tz, mock_day, mock_atz:
regis... | 256 | 256 | 1,340 | 8 | 247 | dralley/rq | tests/test_scheduler.py | Python | TestScheduler | TestScheduler | 122 | 249 | 122 | 123 | 3b39dbc74e13a5d714dc3cd1ef304a8300014890 | bigcode/the-stack | train |
c8d71c88a47b7cc75410c154 | train | class | class TestQueue(RQTestCase):
def test_enqueue_at(self):
"""queue.enqueue_at() puts job in the scheduled"""
queue = Queue(connection=self.testconn)
registry = ScheduledJobRegistry(queue=queue)
scheduler = RQScheduler([queue], connection=self.testconn)
scheduler.acquire_locks(... | class TestQueue(RQTestCase):
| def test_enqueue_at(self):
"""queue.enqueue_at() puts job in the scheduled"""
queue = Queue(connection=self.testconn)
registry = ScheduledJobRegistry(queue=queue)
scheduler = RQScheduler([queue], connection=self.testconn)
scheduler.acquire_locks()
# Jobs created using... | (connection=connection)
worker = Worker(queues=[queue], connection=connection)
p = Process(target=kill_worker, args=(os.getpid(), False, 5))
p.start()
queue.enqueue_at(datetime(2019, 1, 1, tzinfo=timezone.utc), say_hello)
worker.work(burst=False, with_scheduler=True)
p.j... | 121 | 121 | 405 | 8 | 113 | dralley/rq | tests/test_scheduler.py | Python | TestQueue | TestQueue | 313 | 355 | 313 | 314 | ed42c535301d0c3aa11c254ef1adabff0dadbef3 | bigcode/the-stack | train |
9ee49cadef7199ed709304ec | train | class | class TestWorker(RQTestCase):
def test_work_burst(self):
"""worker.work() with scheduler enabled works properly"""
queue = Queue(connection=self.testconn)
worker = Worker(queues=[queue], connection=self.testconn)
worker.work(burst=True, with_scheduler=False)
self.assertIsNon... | class TestWorker(RQTestCase):
| def test_work_burst(self):
"""worker.work() with scheduler enabled works properly"""
queue = Queue(connection=self.testconn)
worker = Worker(queues=[queue], connection=self.testconn)
worker.work(burst=True, with_scheduler=False)
self.assertIsNone(worker.scheduler)
wo... | """prepare_registries() creates self._scheduled_job_registries"""
foo_queue = Queue('foo', connection=self.testconn)
bar_queue = Queue('bar', connection=self.testconn)
scheduler = RQScheduler([foo_queue, bar_queue], connection=self.testconn)
self.assertEqual(scheduler._scheduled_job_reg... | 163 | 163 | 544 | 8 | 155 | dralley/rq | tests/test_scheduler.py | Python | TestWorker | TestWorker | 252 | 310 | 252 | 253 | e0ff66e0640150c75964cbffeed97d9a75ac4805 | bigcode/the-stack | train |
8227a88d54bcb379b1caa05c | train | function | def bureau_and_balance(num_rows = None, nan_as_category = True):
bureau = pd.read_csv('projets//07_loan_customer_scoring//bureau.csv', nrows = num_rows)
bb = pd.read_csv('projets//07_loan_customer_scoring//bureau_balance.csv', nrows = num_rows)
bb, bb_cat = one_hot_encoder(bb, nan_as_category)
bureau, b... | def bureau_and_balance(num_rows = None, nan_as_category = True):
| bureau = pd.read_csv('projets//07_loan_customer_scoring//bureau.csv', nrows = num_rows)
bb = pd.read_csv('projets//07_loan_customer_scoring//bureau_balance.csv', nrows = num_rows)
bb, bb_cat = one_hot_encoder(bb, nan_as_category)
bureau, bureau_cat = one_hot_encoder(bureau, nan_as_category)
# B... | (df[bin_feature])
# Categorical features with One-Hot encode
df, cat_cols = one_hot_encoder(df, nan_as_category)
# NaN values for DAYS_EMPLOYED: 365.243 -> nan
df['DAYS_EMPLOYED'].replace(365243, np.nan, inplace= True)
# Some simple new features (percentages)
df['DAYS_EMPLOYED_PERC'] = df['... | 253 | 253 | 844 | 15 | 237 | vinclab/loan-customer-scoring | model/Modules/data_aggregation_2.py | Python | bureau_and_balance | bureau_and_balance | 110 | 165 | 110 | 110 | 52880f307c5fa94cdcdc83c1cc12c9a523d74fac | bigcode/the-stack | train |
c52da755631b3e170569629c | train | function | def pos_cash(num_rows = None, nan_as_category = True):
pos = pd.read_csv('projets//07_loan_customer_scoring//POS_CASH_balance.csv', nrows = num_rows)
pos, cat_cols = one_hot_encoder(pos, nan_as_category= True)
# Features
aggregations = {
'MONTHS_BALANCE': ['max', 'mean', 'size'],
'SK_DPD... | def pos_cash(num_rows = None, nan_as_category = True):
| pos = pd.read_csv('projets//07_loan_customer_scoring//POS_CASH_balance.csv', nrows = num_rows)
pos, cat_cols = one_hot_encoder(pos, nan_as_category= True)
# Features
aggregations = {
'MONTHS_BALANCE': ['max', 'mean', 'size'],
'SK_DPD': ['max', 'mean'],
'SK_DPD_DEF': ['max', 'mean... | .join(refused_agg, how='left', on='SK_ID_CURR')
del refused, refused_agg, approved, approved_agg, prev
gc.collect()
return prev_agg
# Preprocess POS_CASH_balance.csv
def pos_cash(num_rows = None, nan_as_category = True):
| 66 | 66 | 222 | 14 | 51 | vinclab/loan-customer-scoring | model/Modules/data_aggregation_2.py | Python | pos_cash | pos_cash | 214 | 232 | 214 | 214 | 06fffa49d560d5bbac5278f8f581947aed43b81b | bigcode/the-stack | train |
90feff1ca300b502e0b5f0bf | train | function | def application_train_test(num_rows = None, nan_as_category = False):
# Read data and merge
df = pd.read_csv('projets//07_loan_customer_scoring//application_train.csv', nrows= num_rows)
test_df = pd.read_csv('projets//07_loan_customer_scoring//application_test.csv', nrows= num_rows)
print("Train samples... | def application_train_test(num_rows = None, nan_as_category = False):
# Read data and merge
| df = pd.read_csv('projets//07_loan_customer_scoring//application_train.csv', nrows= num_rows)
test_df = pd.read_csv('projets//07_loan_customer_scoring//application_test.csv', nrows= num_rows)
print("Train samples: {}, test samples: {}".format(len(df), len(test_df)))
df = df.append(test_df).reset_index()... | categorical columns with get_dummies
def one_hot_encoder(df, nan_as_category = True):
original_columns = list(df.columns)
categorical_columns = [col for col in df.columns if df[col].dtype == 'object']
df = pd.get_dummies(df, columns= categorical_columns, dummy_na= nan_as_category)
new_columns = [c for ... | 126 | 126 | 421 | 22 | 103 | vinclab/loan-customer-scoring | model/Modules/data_aggregation_2.py | Python | application_train_test | application_train_test | 82 | 107 | 82 | 83 | 66b07e1446a4171e43fd33c4c9f6d42047cf0f82 | bigcode/the-stack | train |
7d9ebf2198fc5b15ea57d0ef | train | function | def credit_card_balance(num_rows = None, nan_as_category = True):
cc = pd.read_csv('projets//07_loan_customer_scoring//credit_card_balance.csv', nrows = num_rows)
cc, cat_cols = one_hot_encoder(cc, nan_as_category= True)
# General aggregations
cc.drop(['SK_ID_PREV'], axis= 1, inplace = True)
cc_agg ... | def credit_card_balance(num_rows = None, nan_as_category = True):
| cc = pd.read_csv('projets//07_loan_customer_scoring//credit_card_balance.csv', nrows = num_rows)
cc, cat_cols = one_hot_encoder(cc, nan_as_category= True)
# General aggregations
cc.drop(['SK_ID_PREV'], axis= 1, inplace = True)
cc_agg = cc.groupby('SK_ID_CURR').agg(['min', 'max', 'mean', 'sum', 'var'... | ()])
# Count installments accounts
ins_agg['INSTAL_COUNT'] = ins.groupby('SK_ID_CURR').size()
del ins
gc.collect()
return ins_agg
# Preprocess credit_card_balance.csv
def credit_card_balance(num_rows = None, nan_as_category = True):
| 64 | 64 | 187 | 15 | 48 | vinclab/loan-customer-scoring | model/Modules/data_aggregation_2.py | Python | credit_card_balance | credit_card_balance | 268 | 279 | 268 | 268 | ca7cfdaa7402c0ef2cd330ce4feac3a30192c6e7 | bigcode/the-stack | train |
dc1c3de3dd5aeff1e4c3f111 | train | function | def one_hot_encoder(df, nan_as_category = True):
original_columns = list(df.columns)
categorical_columns = [col for col in df.columns if df[col].dtype == 'object']
df = pd.get_dummies(df, columns= categorical_columns, dummy_na= nan_as_category)
new_columns = [c for c in df.columns if c not in original_c... | def one_hot_encoder(df, nan_as_category = True):
| original_columns = list(df.columns)
categorical_columns = [col for col in df.columns if df[col].dtype == 'object']
df = pd.get_dummies(df, columns= categorical_columns, dummy_na= nan_as_category)
new_columns = [c for c in df.columns if c not in original_columns]
return df, new_columns
| )
@contextmanager
def timer(title):
t0 = time.time()
yield
print("{} - done in {:.0f}s".format(title, time.time() - t0))
# One-hot encoding for categorical columns with get_dummies
def one_hot_encoder(df, nan_as_category = True):
| 64 | 64 | 86 | 12 | 51 | vinclab/loan-customer-scoring | model/Modules/data_aggregation_2.py | Python | one_hot_encoder | one_hot_encoder | 74 | 79 | 74 | 74 | 5e71a7a8f34c4bd36c85aaa5f2ec74999f305ab8 | bigcode/the-stack | train |
26ffd99570a6229e779beb61 | train | function | def previous_applications(num_rows = None, nan_as_category = True):
prev = pd.read_csv('projets//07_loan_customer_scoring//previous_application.csv', nrows = num_rows)
prev, cat_cols = one_hot_encoder(prev, nan_as_category= True)
# Days 365.243 values -> nan
prev['DAYS_FIRST_DRAWING'].replace(365243, np... | def previous_applications(num_rows = None, nan_as_category = True):
| prev = pd.read_csv('projets//07_loan_customer_scoring//previous_application.csv', nrows = num_rows)
prev, cat_cols = one_hot_encoder(prev, nan_as_category= True)
# Days 365.243 values -> nan
prev['DAYS_FIRST_DRAWING'].replace(365243, np.nan, inplace= True)
prev['DAYS_FIRST_DUE'].replace(365243, np.n... | _agg.columns = pd.Index(['ACTIVE_' + e[0] + "_" + e[1].upper() for e in active_agg.columns.tolist()])
bureau_agg = bureau_agg.join(active_agg, how='left', on='SK_ID_CURR')
del active, active_agg
gc.collect()
# Bureau: Closed credits - using only numerical aggregations
closed = bureau[bureau['CREDIT_... | 220 | 220 | 735 | 15 | 204 | vinclab/loan-customer-scoring | model/Modules/data_aggregation_2.py | Python | previous_applications | previous_applications | 168 | 211 | 168 | 168 | 41c6a0bb14dd3a252a9a424499d7948c7dce4374 | bigcode/the-stack | train |
d2b98d343df228143fca6e67 | train | function | @contextmanager
def timer(title):
t0 = time.time()
yield
print("{} - done in {:.0f}s".format(title, time.time() - t0))
| @contextmanager
def timer(title):
| t0 = time.time()
yield
print("{} - done in {:.0f}s".format(title, time.time() - t0))
| credit card balance"):
cc = credit_card_balance(num_rows)
print("Credit card balance df shape:", cc.shape)
df = df.join(cc, how='left', on='SK_ID_CURR')
del cc
gc.collect()
return(df)
@contextmanager
def timer(title):
| 64 | 64 | 39 | 8 | 56 | vinclab/loan-customer-scoring | model/Modules/data_aggregation_2.py | Python | timer | timer | 67 | 71 | 67 | 68 | 395153c6666303ee33173dee46bf3f23ed3a5faa | bigcode/the-stack | train |
7b6c246e700f483cfa46d6a7 | train | function | def main(debug = False):
num_rows = 10000 if debug else None
df = application_train_test(num_rows)
with timer("Process bureau and bureau_balance"):
bureau = bureau_and_balance(num_rows)
print("Bureau df shape:", bureau.shape)
df = df.join(bureau, how='left', on='SK_ID_CURR')
... | def main(debug = False):
| num_rows = 10000 if debug else None
df = application_train_test(num_rows)
with timer("Process bureau and bureau_balance"):
bureau = bureau_and_balance(num_rows)
print("Bureau df shape:", bureau.shape)
df = df.join(bureau, how='left', on='SK_ID_CURR')
del bureau
gc.col... | KFold.
import numpy as np
import pandas as pd
import gc
import time
from contextlib import contextmanager
from lightgbm import LGBMClassifier
from sklearn.metrics import roc_auc_score, roc_curve
from sklearn.model_selection import KFold, StratifiedKFold
import matplotlib.pyplot as plt
import seaborn as sns
import wa... | 93 | 93 | 312 | 6 | 87 | vinclab/loan-customer-scoring | model/Modules/data_aggregation_2.py | Python | main | main | 30 | 64 | 30 | 30 | d43b083303a23d009468d21fcf51acfcc25a5971 | bigcode/the-stack | train |
20414088d7da56bae1bf29db | train | function | def installments_payments(num_rows = None, nan_as_category = True):
ins = pd.read_csv('projets//07_loan_customer_scoring//installments_payments.csv', nrows = num_rows)
ins, cat_cols = one_hot_encoder(ins, nan_as_category= True)
# Percentage and difference paid in each installment (amount paid and installmen... | def installments_payments(num_rows = None, nan_as_category = True):
| ins = pd.read_csv('projets//07_loan_customer_scoring//installments_payments.csv', nrows = num_rows)
ins, cat_cols = one_hot_encoder(ins, nan_as_category= True)
# Percentage and difference paid in each installment (amount paid and installment value)
ins['PAYMENT_PERC'] = ins['AMT_PAYMENT'] / ins['AMT_INS... | SK_DPD_DEF': ['max', 'mean']
}
for cat in cat_cols:
aggregations[cat] = ['mean']
pos_agg = pos.groupby('SK_ID_CURR').agg(aggregations)
pos_agg.columns = pd.Index(['POS_' + e[0] + "_" + e[1].upper() for e in pos_agg.columns.tolist()])
# Count pos cash accounts
pos_agg['POS_COUNT'] = ... | 146 | 146 | 489 | 15 | 130 | vinclab/loan-customer-scoring | model/Modules/data_aggregation_2.py | Python | installments_payments | installments_payments | 235 | 265 | 235 | 235 | 31d5e3db18eecac31d6a0cca01fdc7b7b24ec7b1 | bigcode/the-stack | train |
b42e6f92261f40beb09a68da | train | function | def display_importances(feature_importance_df_):
cols = feature_importance_df_[["feature", "importance"]].groupby("feature").mean().sort_values(by="importance", ascending=False)[:40].index
best_features = feature_importance_df_.loc[feature_importance_df_.feature.isin(cols)]
plt.figure(figsize=(8, 10))
s... | def display_importances(feature_importance_df_):
| cols = feature_importance_df_[["feature", "importance"]].groupby("feature").mean().sort_values(by="importance", ascending=False)[:40].index
best_features = feature_importance_df_.loc[feature_importance_df_.feature.isin(cols)]
plt.figure(figsize=(8, 10))
sns.barplot(x="importance", y="feature", data=best... | in cc_agg.columns.tolist()])
# Count credit card lines
cc_agg['CC_COUNT'] = cc.groupby('SK_ID_CURR').size()
del cc
gc.collect()
return cc_agg
# Display/plot feature importance
def display_importances(feature_importance_df_):
| 64 | 64 | 132 | 10 | 53 | vinclab/loan-customer-scoring | model/Modules/data_aggregation_2.py | Python | display_importances | display_importances | 282 | 289 | 282 | 282 | 733789fa2bfd63e566e4da7042b2869b7aff0e12 | bigcode/the-stack | train |
5012a733b714cff6032c327f | train | class | class Migration(migrations.Migration):
dependencies = [
('Cinema', '0004_cinema'),
]
operations = [
migrations.CreateModel(
name='Hall',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
... | class Migration(migrations.Migration):
| dependencies = [
('Cinema', '0004_cinema'),
]
operations = [
migrations.CreateModel(
name='Hall',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('h_name', models.CharField(m... | # -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2018-12-13 09:40
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
| 61 | 64 | 121 | 7 | 53 | YaoYongjia/DjangoRestTpp | Cinema/migrations/0005_hall.py | Python | Migration | Migration | 9 | 25 | 9 | 10 | afff2376c89a37aad9d8ad91ce327e2112463ad4 | bigcode/the-stack | train |
227bd4cdad2ec9216869ccf5 | train | class | class MultispeakerDictionary(Dictionary):
"""
Class containing information about a pronunciation dictionary with different dictionaries per speaker
Parameters
----------
input_path : str
Path to an input pronunciation dictionary
output_directory : str
Path to a directory to stor... | class MultispeakerDictionary(Dictionary):
| """
Class containing information about a pronunciation dictionary with different dictionaries per speaker
Parameters
----------
input_path : str
Path to an input pronunciation dictionary
output_directory : str
Path to a directory to store files for Kaldi
oov_code : str, opti... | .phone_mapping = {}
i = 0
self.phone_mapping['<eps>'] = i
if self.position_dependent_phones:
for p in self.positional_sil_phones:
i += 1
self.phone_mapping[p] = i
for p in self.positional_nonsil_phones:
i += 1
... | 256 | 256 | 1,879 | 7 | 249 | erayee/Montreal-Forced-Aligner | montreal_forced_aligner/dictionary.py | Python | MultispeakerDictionary | MultispeakerDictionary | 1,093 | 1,285 | 1,093 | 1,093 | a90c59a9461ebd083efa7926f1569ae941dbfcd9 | bigcode/the-stack | train |
11708d376a8cbb1551fe0197 | train | class | class Dictionary(object):
"""
Class containing information about a pronunciation dictionary
Parameters
----------
input_path : str
Path to an input pronunciation dictionary
output_directory : str
Path to a directory to store files for Kaldi
oov_code : str, optional
W... | class Dictionary(object):
| """
Class containing information about a pronunciation dictionary
Parameters
----------
input_path : str
Path to an input pronunciation dictionary
output_directory : str
Path to a directory to store files for Kaldi
oov_code : str, optional
What to label words not in ... | :
prob = float(next)
if prob > 1 or prob < 0:
raise ValueError
except ValueError:
silence_probabilities = False
count += 1
if count > 10:
break
return pronunciation_probabiliti... | 256 | 256 | 8,880 | 4 | 252 | erayee/Montreal-Forced-Aligner | montreal_forced_aligner/dictionary.py | Python | Dictionary | Dictionary | 122 | 1,027 | 122 | 122 | e849bb1a92c9e32ef1985eb7c046329cc4156332 | bigcode/the-stack | train |
3faa73143f8d8496e35d0449 | train | class | class OrthographicDictionary(Dictionary):
def __init__(self, input_dict, output_directory, oov_code='<unk>',
position_dependent_phones=True, num_sil_states=5,
num_nonsil_states=3, shared_silence_phones=False,
pronunciation_probabilities=True,
sil_p... | class OrthographicDictionary(Dictionary):
| def __init__(self, input_dict, output_directory, oov_code='<unk>',
position_dependent_phones=True, num_sil_states=5,
num_nonsil_states=3, shared_silence_phones=False,
pronunciation_probabilities=True,
sil_prob=0.5, debug=False):
self.debug ... | outf.write('\t'.join(map(str, [s, loopstate, p, word_or_eps, local_nosilcost])) + "\n")
outf.write('\t'.join(map(str, [s, silstate, p, word_or_eps, local_silcost])) + "\n")
if disambig and disambig_symbol is not None:
outf.write('\t'.join(map(str,... | 176 | 176 | 587 | 6 | 170 | erayee/Montreal-Forced-Aligner | montreal_forced_aligner/dictionary.py | Python | OrthographicDictionary | OrthographicDictionary | 1,030 | 1,090 | 1,030 | 1,030 | 1f5aeb2a8710389fde40703d4d4f828f9554f6ac | bigcode/the-stack | train |
acd35d763d2e282cab2841cb | train | function | def parse_ipa(transcription, strip_diacritics=None, digraphs=None):
if strip_diacritics is None:
strip_diacritics = DEFAULT_STRIP_DIACRITICS
if digraphs is None:
digraphs = DEFAULT_DIGRAPHS
new_transcription = []
for t in transcription:
new_t = t
for d in strip_diacritics... | def parse_ipa(transcription, strip_diacritics=None, digraphs=None):
| if strip_diacritics is None:
strip_diacritics = DEFAULT_STRIP_DIACRITICS
if digraphs is None:
digraphs = DEFAULT_DIGRAPHS
new_transcription = []
for t in transcription:
new_t = t
for d in strip_diacritics:
new_t = new_t.replace(d, '')
if 'g' in new_t:
... | 0:
raise ValueError
except ValueError:
silence_probabilities = False
count += 1
if count > 10:
break
return pronunciation_probabilities, silence_probabilities
def parse_ipa(transcription, strip_diacritics=None, digra... | 64 | 64 | 190 | 19 | 44 | erayee/Montreal-Forced-Aligner | montreal_forced_aligner/dictionary.py | Python | parse_ipa | parse_ipa | 98 | 119 | 98 | 98 | f67ee31d7e30405f996305d34d85530748df7929 | bigcode/the-stack | train |
bdd7817dc9381608cf32d6a3 | train | function | def sanitize(item, punctuation=None, clitic_markers=None):
if punctuation is None:
punctuation = DEFAULT_PUNCTUATION
if clitic_markers is None:
clitic_markers = DEFAULT_CLITIC_MARKERS
for c in clitic_markers:
item = item.replace(c, clitic_markers[0])
if not item:
return i... | def sanitize(item, punctuation=None, clitic_markers=None):
| if punctuation is None:
punctuation = DEFAULT_PUNCTUATION
if clitic_markers is None:
clitic_markers = DEFAULT_CLITIC_MARKERS
for c in clitic_markers:
item = item.replace(c, clitic_markers[0])
if not item:
return item
for b in brackets:
if item[0] == b[0] and i... | ('{', '}'), ('<', '>'), ('(', ')')]
def check_bracketed(word):
for b in brackets:
if word.startswith(b[0]) and word.endswith(b[-1]):
return True
return False
def sanitize(item, punctuation=None, clitic_markers=None):
| 64 | 64 | 154 | 13 | 50 | erayee/Montreal-Forced-Aligner | montreal_forced_aligner/dictionary.py | Python | sanitize | sanitize | 44 | 59 | 44 | 44 | d3b0f23eac6131a04cbfafcd2787b87292941d60 | bigcode/the-stack | train |
16fcb8d05dbc93eaca361bbf | train | function | def compile_graphemes(graphemes):
if '-' in graphemes:
base = r'^\W*([-{}]+)\W*'
else:
base = r'^\W*([{}]+)\W*'
graphemes = list(graphemes)
for i in range(len(graphemes)):
if graphemes[i] == ']':
graphemes[i] = r'\]'
string = ''.join(x for x in graphemes if x != '... | def compile_graphemes(graphemes):
| if '-' in graphemes:
base = r'^\W*([-{}]+)\W*'
else:
base = r'^\W*([{}]+)\W*'
graphemes = list(graphemes)
for i in range(len(graphemes)):
if graphemes[i] == ']':
graphemes[i] = r'\]'
string = ''.join(x for x in graphemes if x != '-')
try:
return re.com... | ERS, \
DEFAULT_DIGRAPHS, DEFAULT_STRIP_DIACRITICS
from .helper import thirdparty_binary
from .utils import get_available_dict_languages, get_dictionary_path
from .exceptions import DictionaryPathError, DictionaryFileError, DictionaryError
def compile_graphemes(graphemes):
| 64 | 64 | 131 | 9 | 54 | erayee/Montreal-Forced-Aligner | montreal_forced_aligner/dictionary.py | Python | compile_graphemes | compile_graphemes | 17 | 31 | 17 | 17 | 2ea0097c800db3c4c016b22a98ddcce553b1ec56 | bigcode/the-stack | train |
af7baee01fed8b5193dbdde2 | train | function | def check_format(path):
count = 0
pronunciation_probabilities = True
silence_probabilities = True
with open(path, 'r', encoding='utf8') as f:
for line in f:
line = line.strip()
if not line:
continue
line = line.split()
_ = line.pop(... | def check_format(path):
| count = 0
pronunciation_probabilities = True
silence_probabilities = True
with open(path, 'r', encoding='utf8') as f:
for line in f:
line = line.strip()
if not line:
continue
line = line.split()
_ = line.pop(0) # word
n... | [0] == b[0] and item[-1] == b[1]:
return item
sanitized = re.sub(r'^[{}]+'.format(punctuation), '', item)
sanitized = re.sub(r'[{}]+$'.format(punctuation), '', sanitized)
return sanitized
def check_format(path):
| 67 | 67 | 224 | 5 | 61 | erayee/Montreal-Forced-Aligner | montreal_forced_aligner/dictionary.py | Python | check_format | check_format | 62 | 95 | 62 | 62 | 2ad544874e11a34c4c93527b5b5390b32e98980b | bigcode/the-stack | train |
8027047239c26d14af64a149 | train | function | def check_bracketed(word):
for b in brackets:
if word.startswith(b[0]) and word.endswith(b[-1]):
return True
return False
| def check_bracketed(word):
| for b in brackets:
if word.startswith(b[0]) and word.endswith(b[-1]):
return True
return False
| x in graphemes if x != '-')
try:
return re.compile(base.format(string))
except Exception:
print(graphemes)
raise
brackets = [('[', ']'), ('{', '}'), ('<', '>'), ('(', ')')]
def check_bracketed(word):
| 63 | 64 | 36 | 7 | 56 | erayee/Montreal-Forced-Aligner | montreal_forced_aligner/dictionary.py | Python | check_bracketed | check_bracketed | 37 | 41 | 37 | 37 | 2f77b538a53263fd51a8740672f82064986b28e0 | bigcode/the-stack | train |
836dd37db8ed3238b721228a | train | class | class TriggerPlotter:
def __init__(self):
self.fig, self.ax = plt.subplots()
def add(self, x, y):
self.ax.plot(x, y)
def save(self, path):
print("Figure saved to: ", path)
self.ax.set_xscale('log')
self.ax.set_xlabel("Image Amplitude (p.e.)")
self.ax.set_yla... | class TriggerPlotter:
| def __init__(self):
self.fig, self.ax = plt.subplots()
def add(self, x, y):
self.ax.plot(x, y)
def save(self, path):
print("Figure saved to: ", path)
self.ax.set_xscale('log')
self.ax.set_xlabel("Image Amplitude (p.e.)")
self.ax.set_ylabel("Trigger Eff.")
... | )
self.plot.plot_poisson(x)
self.plot.plot_requirement(x)
self.plot.ax.set_xlabel("Illumination (p.e.)")
self.plot.ax.set_ylabel("Fractional Charge Resolution")
self.plot.add_legend(loc='best')
self.plot.save(path)
class TriggerPlotter:
| 64 | 64 | 94 | 5 | 59 | sstcam/sstcam-simulation | optimisation_studies/pulse_shape2/4_extract_performance.py | Python | TriggerPlotter | TriggerPlotter | 62 | 74 | 62 | 62 | 257cab86fc34691f248034605b419d920c5730ee | bigcode/the-stack | train |
ccf2febc9ac64c27209d3171 | train | function | def main():
parser = argparse.ArgumentParser()
parser.add_argument('-i', dest='performance_paths', nargs='+',
help="paths to performance output files")
args = parser.parse_args()
paths = args.performance_paths
n_total_events = defaultdict(int)
cr_extracted_collection = d... | def main():
| parser = argparse.ArgumentParser()
parser.add_argument('-i', dest='performance_paths', nargs='+',
help="paths to performance output files")
args = parser.parse_args()
paths = args.performance_paths
n_total_events = defaultdict(int)
cr_extracted_collection = defaultdict(C... | '].values
trigger_success = df_binned['sum'] / df_binned['count']
return image_amplitude, trigger_success
class CRPlotter:
def __init__(self):
self.plot = ChargeResolutionPlotter()
def add(self, x, y, label):
self.plot._plot(x, y, None, label=label)
def save(self, path):
... | 256 | 256 | 1,062 | 3 | 253 | sstcam/sstcam-simulation | optimisation_studies/pulse_shape2/4_extract_performance.py | Python | main | main | 77 | 177 | 77 | 77 | 6e36622321fd66a5a81474dd4950f414860c7b61 | bigcode/the-stack | train |
5b04a5821287665316917f53 | train | class | class TriggerGatherer:
def __init__(self):
self.triggers = []
def add(self, df):
self.triggers.append(df)
def finish(self):
df_triggers = pd.concat(self.triggers, ignore_index=True)
df_ia = df_triggers.groupby('image_amplitude')['triggered'].agg(['sum', 'count']).reset_inde... | class TriggerGatherer:
| def __init__(self):
self.triggers = []
def add(self, df):
self.triggers.append(df)
def finish(self):
df_triggers = pd.concat(self.triggers, ignore_index=True)
df_ia = df_triggers.groupby('image_amplitude')['triggered'].agg(['sum', 'count']).reset_index()
df_binned =... | res, _ = self.charge_resolution.finish()
res = bin_charge_resolution(res, n_bins=20)
res = res.groupby('bin').mean()
x = res['true'].values
y = res['charge_resolution'].values
return x, y
class TriggerGatherer:
| 64 | 64 | 152 | 5 | 58 | sstcam/sstcam-simulation | optimisation_studies/pulse_shape2/4_extract_performance.py | Python | TriggerGatherer | TriggerGatherer | 28 | 42 | 28 | 28 | be68c475b90d61aaff7a9f7e76b27e99293c45b1 | bigcode/the-stack | train |
2570dda52c896e4b339cff3c | train | class | class CRGatherer:
def __init__(self):
self.charge_resolution = ChargeResolution(mc_true=True)
def add(self, df):
self.charge_resolution._df_list.append(df)
def finish(self):
res, _ = self.charge_resolution.finish()
res = bin_charge_resolution(res, n_bins=20)
res = r... | class CRGatherer:
| def __init__(self):
self.charge_resolution = ChargeResolution(mc_true=True)
def add(self, df):
self.charge_resolution._df_list.append(df)
def finish(self):
res, _ = self.charge_resolution.finish()
res = bin_charge_resolution(res, n_bins=20)
res = res.groupby('bin').... |
import pandas as pd
from sstcam_simulation.performance.plot_lab_performance import \
bin_charge_resolution, ChargeResolution
from matplotlib import pyplot as plt
from CHECLabPy.plotting.resolutions import ChargeResolutionPlotter
from tqdm import tqdm
from collections import defaultdict
class CRGatherer:
| 64 | 64 | 106 | 5 | 58 | sstcam/sstcam-simulation | optimisation_studies/pulse_shape2/4_extract_performance.py | Python | CRGatherer | CRGatherer | 12 | 25 | 12 | 12 | 3b62bd31c46f833c83cbbac03f338e1980ee6383 | bigcode/the-stack | train |
a48eafd5884c5f802189e768 | train | class | class CRPlotter:
def __init__(self):
self.plot = ChargeResolutionPlotter()
def add(self, x, y, label):
self.plot._plot(x, y, None, label=label)
def save(self, path):
x = np.geomspace(0.1, 1000, 100)
self.plot.plot_poisson(x)
self.plot.plot_requirement(x)
sel... | class CRPlotter:
| def __init__(self):
self.plot = ChargeResolutionPlotter()
def add(self, x, y, label):
self.plot._plot(x, y, None, label=label)
def save(self, path):
x = np.geomspace(0.1, 1000, 100)
self.plot.plot_poisson(x)
self.plot.plot_requirement(x)
self.plot.ax.set_xla... | image_amplitude')
df_binned = df_binned.groupby('bin').mean()
image_amplitude = df_binned['image_amplitude'].values
trigger_success = df_binned['sum'] / df_binned['count']
return image_amplitude, trigger_success
class CRPlotter:
| 64 | 64 | 130 | 5 | 58 | sstcam/sstcam-simulation | optimisation_studies/pulse_shape2/4_extract_performance.py | Python | CRPlotter | CRPlotter | 45 | 59 | 45 | 45 | 8e268be695abe55b7bc4699cd705ba92c38652de | bigcode/the-stack | train |
4f0bffbb53ba01c74f37f951 | train | function | def trade(site,bot='',roundid:str='', percent=0.005):
print (f'\nNoise Bot {datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S")}')
try:
api_key = botutils.lookup_key(site+bot)
URL = scicast_bot_urls[site]
s = SciCastBotSession(base_url=URL, api_key=api_key)
assets = s.get_user_... | def trade(site,bot='',roundid:str='', percent=0.005):
| print (f'\nNoise Bot {datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S")}')
try:
api_key = botutils.lookup_key(site+bot)
URL = scicast_bot_urls[site]
s = SciCastBotSession(base_url=URL, api_key=api_key)
assets = s.get_user_info()
currentCash=assets["cash"]
budg... | import random
from scicast_bot_session.client.scicast_bot_session import SciCastBotSession
from scicast_bot_session.common.utils import scicast_bot_urls
import botutils
from time import sleep
import datetime
noisebot_comment="[NoiseBot] I flip a coin to buy/sell shares. "\
"If I made a mistake, cor... | 99 | 152 | 507 | 16 | 82 | scottleibrand/scicast_bot | NoiseBot.py | Python | trade | trade | 12 | 54 | 12 | 12 | b4ad17ad4fb4d96c2d8867fbdbf241d2944c8109 | bigcode/the-stack | train |
8cdbfe40a40ed66e5e6732b5 | train | class | class SawyerDrawerOpenEnvV2(SawyerXYZEnv):
def __init__(self, render_env=False):
hand_low = (-0.5, 0.40, 0.05)
hand_high = (0.5, 1, 0.5)
obj_low = (-0.1, 0.9, 0.0)
obj_high = (0.1, 0.9, 0.0)
super().__init__(
self.model_name,
hand_low=hand_low,
... | class SawyerDrawerOpenEnvV2(SawyerXYZEnv):
| def __init__(self, render_env=False):
hand_low = (-0.5, 0.40, 0.05)
hand_high = (0.5, 1, 0.5)
obj_low = (-0.1, 0.9, 0.0)
obj_high = (0.1, 0.9, 0.0)
super().__init__(
self.model_name,
hand_low=hand_low,
hand_high=hand_high,
ren... | import numpy as np
from gym.spaces import Box
from metaworld.envs import reward_utils
from metaworld.envs.asset_path_utils import full_v2_path_for
from metaworld.envs.mujoco.sawyer_xyz.sawyer_xyz_env import SawyerXYZEnv, _assert_task_is_set
class SawyerDrawerOpenEnvV2(SawyerXYZEnv):
| 80 | 256 | 1,128 | 13 | 66 | Neo-X/metaworld | metaworld/envs/mujoco/sawyer_xyz/v2/sawyer_drawer_open_v2.py | Python | SawyerDrawerOpenEnvV2 | SawyerDrawerOpenEnvV2 | 9 | 145 | 9 | 9 | 138541a503f5f60659c772fd689c4d391d4cf4c4 | bigcode/the-stack | train |
47283af0ed70bd8f9dfb1614 | train | class | class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Forum'
db.create_table('forums_forum', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('name', self.gf('django.db.models.fields.CharField')(unique=True, max_length=50)),
... | class Migration(SchemaMigration):
| def forwards(self, orm):
# Adding model 'Forum'
db.create_table('forums_forum', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('name', self.gf('django.db.models.fields.CharField')(unique=True, max_length=50)),
('slug', self.gf('django.d... | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
| 37 | 256 | 2,414 | 6 | 30 | jgmize/kitsune | kitsune/forums/migrations/0001_initial.py | Python | Migration | Migration | 8 | 143 | 8 | 9 | 71be60e4ecdf8c774eb7dfb8c477808682dd1591 | bigcode/the-stack | train |
ca42d80fc833bd9f6fb82bcc | train | function | def main():
""" Main function. """
domain_bounds = [[-5, 10], [0, 15]]
max_capital = 100
opt_val, opt_pt, _ = maximise_function(branin, domain_bounds, max_capital)
print('Optimum Value in %d evals: %0.4f'%(max_capital, opt_val))
print('Optimum Point: %s'%(opt_pt))
| def main():
| """ Main function. """
domain_bounds = [[-5, 10], [0, 15]]
max_capital = 100
opt_val, opt_pt, _ = maximise_function(branin, domain_bounds, max_capital)
print('Optimum Value in %d evals: %0.4f'%(max_capital, opt_val))
print('Optimum Point: %s'%(opt_pt))
| """
Branin function.
-- kvysyara@andrew.cmu.edu
"""
# pylint: disable=invalid-name
from __future__ import print_function
from dragonfly import maximise_function
# Local imports
from demos_synthetic.branin.branin import branin
def main():
| 63 | 64 | 93 | 3 | 59 | qboticslabs/dragonfly | demos_synthetic/branin/in_code_demo.py | Python | main | main | 13 | 19 | 13 | 13 | 8e33d617c252cf7711c4915242317deaee2403c8 | bigcode/the-stack | train |
d866d77dc0b1cae579c29852 | train | class | class PyMonty(PythonPackage):
"""Monty is the missing complement to Python."""
homepage = "https://github.com/materialsvirtuallab/monty"
pypi = "monty/monty-0.9.6.tar.gz"
version('2021.8.17', sha256='d4d5b85566bda80360e275e6ffb72228d203de68c5155446a0e09f19c63e8540')
version('0.9.6', sha256='bbf056... | class PyMonty(PythonPackage):
| """Monty is the missing complement to Python."""
homepage = "https://github.com/materialsvirtuallab/monty"
pypi = "monty/monty-0.9.6.tar.gz"
version('2021.8.17', sha256='d4d5b85566bda80360e275e6ffb72228d203de68c5155446a0e09f19c63e8540')
version('0.9.6', sha256='bbf05646c4e86731c2398a57b1044add7487... | # Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack.package import *
class PyMonty(PythonPackage):
| 63 | 64 | 204 | 8 | 55 | jeanbez/spack | var/spack/repos/builtin/packages/py-monty/package.py | Python | PyMonty | PyMonty | 9 | 20 | 9 | 9 | 56b4273a9b5db5a7974350c297eab58e742a87a3 | bigcode/the-stack | train |
5cd13eb70855364b11470eca | train | function | def write_entry(file, CIF, NA):
'''Write entry DB file with certain properties.
Keyword Arguments:
file (str) - output file
CIF (str) - name of CIF
NA (int) - number of atoms per UC from pymatgen
'''
with open(file, 'a') as f:
f.write(CIF + ',' + str(NA) + '\n')
| def write_entry(file, CIF, NA):
| '''Write entry DB file with certain properties.
Keyword Arguments:
file (str) - output file
CIF (str) - name of CIF
NA (int) - number of atoms per UC from pymatgen
'''
with open(file, 'a') as f:
f.write(CIF + ',' + str(NA) + '\n')
| # -*- coding: utf-8 -*-
# Distributed under the terms of the MIT License.
"""
Script to analyze CIFs in a directory.
Author: Andrew Tarzia
Date Created: 04 Mar 2019
"""
import glob
import sys
import atools
def write_entry(file, CIF, NA):
| 64 | 64 | 87 | 9 | 54 | andrewtarzia/cage_collect | utils/analyse_CIFs.py | Python | write_entry | write_entry | 19 | 29 | 19 | 19 | 7b342529f822cdc7652ceacdcacd077cd487e3da | bigcode/the-stack | train |
77e9bc3612bd4ca86af9bdc7 | train | function | def add_user(username: str, password: str) -> None:
db.session.add(User(username=username, password=password))
db.session.commit()
flash("User is created")
| def add_user(username: str, password: str) -> None:
| db.session.add(User(username=username, password=password))
db.session.commit()
flash("User is created")
| login_manager.login_view = "login_page"
class HttpMethod:
GET: str = "GET"
POST: str = "POST"
@classmethod
def new_request(cls) -> tuple:
return cls.GET, cls.POST
def add_user(username: str, password: str) -> None:
| 64 | 64 | 37 | 14 | 49 | vyahello/flask-login-template | login/routes.py | Python | add_user | add_user | 25 | 28 | 25 | 25 | a4504dbe7663b21a7102c5785452b8a1d8ff5057 | bigcode/the-stack | train |
01b72587bef1990da9511b30 | train | function | @login_manager.user_loader
def load_user(user_id: str):
return User.query.get(int(user_id))
| @login_manager.user_loader
def load_user(user_id: str):
| return User.query.get(int(user_id))
| :
if request.method == HttpMethod.POST and "username" in request.form:
username = request.form.get("username")
password = request.form.get("password")
add_user(username, password)
return render_template("create_user.html")
@login_manager.user_loader
def load_user(user_id: str):
| 64 | 64 | 22 | 13 | 51 | vyahello/flask-login-template | login/routes.py | Python | load_user | load_user | 73 | 75 | 73 | 74 | a9cce45d302ccef39f84796d3a204b9db053c1fb | bigcode/the-stack | train |
b71c7bc6bf0f3c673d0eda77 | train | function | @app.route("/create_user", methods=HttpMethod.new_request())
def create_user() -> str:
if request.method == HttpMethod.POST and "username" in request.form:
username = request.form.get("username")
password = request.form.get("password")
add_user(username, password)
return render_template(... | @app.route("/create_user", methods=HttpMethod.new_request())
def create_user() -> str:
| if request.method == HttpMethod.POST and "username" in request.form:
username = request.form.get("username")
password = request.form.get("password")
add_user(username, password)
return render_template("create_user.html")
| return "Invalid username or password"
return render_template("login.html")
@app.route("/logout")
@login_required
def logout_page() -> str:
logout_user()
return redirect(url_for("index"))
@app.route("/create_user", methods=HttpMethod.new_request())
def create_user() -> str:
| 63 | 64 | 70 | 20 | 43 | vyahello/flask-login-template | login/routes.py | Python | create_user | create_user | 64 | 70 | 64 | 65 | 4429a10f72c70a8d6f211beb02e0ab260623b024 | bigcode/the-stack | train |
580df8c87ab10976a096eae9 | train | function | @app.route("/logout")
@login_required
def logout_page() -> str:
logout_user()
return redirect(url_for("index"))
| @app.route("/logout")
@login_required
def logout_page() -> str:
| logout_user()
return redirect(url_for("index"))
| ")
).first()
if user:
if user.password == request.form.get("password"):
login_user(user)
return redirect(url_for("dashboard"))
return "Invalid username or password"
return render_template("login.html")
@app.route("/logout")
@login_required
def logo... | 64 | 64 | 27 | 15 | 49 | vyahello/flask-login-template | login/routes.py | Python | logout_page | logout_page | 57 | 61 | 57 | 59 | 3b1c6775fd0140884906dcbbae49bd077dc5a935 | bigcode/the-stack | train |
e6dcf80ef3f5a8507481dfa9 | train | function | @app.route("/")
@app.route("/index.html")
def index() -> str:
return render_template("index.html")
| @app.route("/")
@app.route("/index.html")
def index() -> str:
| return render_template("index.html")
| ) -> tuple:
return cls.GET, cls.POST
def add_user(username: str, password: str) -> None:
db.session.add(User(username=username, password=password))
db.session.commit()
flash("User is created")
@app.route("/")
@app.route("/index.html")
def index() -> str:
| 64 | 64 | 23 | 15 | 49 | vyahello/flask-login-template | login/routes.py | Python | index | index | 31 | 34 | 31 | 33 | c665d509bd5c8b95ac7fd5cefafcd0683ab117ad | bigcode/the-stack | train |
13f7ec840d380941618b6de3 | train | function | @app.route("/dashboard")
@login_required
def dashboard() -> str:
return render_template("dashboard.html")
| @app.route("/dashboard")
@login_required
def dashboard() -> str:
| return render_template("dashboard.html")
| ) -> None:
db.session.add(User(username=username, password=password))
db.session.commit()
flash("User is created")
@app.route("/")
@app.route("/index.html")
def index() -> str:
return render_template("index.html")
@app.route("/dashboard")
@login_required
def dashboard() -> str:
| 64 | 64 | 22 | 14 | 50 | vyahello/flask-login-template | login/routes.py | Python | dashboard | dashboard | 37 | 40 | 37 | 39 | 3ba5dba0fbe69251f942ac922ac4b8187afcc2c7 | bigcode/the-stack | train |
87c8fb7ea3525c9e78db4c97 | train | class | class HttpMethod:
GET: str = "GET"
POST: str = "POST"
@classmethod
def new_request(cls) -> tuple:
return cls.GET, cls.POST
| class HttpMethod:
| GET: str = "GET"
POST: str = "POST"
@classmethod
def new_request(cls) -> tuple:
return cls.GET, cls.POST
| _template, request, redirect, url_for
from flask_login import (
LoginManager,
login_required,
login_user,
logout_user,
)
from login import app, db
from login.models import User
login_manager = LoginManager(app)
login_manager.login_view = "login_page"
class HttpMethod:
| 64 | 64 | 41 | 4 | 60 | vyahello/flask-login-template | login/routes.py | Python | HttpMethod | HttpMethod | 16 | 22 | 16 | 16 | 1712ebccfc5f17a7e37bdb4d351828836814f771 | bigcode/the-stack | train |
455c5ff0338670b48d233590 | train | function | @app.route("/login", methods=HttpMethod.new_request())
def login_page() -> str:
if request.method == HttpMethod.POST and "username" in request.form:
user = User.query.filter_by(
username=request.form.get("username")
).first()
if user:
if user.password == request.form.... | @app.route("/login", methods=HttpMethod.new_request())
def login_page() -> str:
| if request.method == HttpMethod.POST and "username" in request.form:
user = User.query.filter_by(
username=request.form.get("username")
).first()
if user:
if user.password == request.form.get("password"):
login_user(user)
return redirec... | @app.route("/")
@app.route("/index.html")
def index() -> str:
return render_template("index.html")
@app.route("/dashboard")
@login_required
def dashboard() -> str:
return render_template("dashboard.html")
@app.route("/login", methods=HttpMethod.new_request())
def login_page() -> str:
| 64 | 64 | 99 | 19 | 45 | vyahello/flask-login-template | login/routes.py | Python | login_page | login_page | 43 | 54 | 43 | 44 | d205ef9530d008227cfcf4a52146d333bffb0619 | bigcode/the-stack | train |
6dc7c1a07f5ff9159554e95d | train | class | class Workbook(object):
"""Workbook is the container for all other parts of the document."""
_read_only = False
_data_only = False
_keep_links = True
template = False
path = "/xl/workbook.xml"
def __init__(self,
write_only=False,
):
self._sheets = ... | class Workbook(object):
| """Workbook is the container for all other parts of the document."""
_read_only = False
_data_only = False
_keep_links = True
template = False
path = "/xl/workbook.xml"
def __init__(self,
write_only=False,
):
self._sheets = []
self._active_... | import CALENDAR_WINDOWS_1900
from openpyxl.utils.exceptions import ReadOnlyWorkbookException
from openpyxl.writer.write_only import WriteOnlyWorksheet, save_dump
from openpyxl.writer.excel import save_workbook
from openpyxl.styles.cell_style import StyleArray
from openpyxl.styles.named_styles import NamedStyle
from... | 256 | 256 | 2,131 | 4 | 252 | percevalm/aumyproject | Lib/site-packages/openpyxl/workbook/workbook.py | Python | Workbook | Workbook | 46 | 383 | 46 | 46 | 82d69850e8d2d6fcbcb6e76eb20afe4178ced9aa | bigcode/the-stack | train |
6dae9948eed899a776f055ee | train | class | class MapStatus(ModelSimple):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
Attributes:
allowed_values (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The valu... | class MapStatus(ModelSimple):
| """NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
Attributes:
allowed_values (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
with a c... | two types of workflows supported in the API. The first workflow type follows traditional API conventions in that a request is accepted and a response is returned synchronously. The second workflow type involves a background task. With this workflow, a task is created for uploading a set of queries, and then the client... | 256 | 256 | 2,126 | 6 | 249 | factset/enterprise-sdk | code/python/FactSetConcordance/v2/fds/sdk/FactSetConcordance/model/map_status.py | Python | MapStatus | MapStatus | 34 | 284 | 34 | 34 | f181f969b3f1ef9043d8cacb20aa2ef5a6ee6b02 | bigcode/the-stack | train |
c04844b810bf60baee28b313 | train | function | def calc_cache_key(custom_models):
''' Generate a key to cache a custom extension implementation with.
There is no metadata other than the Model classes, so this is the only
base to generate a cache key.
We build the model keys from the list of ``model.full_name``. This is
not ideal but possibly a... | def calc_cache_key(custom_models):
| ''' Generate a key to cache a custom extension implementation with.
There is no metadata other than the Model classes, so this is the only
base to generate a cache key.
We build the model keys from the list of ``model.full_name``. This is
not ideal but possibly a better solution can be found found... | _CACHING_IMPLEMENTATION
def set_cache_hook(hook):
'''Sets a compiled model cache hook used to look up the compiled
code given the CustomModel and Implementation'''
global _CACHING_IMPLEMENTATION
_CACHING_IMPLEMENTATION = hook
def calc_cache_key(custom_models):
| 64 | 64 | 123 | 7 | 56 | arihans/bokeh | bokeh/util/compiler.py | Python | calc_cache_key | calc_cache_key | 270 | 282 | 270 | 270 | 6837502c0e97fdc6c57d2cfcea143b795b9b202d | bigcode/the-stack | train |
01e0589c368e523d4a7c89d6 | train | function | def get_cache_hook():
'''Returns the current cache hook used to look up the compiled
code given the CustomModel and Implementation'''
return _CACHING_IMPLEMENTATION
| def get_cache_hook():
| '''Returns the current cache hook used to look up the compiled
code given the CustomModel and Implementation'''
return _CACHING_IMPLEMENTATION
| impl = impl.__class__(impl.code, file)
return impl
@property
def dependencies(self):
return getattr(self.cls, "__dependencies__", {})
@property
def module(self):
return "custom/%s" % snakify(self.full_name)
def get_cache_hook():
| 64 | 64 | 37 | 5 | 59 | arihans/bokeh | bokeh/util/compiler.py | Python | get_cache_hook | get_cache_hook | 259 | 262 | 259 | 259 | fe133f61a609b6192e7bce471fd6fdbf01d79a30 | bigcode/the-stack | train |
10fbd7aa529eadd808fd5365 | train | class | class TypeScript(Inline):
''' An implementation for a Bokeh custom model in TypeScript
Example:
.. code-block:: python
class MyExt(Model):
__implementation__ = TypeScript(""" <TypeScript code> """)
'''
@property
def lang(self):
return "typescript"
| class TypeScript(Inline):
| ''' An implementation for a Bokeh custom model in TypeScript
Example:
.. code-block:: python
class MyExt(Model):
__implementation__ = TypeScript(""" <TypeScript code> """)
'''
@property
def lang(self):
return "typescript"
| :
The source code for the implementation
file (str, optional)
A file path to a file containing the source text (default: None)
'''
def __init__(self, code, file=None):
self.code = code
self.file = file
class TypeScript(Inline):
| 64 | 64 | 67 | 6 | 57 | arihans/bokeh | bokeh/util/compiler.py | Python | TypeScript | TypeScript | 136 | 149 | 136 | 136 | 708548c901313b422373ae3ee11cf62b9a513b37 | bigcode/the-stack | train |
e33e3a86861dad42e4ebab0f | train | function | def _model_cache_no_op(model, implementation):
"""Return cached compiled implementation"""
return None
| def _model_cache_no_op(model, implementation):
| """Return cached compiled implementation"""
return None
| js(argv, input=None):
return _run(_npmjs_path(), argv, input)
def _version(run_app):
try:
version = run_app(["--version"])
except RuntimeError:
return None
else:
return version.strip()
def _model_cache_no_op(model, implementation):
| 64 | 64 | 21 | 10 | 54 | arihans/bokeh | bokeh/util/compiler.py | Python | _model_cache_no_op | _model_cache_no_op | 446 | 448 | 446 | 446 | fd1ef50398b6085c79a803725c9da5fd5f9e8c60 | bigcode/the-stack | train |
94bd0bef939613df67c08887 | train | function | def _version(run_app):
try:
version = run_app(["--version"])
except RuntimeError:
return None
else:
return version.strip()
| def _version(run_app):
| try:
version = run_app(["--version"])
except RuntimeError:
return None
else:
return version.strip()
| _2_lf(stdout.decode('utf-8'))
def _run_nodejs(argv, input=None):
return _run(_nodejs_path(), argv, input)
def _run_npmjs(argv, input=None):
return _run(_npmjs_path(), argv, input)
def _version(run_app):
| 64 | 64 | 35 | 6 | 58 | arihans/bokeh | bokeh/util/compiler.py | Python | _version | _version | 438 | 444 | 438 | 438 | 8499192a67c1544cca4248ad722a98b1dc198d31 | bigcode/the-stack | train |
b0277b447f00135cb62a7dea | train | function | def _crlf_cr_2_lf(s):
return re.sub(r"\\r\\n|\\r|\\n", r"\\n", s)
| def _crlf_cr_2_lf(s):
| return re.sub(r"\\r\\n|\\r|\\n", r"\\n", s)
| ():
global _npmjs
if _npmjs is None:
_npmjs = join(dirname(_nodejs_path()), "npm")
if sys.platform == "win32":
_npmjs += '.cmd'
return _npmjs
def _crlf_cr_2_lf(s):
| 64 | 64 | 35 | 11 | 52 | arihans/bokeh | bokeh/util/compiler.py | Python | _crlf_cr_2_lf | _crlf_cr_2_lf | 420 | 421 | 420 | 420 | df477a2c3c1629383e1cbeb700852acdcd6ac6bd | bigcode/the-stack | train |
e88eebbb0560264511206f63 | train | function | def _compile_models(custom_models):
"""Returns the compiled implementation of supplied `models`. """
ordered_models = sorted(custom_models.values(), key=lambda model: model.full_name)
custom_impls = {}
dependencies = []
for model in ordered_models:
dependencies.extend(list(model.dependencie... | def _compile_models(custom_models):
| """Returns the compiled implementation of supplied `models`. """
ordered_models = sorted(custom_models.values(), key=lambda model: model.full_name)
custom_impls = {}
dependencies = []
for model in ordered_models:
dependencies.extend(list(model.dependencies.items()))
if dependencies:
... | for cls in models:
impl = getattr(cls, "__implementation__", None)
if impl is not None:
model = CustomModel(cls)
custom_models[model.full_name] = model
if not custom_models:
return None
return custom_models
def _compile_models(custom_models):
| 64 | 64 | 199 | 7 | 56 | arihans/bokeh | bokeh/util/compiler.py | Python | _compile_models | _compile_models | 469 | 493 | 469 | 469 | 3327af71b0f7ef490a1f13ee54afba3408e33d90 | bigcode/the-stack | train |
cb0c59c36bd32c4d50a50600 | train | class | class CustomModel(object):
''' Represent a custom (user-defined) Bokeh model.
'''
def __init__(self, cls):
self.cls = cls
@property
def name(self):
return self.cls.__name__
@property
def full_name(self):
name = self.cls.__module__ + "." + self.name
return n... | class CustomModel(object):
| ''' Represent a custom (user-defined) Bokeh model.
'''
def __init__(self, cls):
self.cls = cls
@property
def name(self):
return self.cls.__name__
@property
def full_name(self):
name = self.cls.__module__ + "." + self.name
return name.replace("__main__.", ""... | , encoding="utf-8") as f:
self.code = f.read()
self.file = path
@property
def lang(self):
if self.file.endswith(".ts"):
return "typescript"
if self.file.endswith(".js"):
return "javascript"
if self.file.endswith((".css", ".less")):
... | 105 | 105 | 350 | 5 | 100 | arihans/bokeh | bokeh/util/compiler.py | Python | CustomModel | CustomModel | 199 | 257 | 199 | 199 | 166d07e72de7194218a0a11df46caa3d51559a6d | bigcode/the-stack | train |
4d9319900e328ec8ad967cee | train | class | class Less(Inline):
''' An implementation of a Less CSS style sheet.
'''
@property
def lang(self):
return "less"
| class Less(Inline):
| ''' An implementation of a Less CSS style sheet.
'''
@property
def lang(self):
return "less"
| An implementation for a Bokeh custom model in JavaScript
Example:
.. code-block:: python
class MyExt(Model):
__implementation__ = JavaScript(""" <JavaScript code> """)
'''
@property
def lang(self):
return "javascript"
class Less(Inline):
| 64 | 64 | 32 | 5 | 59 | arihans/bokeh | bokeh/util/compiler.py | Python | Less | Less | 166 | 172 | 166 | 166 | bf39ffaff32068cbc1f379defb20eb317172ade1 | bigcode/the-stack | train |
6e8514a319c16b6fdd39adfc | train | function | def _npmjs_path():
global _npmjs
if _npmjs is None:
_npmjs = join(dirname(_nodejs_path()), "npm")
if sys.platform == "win32":
_npmjs += '.cmd'
return _npmjs
| def _npmjs_path():
| global _npmjs
if _npmjs is None:
_npmjs = join(dirname(_nodejs_path()), "npm")
if sys.platform == "win32":
_npmjs += '.cmd'
return _npmjs
| ://nodejs.org/en/download/)')
_nodejs = None
_npmjs = None
def _nodejs_path() -> str:
global _nodejs
if _nodejs is None:
_nodejs = _detect_nodejs()
return _nodejs
def _npmjs_path():
| 64 | 64 | 58 | 6 | 57 | arihans/bokeh | bokeh/util/compiler.py | Python | _npmjs_path | _npmjs_path | 412 | 418 | 412 | 412 | 5d644b39c03f46f42d9ff00afc3692fd3c8226d8 | bigcode/the-stack | train |
39ac99653a7d9a755c051e61 | train | class | class JavaScript(Inline):
''' An implementation for a Bokeh custom model in JavaScript
Example:
.. code-block:: python
class MyExt(Model):
__implementation__ = JavaScript(""" <JavaScript code> """)
'''
@property
def lang(self):
return "javascript"
| class JavaScript(Inline):
| ''' An implementation for a Bokeh custom model in JavaScript
Example:
.. code-block:: python
class MyExt(Model):
__implementation__ = JavaScript(""" <JavaScript code> """)
'''
@property
def lang(self):
return "javascript"
| implementation for a Bokeh custom model in TypeScript
Example:
.. code-block:: python
class MyExt(Model):
__implementation__ = TypeScript(""" <TypeScript code> """)
'''
@property
def lang(self):
return "typescript"
class JavaScript(Inline):
| 64 | 64 | 67 | 6 | 58 | arihans/bokeh | bokeh/util/compiler.py | Python | JavaScript | JavaScript | 151 | 164 | 151 | 151 | 361a038db6164f0d4471885f3f958e8e752b205a | bigcode/the-stack | train |
6e62d072aae4e800b9fe8296 | train | function | def set_cache_hook(hook):
'''Sets a compiled model cache hook used to look up the compiled
code given the CustomModel and Implementation'''
global _CACHING_IMPLEMENTATION
_CACHING_IMPLEMENTATION = hook
| def set_cache_hook(hook):
| '''Sets a compiled model cache hook used to look up the compiled
code given the CustomModel and Implementation'''
global _CACHING_IMPLEMENTATION
_CACHING_IMPLEMENTATION = hook
| def module(self):
return "custom/%s" % snakify(self.full_name)
def get_cache_hook():
'''Returns the current cache hook used to look up the compiled
code given the CustomModel and Implementation'''
return _CACHING_IMPLEMENTATION
def set_cache_hook(hook):
| 64 | 64 | 50 | 7 | 56 | arihans/bokeh | bokeh/util/compiler.py | Python | set_cache_hook | set_cache_hook | 264 | 268 | 264 | 264 | 35cb59919b6375e5a8121df5dbfaaf791b71cd11 | bigcode/the-stack | train |
5a1991bafb8e4c3470674069 | train | function | def nodejs_version():
return _version(_run_nodejs)
| def nodejs_version():
| return _version(_run_nodejs)
| ated = error.get("annotated")
else:
self.text = error
def __str__(self):
return "\n" + self.text.strip()
bokehjs_dir = settings.bokehjsdir()
nodejs_min_version = (10, 13, 0)
def nodejs_version():
| 64 | 64 | 14 | 5 | 59 | arihans/bokeh | bokeh/util/compiler.py | Python | nodejs_version | nodejs_version | 93 | 94 | 93 | 93 | 42f248eb012cc6e212a803454b842d0c4dae819f | bigcode/the-stack | train |
8288df91a04ffc4e93059d44 | train | function | def _detect_nodejs():
if settings.nodejs_path() is not None:
nodejs_paths = [settings.nodejs_path()]
else:
nodejs_paths = ["nodejs", "node"]
for nodejs_path in nodejs_paths:
try:
proc = Popen([nodejs_path, "--version"], stdout=PIPE, stderr=PIPE)
(stdout, _) =... | def _detect_nodejs():
| if settings.nodejs_path() is not None:
nodejs_paths = [settings.nodejs_path()]
else:
nodejs_paths = ["nodejs", "node"]
for nodejs_path in nodejs_paths:
try:
proc = Popen([nodejs_path, "--version"], stdout=PIPE, stderr=PIPE)
(stdout, _) = proc.communicate()
... | } else {
style.appendChild(document.createTextNode(css));
}
head.appendChild(style);
}());
"""
_export_template = \
""""%(name)s": require("%(module)s").%(name)s"""
_module_template = \
""""%(module)s": function(require, module, exports) {\n%(source)s\n}"""
def _detect_nodejs():
| 73 | 73 | 244 | 6 | 67 | arihans/bokeh | bokeh/util/compiler.py | Python | _detect_nodejs | _detect_nodejs | 374 | 401 | 374 | 374 | 0e6ddbfa382bf4dda195fbb059e46667a54e5290 | bigcode/the-stack | train |
c1881367f8b68c6913e48a6c | train | class | class FromFile(Implementation):
''' A custom model implementation read from a separate source file.
Args:
path (str) :
The path to the file containing the extension source code
'''
def __init__(self, path):
with io.open(path, encoding="utf-8") as f:
self.code = ... | class FromFile(Implementation):
| ''' A custom model implementation read from a separate source file.
Args:
path (str) :
The path to the file containing the extension source code
'''
def __init__(self, path):
with io.open(path, encoding="utf-8") as f:
self.code = f.read()
self.file = pat... | JavaScript(""" <JavaScript code> """)
'''
@property
def lang(self):
return "javascript"
class Less(Inline):
''' An implementation of a Less CSS style sheet.
'''
@property
def lang(self):
return "less"
class FromFile(Implementation):
| 64 | 64 | 132 | 6 | 58 | arihans/bokeh | bokeh/util/compiler.py | Python | FromFile | FromFile | 174 | 194 | 174 | 174 | 82618ac707640aa3efe8ed9ca3af8509d20dec17 | bigcode/the-stack | train |
a0074546fab7b9ce13873146 | train | class | class AttrDict(dict):
''' Provide a dict subclass that supports access by named attributes.
'''
def __getattr__(self, key):
return self[key]
| class AttrDict(dict):
| ''' Provide a dict subclass that supports access by named attributes.
'''
def __getattr__(self, key):
return self[key]
| _cache_hook',
'Implementation',
'Inline',
'JavaScript',
'Less',
'nodejs_compile',
'nodejs_version',
'npmjs_version',
'set_cache_hook',
'TypeScript',
)
#-----------------------------------------------------------------------------
# General API
#--------------------------------------... | 63 | 64 | 35 | 5 | 58 | arihans/bokeh | bokeh/util/compiler.py | Python | AttrDict | AttrDict | 65 | 70 | 65 | 65 | ff41460cbc00f6488ecde8c49c800b88e2a326f7 | bigcode/the-stack | train |
c7b9f9ff194a3b41b4457ed1 | train | function | def _nodejs_path() -> str:
global _nodejs
if _nodejs is None:
_nodejs = _detect_nodejs()
return _nodejs
| def _nodejs_path() -> str:
| global _nodejs
if _nodejs is None:
_nodejs = _detect_nodejs()
return _nodejs
| ))
raise RuntimeError('node.js v%s or higher is needed to allow compilation of custom models ' % version +
'("conda install nodejs" or follow https://nodejs.org/en/download/)')
_nodejs = None
_npmjs = None
def _nodejs_path() -> str:
| 64 | 64 | 39 | 9 | 54 | arihans/bokeh | bokeh/util/compiler.py | Python | _nodejs_path | _nodejs_path | 406 | 410 | 406 | 406 | 1d51fc6d787da5a850eebd89f85c011951521228 | bigcode/the-stack | train |
949626462765da54971135c3 | train | class | class Implementation(object):
''' Base class for representing Bokeh custom model implementations.
'''
file = None
| class Implementation(object):
| ''' Base class for representing Bokeh custom model implementations.
'''
file = None
| i, line in enumerate(lines):
if not line.startswith("LOG"):
break
else:
print(line)
obj = json.loads("\n".join(lines[i:]))
if isinstance(obj, dict):
return AttrDict(obj)
else:
return dict(error=obj)
class Implementation(object):
| 64 | 64 | 23 | 4 | 60 | arihans/bokeh | bokeh/util/compiler.py | Python | Implementation | Implementation | 114 | 118 | 114 | 114 | 5b35db34c59f831735c4b3356557769fedc973e0 | bigcode/the-stack | train |
cd92359e2fa0a683ca587c72 | train | class | class Inline(Implementation):
''' Base class for representing Bokeh custom model implementations that may
be given as inline code in some language.
Args:
code (str) :
The source code for the implementation
file (str, optional)
A file path to a file containing the so... | class Inline(Implementation):
| ''' Base class for representing Bokeh custom model implementations that may
be given as inline code in some language.
Args:
code (str) :
The source code for the implementation
file (str, optional)
A file path to a file containing the source text (default: None)
... | )
obj = json.loads("\n".join(lines[i:]))
if isinstance(obj, dict):
return AttrDict(obj)
else:
return dict(error=obj)
class Implementation(object):
''' Base class for representing Bokeh custom model implementations.
'''
file = None
class Inline(Implementation):
| 64 | 64 | 95 | 5 | 58 | arihans/bokeh | bokeh/util/compiler.py | Python | Inline | Inline | 120 | 134 | 120 | 120 | 207b84deed8e4f336d450758f2d9fae2056b4539 | bigcode/the-stack | train |
ea3c18cb437c0e045ad11fee | train | function | def nodejs_compile(code, lang="javascript", file=None):
compilejs_script = join(bokehjs_dir, "js", "compiler.js")
output = _run_nodejs([compilejs_script], dict(code=code, lang=lang, file=file, bokehjs_dir=bokehjs_dir))
lines = output.split("\n")
for i, line in enumerate(lines):
if not line.start... | def nodejs_compile(code, lang="javascript", file=None):
| compilejs_script = join(bokehjs_dir, "js", "compiler.js")
output = _run_nodejs([compilejs_script], dict(code=code, lang=lang, file=file, bokehjs_dir=bokehjs_dir))
lines = output.split("\n")
for i, line in enumerate(lines):
if not line.startswith("LOG"):
break
else:
... | _dir = settings.bokehjsdir()
nodejs_min_version = (10, 13, 0)
def nodejs_version():
return _version(_run_nodejs)
def npmjs_version():
return _version(_run_npmjs)
def nodejs_compile(code, lang="javascript", file=None):
| 64 | 64 | 134 | 13 | 51 | arihans/bokeh | bokeh/util/compiler.py | Python | nodejs_compile | nodejs_compile | 99 | 112 | 99 | 99 | ab05c13e61dce2637171d74a56d338f6c76f8662 | bigcode/the-stack | train |
69803b4d4457e6a80e20e6d0 | train | function | def _run_nodejs(argv, input=None):
return _run(_nodejs_path(), argv, input)
| def _run_nodejs(argv, input=None):
| return _run(_nodejs_path(), argv, input)
| (input=None if input is None else json.dumps(input).encode())
if proc.returncode != 0:
raise RuntimeError(errout.decode('utf-8'))
else:
return _crlf_cr_2_lf(stdout.decode('utf-8'))
def _run_nodejs(argv, input=None):
| 64 | 64 | 23 | 10 | 54 | arihans/bokeh | bokeh/util/compiler.py | Python | _run_nodejs | _run_nodejs | 432 | 433 | 432 | 432 | a2d65eb2574b134fb36fc587bc237e81538f9228 | bigcode/the-stack | train |
ced2830bbccaa5b9abc8b96f | train | function | def bundle_models(models):
"""Create a bundle of selected `models`. """
custom_models = _get_custom_models(models)
if custom_models is None:
return None
key = calc_cache_key(custom_models)
bundle = _bundle_cache.get(key, None)
if bundle is None:
try:
_bundle_cache[ke... | def bundle_models(models):
| """Create a bundle of selected `models`. """
custom_models = _get_custom_models(models)
if custom_models is None:
return None
key = calc_cache_key(custom_models)
bundle = _bundle_cache.get(key, None)
if bundle is None:
try:
_bundle_cache[key] = bundle = _bundle_model... | possibly a better solution can be found found later.
'''
model_names = {model.full_name for model in custom_models.values()}
encoded_names = ",".join(sorted(model_names)).encode('utf-8')
return hashlib.sha256(encoded_names).hexdigest()
_bundle_cache = {}
def bundle_models(models):
| 64 | 64 | 117 | 5 | 59 | arihans/bokeh | bokeh/util/compiler.py | Python | bundle_models | bundle_models | 286 | 301 | 286 | 286 | d5da735651a9a85b9a0f32380af283a3226a51f9 | bigcode/the-stack | train |
504889ada4be38f55566cc1c | train | class | class CompilationError(RuntimeError):
''' A ``RuntimeError`` subclass for reporting JS compilation errors.
'''
def __init__(self, error):
super().__init__()
if isinstance(error, dict):
self.line = error.get("line")
self.column = error.get("column")
self.m... | class CompilationError(RuntimeError):
| ''' A ``RuntimeError`` subclass for reporting JS compilation errors.
'''
def __init__(self, error):
super().__init__()
if isinstance(error, dict):
self.line = error.get("line")
self.column = error.get("column")
self.message = error.get("message")
... | _version',
'set_cache_hook',
'TypeScript',
)
#-----------------------------------------------------------------------------
# General API
#-----------------------------------------------------------------------------
class AttrDict(dict):
''' Provide a dict subclass that supports access by named attribute... | 64 | 64 | 116 | 6 | 58 | arihans/bokeh | bokeh/util/compiler.py | Python | CompilationError | CompilationError | 72 | 88 | 72 | 72 | cf5e00a79ee098e0151e6cb47ebb8782666fcf54 | bigcode/the-stack | train |
c4bc34b02d33c1ff4ad32149 | train | function | def _get_custom_models(models):
"""Returns CustomModels for models with a custom `__implementation__`"""
if models is None:
models = Model.model_class_reverse_map.values()
custom_models = OrderedDict()
for cls in models:
impl = getattr(cls, "__implementation__", None)
if impl i... | def _get_custom_models(models):
| """Returns CustomModels for models with a custom `__implementation__`"""
if models is None:
models = Model.model_class_reverse_map.values()
custom_models = OrderedDict()
for cls in models:
impl = getattr(cls, "__implementation__", None)
if impl is not None:
model = ... | = run_app(["--version"])
except RuntimeError:
return None
else:
return version.strip()
def _model_cache_no_op(model, implementation):
"""Return cached compiled implementation"""
return None
_CACHING_IMPLEMENTATION = _model_cache_no_op
def _get_custom_models(models):
| 64 | 64 | 103 | 7 | 56 | arihans/bokeh | bokeh/util/compiler.py | Python | _get_custom_models | _get_custom_models | 452 | 467 | 452 | 452 | 684e0c543a90ac676e8644f6acc8fe4939b89c0a | bigcode/the-stack | train |
32be953d7f5e103ab9de0c30 | train | function | def _bundle_models(custom_models):
""" Create a JavaScript bundle with selected `models`. """
exports = []
modules = []
with io.open(join(bokehjs_dir, "js", "bokeh.json"), encoding="utf-8") as f:
bokeh = json.loads(f.read())
known_modules = set()
for artifact in bokeh["artifacts"]:
... | def _bundle_models(custom_models):
| """ Create a JavaScript bundle with selected `models`. """
exports = []
modules = []
with io.open(join(bokehjs_dir, "js", "bokeh.json"), encoding="utf-8") as f:
bokeh = json.loads(f.read())
known_modules = set()
for artifact in bokeh["artifacts"]:
canonical = artifact["module"]... | custom_models[model.full_name] = model
if not custom_models:
return None
return custom_models
def _compile_models(custom_models):
"""Returns the compiled implementation of supplied `models`. """
ordered_models = sorted(custom_models.values(), key=lambda model: model.full_name)
custom_impl... | 231 | 231 | 773 | 7 | 223 | arihans/bokeh | bokeh/util/compiler.py | Python | _bundle_models | _bundle_models | 495 | 588 | 495 | 495 | 7fe5453670f8f9b4968d69c84ca4a14466ff730f | bigcode/the-stack | train |
dbbdeabeae8887e8d0d4e1c5 | train | function | def bundle_all_models():
"""Create a bundle of all models. """
return bundle_models(None)
| def bundle_all_models():
| """Create a bundle of all models. """
return bundle_models(None)
| if bundle is None:
try:
_bundle_cache[key] = bundle = _bundle_models(custom_models)
except CompilationError as error:
print("Compilation failed:", file=sys.stderr)
print(str(error), file=sys.stderr)
sys.exit(1)
return bundle
def bundle_all_models():
| 64 | 64 | 21 | 5 | 58 | arihans/bokeh | bokeh/util/compiler.py | Python | bundle_all_models | bundle_all_models | 303 | 305 | 303 | 303 | 4e7c14c9f04dbbbd41c1543720399a74bd6ef352 | bigcode/the-stack | train |
b280a3cbe0a56a0af362d073 | train | function | def _run(app, argv, input=None):
proc = Popen([app] + argv, stdout=PIPE, stderr=PIPE, stdin=PIPE)
(stdout, errout) = proc.communicate(input=None if input is None else json.dumps(input).encode())
if proc.returncode != 0:
raise RuntimeError(errout.decode('utf-8'))
else:
return _crlf_cr_2_... | def _run(app, argv, input=None):
| proc = Popen([app] + argv, stdout=PIPE, stderr=PIPE, stdin=PIPE)
(stdout, errout) = proc.communicate(input=None if input is None else json.dumps(input).encode())
if proc.returncode != 0:
raise RuntimeError(errout.decode('utf-8'))
else:
return _crlf_cr_2_lf(stdout.decode('utf-8'))
| == "win32":
_npmjs += '.cmd'
return _npmjs
def _crlf_cr_2_lf(s):
return re.sub(r"\\r\\n|\\r|\\n", r"\\n", s)
def _run(app, argv, input=None):
| 64 | 64 | 98 | 10 | 54 | arihans/bokeh | bokeh/util/compiler.py | Python | _run | _run | 423 | 430 | 423 | 423 | c88d6f8d852319aa2c8b55b630d075d3290bc7de | bigcode/the-stack | train |
83001b763ea4214204f7b66e | train | function | def _run_npmjs(argv, input=None):
return _run(_npmjs_path(), argv, input)
| def _run_npmjs(argv, input=None):
| return _run(_npmjs_path(), argv, input)
| RuntimeError(errout.decode('utf-8'))
else:
return _crlf_cr_2_lf(stdout.decode('utf-8'))
def _run_nodejs(argv, input=None):
return _run(_nodejs_path(), argv, input)
def _run_npmjs(argv, input=None):
| 64 | 64 | 24 | 11 | 53 | arihans/bokeh | bokeh/util/compiler.py | Python | _run_npmjs | _run_npmjs | 435 | 436 | 435 | 435 | 91466ad7ee1e47b2314de5136f62c01c13449b45 | bigcode/the-stack | train |
c9c5aee4f1ba9138de965c2b | train | function | def npmjs_version():
return _version(_run_npmjs)
| def npmjs_version():
| return _version(_run_npmjs)
| = error
def __str__(self):
return "\n" + self.text.strip()
bokehjs_dir = settings.bokehjsdir()
nodejs_min_version = (10, 13, 0)
def nodejs_version():
return _version(_run_nodejs)
def npmjs_version():
| 64 | 64 | 15 | 5 | 59 | arihans/bokeh | bokeh/util/compiler.py | Python | npmjs_version | npmjs_version | 96 | 97 | 96 | 96 | 9c46dec41e2c9e0de55409fb5d16720dd7d4b241 | bigcode/the-stack | train |
e127f078eecf81040c684fa8 | train | function | def test_local_install():
runner = CliRunner()
result = runner.invoke(install, ['local'])
assert result.exit_code == 0
assert result.output == 'Successfully installed for current repository!\n'
hook_file_path = os.path.join(
os.getcwd(),
'.git',
'hooks',
HOOK_FILENA... | def test_local_install():
| runner = CliRunner()
result = runner.invoke(install, ['local'])
assert result.exit_code == 0
assert result.output == 'Successfully installed for current repository!\n'
hook_file_path = os.path.join(
os.getcwd(),
'.git',
'hooks',
HOOK_FILENAME,
)
assert os.pa... | import os
from click.testing import CliRunner
from podmena.cli import install
from podmena.cli import HOOK_FILENAME, DATABASE_FILE
def test_local_install():
| 34 | 64 | 119 | 5 | 28 | bmwant/podmena | tests/test_cli.py | Python | test_local_install | test_local_install | 9 | 30 | 9 | 9 | ce21a2e03dd88340e93acc8036797c167a0179bc | bigcode/the-stack | train |
9776f599e8b574dfdea951c3 | train | function | def test_global_install():
pass
| def test_global_install():
| pass
| git',
'hooks',
HOOK_FILENAME,
)
assert os.path.exists(hook_file_path)
db_file_path = os.path.join(
os.getcwd(),
'.git',
'hooks',
DATABASE_FILE
)
assert os.path.exists(db_file_path)
def test_global_install():
| 64 | 64 | 8 | 5 | 59 | bmwant/podmena | tests/test_cli.py | Python | test_global_install | test_global_install | 33 | 34 | 33 | 33 | 68062c7ac8c7d3dbd003e7af203ad1c82a976096 | bigcode/the-stack | train |
dbaf5bc84c80504b9d4bded5 | train | function | def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
| def read(fname):
| return open(os.path.join(os.path.dirname(__file__), fname)).read()
| import setup
# Utility function to read the README file.
# Used for the long_description. It's nice, because now 1) we have a top level
# README file and 2) it's easier to type in the README file than to put a raw
# string in below ...
def read(fname):
| 64 | 64 | 20 | 4 | 60 | gmuraru/PyGridNode | setup.py | Python | read | read | 11 | 12 | 11 | 11 | 25140daff2d7629339d0ed0f8504d53a5ea3d9b3 | bigcode/the-stack | train |
24289ec36be94b0e99fb5986 | train | function | def get_requirements(req_file):
"""Read requirements file and return packages and git repos separately"""
requirements = []
dependency_links = []
lines = read(req_file).split("\n")
for line in lines:
if line.startswith("git+"):
dependency_links.append(line)
else:
... | def get_requirements(req_file):
| """Read requirements file and return packages and git repos separately"""
requirements = []
dependency_links = []
lines = read(req_file).split("\n")
for line in lines:
if line.startswith("git+"):
dependency_links.append(line)
else:
requirements.append(line)
... | because now 1) we have a top level
# README file and 2) it's easier to type in the README file than to put a raw
# string in below ...
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
def get_requirements(req_file):
| 64 | 64 | 75 | 7 | 57 | gmuraru/PyGridNode | setup.py | Python | get_requirements | get_requirements | 15 | 25 | 15 | 15 | 9d6175eda5c0e6f8cbe7a89a270c58f8c204b61b | bigcode/the-stack | train |
a6946232db7df1cfd1351674 | train | function | def safe_as_int(val, atol=1e-3):
"""
Attempt to safely cast values to integer format.
Parameters
----------
val : scalar or iterable of scalars
Number or container of numbers which are intended to be interpreted as
integers, e.g., for indexing purposes, but which may not carry integ... | def safe_as_int(val, atol=1e-3):
| """
Attempt to safely cast values to integer format.
Parameters
----------
val : scalar or iterable of scalars
Number or container of numbers which are intended to be interpreted as
integers, e.g., for indexing purposes, but which may not carry integer
type.
atol : float... | precation,
filename=func_code.co_filename,
lineno=func_code.co_firstlineno + 1)
elif self.behavior == 'raise':
raise skimage_deprecation(msg)
return func(*args, **kwargs)
# modify doc string to... | 166 | 167 | 559 | 13 | 153 | oz90210/Pyto | site-packages/skimage/_shared/utils.py | Python | safe_as_int | safe_as_int | 87 | 151 | 87 | 87 | b3c679f99753f8aaf9718d0a4c6f33f2841a1031 | bigcode/the-stack | train |
936fc79f809d98e4f44dac72 | train | function | def check_nD(array, ndim, arg_name='image'):
"""
Verify an array meets the desired ndims and array isn't empty.
Parameters
----------
array : array-like
Input array to be validated
ndim : int or iterable of ints
Allowable ndim or ndims for the array.
arg_name : str, optional... | def check_nD(array, ndim, arg_name='image'):
| """
Verify an array meets the desired ndims and array isn't empty.
Parameters
----------
array : array-like
Input array to be validated
ndim : int or iterable of ints
Allowable ndim or ndims for the array.
arg_name : str, optional
The name of the array in the origina... | )
def check_shape_equality(im1, im2):
"""Raise an error if the shape do not match."""
if not im1.shape == im2.shape:
raise ValueError('Input images must have the same dimensions.')
return
def check_nD(array, ndim, arg_name='image'):
| 64 | 64 | 205 | 13 | 50 | oz90210/Pyto | site-packages/skimage/_shared/utils.py | Python | check_nD | check_nD | 161 | 183 | 161 | 161 | c91d1187f128599bf6312f3b027bd78e086fde90 | bigcode/the-stack | train |
817c9b48a4997a23f871d363 | train | class | class deprecated(object):
"""Decorator to mark deprecated functions with warning.
Adapted from <http://wiki.python.org/moin/PythonDecoratorLibrary>.
Parameters
----------
alt_func : str
If given, tell user what function to use instead.
behavior : {'warn', 'raise'}
Behavior duri... | class deprecated(object):
| """Decorator to mark deprecated functions with warning.
Adapted from <http://wiki.python.org/moin/PythonDecoratorLibrary>.
Parameters
----------
alt_func : str
If given, tell user what function to use instead.
behavior : {'warn', 'raise'}
Behavior during call to deprecated func... | import warnings
import functools
import sys
import numpy as np
import types
import numbers
from ..util import img_as_float
from ._warnings import all_warnings, warn
__all__ = ['deprecated', 'get_bound_method_class', 'all_warnings',
'safe_as_int', 'check_nD', 'check_shape_equality', 'warn']
class skimage_... | 120 | 131 | 437 | 4 | 115 | oz90210/Pyto | site-packages/skimage/_shared/utils.py | Python | deprecated | deprecated | 23 | 77 | 23 | 23 | 36417ac6eb7e7c10cc26d93cfc16db2ef69cf732 | bigcode/the-stack | train |
3bfce36f221b151e16291270 | train | function | def check_random_state(seed):
"""Turn seed into a `np.random.RandomState` instance.
Parameters
----------
seed : None, int or np.random.RandomState
If `seed` is None, return the RandomState singleton used by `np.random`.
If `seed` is an int, return a new RandomState instance seede... | def check_random_state(seed):
| """Turn seed into a `np.random.RandomState` instance.
Parameters
----------
seed : None, int or np.random.RandomState
If `seed` is None, return the RandomState singleton used by `np.random`.
If `seed` is an int, return a new RandomState instance seeded with `seed`.
If `... | Parameters
----------
f : function
Function to copy.
name : str, optional
Name of new function.
"""
return types.FunctionType(f.__code__, f.__globals__, name or f.__name__,
f.__defaults__, f.__closure__)
def check_random_state(seed):
| 64 | 64 | 209 | 6 | 58 | oz90210/Pyto | site-packages/skimage/_shared/utils.py | Python | check_random_state | check_random_state | 201 | 225 | 201 | 201 | e6b3e6c04ae3c5e854f53776a2434abb62b0606a | bigcode/the-stack | train |
fd4d37bb42653c5c825b7fcf | train | function | def convert_to_float(image, preserve_range):
"""Convert input image to double image with the appropriate range.
Parameters
----------
image : ndarray
Input image.
preserve_range : bool
Determines if the range of the image should be kept or transformed
using img_as_float. Als... | def convert_to_float(image, preserve_range):
| """Convert input image to double image with the appropriate range.
Parameters
----------
image : ndarray
Input image.
preserve_range : bool
Determines if the range of the image should be kept or transformed
using img_as_float. Also see
https://scikit-image.org/docs/d... | (numbers.Integral, np.integer)):
return np.random.RandomState(seed)
if isinstance(seed, np.random.RandomState):
return seed
raise ValueError('%r cannot be used to seed a numpy.random.RandomState'
' instance' % seed)
def convert_to_float(image, preserve_range):
| 64 | 64 | 129 | 9 | 55 | oz90210/Pyto | site-packages/skimage/_shared/utils.py | Python | convert_to_float | convert_to_float | 228 | 249 | 228 | 228 | e718e874cd9adb7133795029266b89bdf0f4620d | bigcode/the-stack | train |
39a961a3c9aaa302c62e2019 | train | class | class skimage_deprecation(Warning):
"""Create our own deprecation class, since Python >= 2.7
silences deprecations by default.
"""
pass
| class skimage_deprecation(Warning):
| """Create our own deprecation class, since Python >= 2.7
silences deprecations by default.
"""
pass
| ..util import img_as_float
from ._warnings import all_warnings, warn
__all__ = ['deprecated', 'get_bound_method_class', 'all_warnings',
'safe_as_int', 'check_nD', 'check_shape_equality', 'warn']
class skimage_deprecation(Warning):
| 64 | 64 | 39 | 8 | 56 | oz90210/Pyto | site-packages/skimage/_shared/utils.py | Python | skimage_deprecation | skimage_deprecation | 15 | 20 | 15 | 15 | 58b9679a9e8ddec0abfc943d8b1af892689202f9 | bigcode/the-stack | train |
25fe7644a33f9e0804212bb5 | train | function | def get_bound_method_class(m):
"""Return the class for a bound method.
"""
return m.im_class if sys.version < '3' else m.__self__.__class__
| def get_bound_method_class(m):
| """Return the class for a bound method.
"""
return m.im_class if sys.version < '3' else m.__self__.__class__
| precation warning
doc = '**Deprecated function**.' + alt_msg
if wrapped.__doc__ is None:
wrapped.__doc__ = doc
else:
wrapped.__doc__ = doc + '\n\n ' + wrapped.__doc__
return wrapped
def get_bound_method_class(m):
| 64 | 64 | 38 | 7 | 56 | oz90210/Pyto | site-packages/skimage/_shared/utils.py | Python | get_bound_method_class | get_bound_method_class | 80 | 84 | 80 | 80 | 2b61e9f115540b86b8ec52ed43926f2f6b92df7f | bigcode/the-stack | train |
4b920760f263bfba1e3ebf20 | train | function | def check_shape_equality(im1, im2):
"""Raise an error if the shape do not match."""
if not im1.shape == im2.shape:
raise ValueError('Input images must have the same dimensions.')
return
| def check_shape_equality(im1, im2):
| """Raise an error if the shape do not match."""
if not im1.shape == im2.shape:
raise ValueError('Input images must have the same dimensions.')
return
| np.testing.assert_allclose(mod, 0, atol=atol)
except AssertionError:
raise ValueError("Integer argument required but received "
"{0}, check inputs.".format(val))
return np.round(val).astype(np.int64)
def check_shape_equality(im1, im2):
| 64 | 64 | 50 | 11 | 53 | oz90210/Pyto | site-packages/skimage/_shared/utils.py | Python | check_shape_equality | check_shape_equality | 154 | 158 | 154 | 154 | 3f8bb66825bac349637f9b9811eff1c94e3ee55a | bigcode/the-stack | train |
93920700c929682369067093 | train | function | def copy_func(f, name=None):
"""Create a copy of a function.
Parameters
----------
f : function
Function to copy.
name : str, optional
Name of new function.
"""
return types.FunctionType(f.__code__, f.__globals__, name or f.__name__,
f.__defaul... | def copy_func(f, name=None):
| """Create a copy of a function.
Parameters
----------
f : function
Function to copy.
name : str, optional
Name of new function.
"""
return types.FunctionType(f.__code__, f.__globals__, name or f.__name__,
f.__defaults__, f.__closure__)
| if array.size == 0:
raise ValueError(msg_empty_array % (arg_name))
if not array.ndim in ndim:
raise ValueError(msg_incorrect_dim % (arg_name, '-or-'.join([str(n) for n in ndim])))
def copy_func(f, name=None):
| 63 | 64 | 75 | 8 | 55 | oz90210/Pyto | site-packages/skimage/_shared/utils.py | Python | copy_func | copy_func | 186 | 198 | 186 | 186 | d397a2f30d35ed19bfa5bf2b87a4946d8a372825 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.