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
d1284875020b37cde911644a
train
class
class Callback: """A class to provide gpio level change callbacks.""" def __init__(self, notify, user_gpio, edge=RISING_EDGE, func=None): """ Initialise a callback and adds it to the notification thread. """ self._notify = notify self.count = 0 if func is None: ...
class Callback:
"""A class to provide gpio level change callbacks.""" def __init__(self, notify, user_gpio, edge=RISING_EDGE, func=None): """ Initialise a callback and adds it to the notification thread. """ self._notify = notify self.count = 0 if func is None: func ...
struct.pack('IIII', cmd, p1, p2, 0) await self._loop.sock_sendall(self.s, data) response = await self._loop.sock_recv(self.s, 16) _, res = struct.unpack('12sI', response) return res class Callback:
64
64
216
3
60
nowls/apigpio
apigpio/apigpio.py
Python
Callback
Callback
465
495
465
465
9791841b526f84ed2f01b7231df5161ff356b255
bigcode/the-stack
train
710450e73548176c7af10ffe
train
class
class ApigpioError(Exception): """pigpio module exception""" def __init__(self, value): self.value = value def __str__(self): return repr(self.value)
class ApigpioError(Exception):
"""pigpio module exception""" def __init__(self, value): self.value = value def __str__(self): return repr(self.value)
", PI_CHAIN_NESTING: "chain counters nested too deeply", PI_CHAIN_TOO_BIG: "chain is too long", PI_DEPRECATED: "deprecated function removed", PI_BAD_SER_INVERT: "bit bang serial invert not 0 or 1" } class ApigpioError(Exception):
64
64
42
7
57
nowls/apigpio
apigpio/apigpio.py
Python
ApigpioError
ApigpioError
255
261
255
255
bdb4be3c69aca107c4a6b13e9e5fd1d77ad7b89c
bigcode/the-stack
train
94dcd041db060738b7649b47
train
function
def error_text(errnum): """ Returns a text description of a pigpio error. errnum:= <0, the error number ... print(pigpio.error_text(-5)) level not 0-1 ... """ return _errors.get(errnum) or "unknown error ({})".format(errnum)
def error_text(errnum):
""" Returns a text description of a pigpio error. errnum:= <0, the error number ... print(pigpio.error_text(-5)) level not 0-1 ... """ return _errors.get(errnum) or "unknown error ({})".format(errnum)
the pulse. gpio_off:= the GPIO to switch off at the start of the pulse. delay:= the delay in microseconds before the next pulse. """ self.gpio_on = gpio_on self.gpio_off = gpio_off self.delay = delay def error_text(errnum):
64
64
73
6
57
nowls/apigpio
apigpio/apigpio.py
Python
error_text
error_text
281
292
281
281
cc3c0d6f28a6c010f0a5564c23f3294e81698ee1
bigcode/the-stack
train
d19324dd0684f0ad2677a459
train
function
def _u2i(uint32): """ Converts a 32 bit unsigned number to signed. If the number is negative it indicates an error. On error a pigpio exception will be raised if exceptions is True. """ v = u2i(uint32) if v < 0: if exceptions: raise ApigpioError(error_text(v)) retur...
def _u2i(uint32):
""" Converts a 32 bit unsigned number to signed. If the number is negative it indicates an error. On error a pigpio exception will be raised if exceptions is True. """ v = u2i(uint32) if v < 0: if exceptions: raise ApigpioError(error_text(v)) return v
37 ... """ mask = (2 ** 32) - 1 if uint32 & (1 << 31): v = uint32 | ~mask else: v = uint32 & mask return v def _u2i(uint32):
64
64
87
8
55
nowls/apigpio
apigpio/apigpio.py
Python
_u2i
_u2i
315
325
315
315
a69a31cbfc6ca93e886b238a8460d1c3dfac1506
bigcode/the-stack
train
2bbdd360570b4d95cf8837cb
train
class
class UploadCommand(Command): """Support setup.py upload.""" description = "Build and publish the package." user_options = [] @staticmethod def status(s): """Prints things in bold.""" print("\033[1m{0}\033[0m".format(s)) def initialize_options(self): pass def fina...
class UploadCommand(Command):
"""Support setup.py upload.""" description = "Build and publish the package." user_options = [] @staticmethod def status(s): """Prints things in bold.""" print("\033[1m{0}\033[0m".format(s)) def initialize_options(self): pass def finalize_options(self): pa...
= {} if not VERSION: project_slug = NAME.lower().replace("-", "_").replace(" ", "_") with open(os.path.join(here, project_slug, "__version__.py")) as f: exec(f.read(), about) else: about["__version__"] = VERSION class UploadCommand(Command):
66
66
221
5
60
rdmolony/streamlit-cloud-uploader
setup.py
Python
UploadCommand
UploadCommand
56
90
56
56
2dcfb07ae1b1d7f2fc8c9f5f823700a2198893d2
bigcode/the-stack
train
3094625ccb6e34bbbe5d964c
train
class
class ClassificationTask: def __init__(self, texts, labels, optimize="compute"): self.texts = texts self.hidden_idx = 1 # TODO we might think of using sklearn's LabelEncoder here for broader support self.labels = labels self.optimize = optimize self.num_labels = len(...
class ClassificationTask:
def __init__(self, texts, labels, optimize="compute"): self.texts = texts self.hidden_idx = 1 # TODO we might think of using sklearn's LabelEncoder here for broader support self.labels = labels self.optimize = optimize self.num_labels = len(set(labels)) self....
from transformers import AutoModelForSequenceClassification from transformers.models.auto.configuration_auto import AutoConfig from transformers import AutoTokenizer from torch.nn import CrossEntropyLoss from transformer_baselines.dataset import * # TODO: Task should be an abstract class class ClassificationTask:
54
64
200
4
49
MilaNLProc/nlpb
transformer_baselines/tasks/classification.py
Python
ClassificationTask
ClassificationTask
8
32
8
8
9f4157bd83dca36bdb6ec3126d182920c3d1238c
bigcode/the-stack
train
a17bb533bca614e59bfed134
train
function
def _check_box_size(size): if int(size) <= 0: raise ValueError( f"Invalid box size (was {size}, expected larger than 0)")
def _check_box_size(size):
if int(size) <= 0: raise ValueError( f"Invalid box size (was {size}, expected larger than 0)")
from bisect import bisect_left # Cache modules generated just based on the QR Code version precomputed_qr_blanks = {} def make(data=None, **kwargs): qr = QRCode(**kwargs) qr.add_data(data) return qr.make_image() def _check_box_size(size):
64
64
38
7
57
Aayush3thoughtwin/nft_metaplex
QRCode_generator/.env/qrcode/lib/python3.8/site-packages/qrcode/main.py
Python
_check_box_size
_check_box_size
16
19
16
16
d807c244c1c85ae16516ccfe6d05ce1a5fa25881
bigcode/the-stack
train
f92272896d588353ad112bcf
train
function
def copy_2d_array(x): return [row[:] for row in x]
def copy_2d_array(x):
return [row[:] for row in x]
Error( f"Invalid mask pattern (was {type(mask_pattern)}, expected int)") if mask_pattern < 0 or mask_pattern > 7: raise ValueError( f"Mask pattern should be in range(8) (got {mask_pattern})") def copy_2d_array(x):
64
64
18
8
56
Aayush3thoughtwin/nft_metaplex
QRCode_generator/.env/qrcode/lib/python3.8/site-packages/qrcode/main.py
Python
copy_2d_array
copy_2d_array
36
37
36
36
2a4a289b0f1c612d74d4483f29646f3007950d69
bigcode/the-stack
train
6fa7ccc5fececb13ab986a1f
train
function
def make(data=None, **kwargs): qr = QRCode(**kwargs) qr.add_data(data) return qr.make_image()
def make(data=None, **kwargs):
qr = QRCode(**kwargs) qr.add_data(data) return qr.make_image()
from qrcode import constants, exceptions, util from qrcode.image.base import BaseImage import sys from bisect import bisect_left # Cache modules generated just based on the QR Code version precomputed_qr_blanks = {} def make(data=None, **kwargs):
58
64
28
8
50
Aayush3thoughtwin/nft_metaplex
QRCode_generator/.env/qrcode/lib/python3.8/site-packages/qrcode/main.py
Python
make
make
10
13
10
10
c458407e88c0d4d90c554c7deeea8372538fd339
bigcode/the-stack
train
656c1d548003f556661a83c7
train
class
class QRCode: def __init__(self, version=None, error_correction=constants.ERROR_CORRECT_M, box_size=10, border=4, image_factory=None, mask_pattern=None): _check_box_size(box_size) _check_border(border) self.version = versio...
class QRCode:
def __init__(self, version=None, error_correction=constants.ERROR_CORRECT_M, box_size=10, border=4, image_factory=None, mask_pattern=None): _check_box_size(box_size) _check_border(border) self.version = version and int(versi...
util from qrcode.image.base import BaseImage import sys from bisect import bisect_left # Cache modules generated just based on the QR Code version precomputed_qr_blanks = {} def make(data=None, **kwargs): qr = QRCode(**kwargs) qr.add_data(data) return qr.make_image() def _check_box_size(size): if ...
256
256
3,208
4
252
Aayush3thoughtwin/nft_metaplex
QRCode_generator/.env/qrcode/lib/python3.8/site-packages/qrcode/main.py
Python
QRCode
QRCode
39
467
39
40
1b8c5f35453c75dff8942d44a7e8ee1cfce38121
bigcode/the-stack
train
293da6d3d2fdf3e7a15d949a
train
function
def _check_border(size): if int(size) < 0: raise ValueError("Invalid border value (was %s, expected 0 or larger than that)" % size)
def _check_border(size):
if int(size) < 0: raise ValueError("Invalid border value (was %s, expected 0 or larger than that)" % size)
qr = QRCode(**kwargs) qr.add_data(data) return qr.make_image() def _check_box_size(size): if int(size) <= 0: raise ValueError( f"Invalid box size (was {size}, expected larger than 0)") def _check_border(size):
63
64
39
6
57
Aayush3thoughtwin/nft_metaplex
QRCode_generator/.env/qrcode/lib/python3.8/site-packages/qrcode/main.py
Python
_check_border
_check_border
21
23
21
21
52f24b7d59067c7efaf057a1c390461744c37157
bigcode/the-stack
train
3d8698737f562fe6b072a13a
train
function
def _check_mask_pattern(mask_pattern): if mask_pattern is None: return if not isinstance(mask_pattern, int): raise TypeError( f"Invalid mask pattern (was {type(mask_pattern)}, expected int)") if mask_pattern < 0 or mask_pattern > 7: raise ValueError( f"Mask pa...
def _check_mask_pattern(mask_pattern):
if mask_pattern is None: return if not isinstance(mask_pattern, int): raise TypeError( f"Invalid mask pattern (was {type(mask_pattern)}, expected int)") if mask_pattern < 0 or mask_pattern > 7: raise ValueError( f"Mask pattern should be in range(8) (got {mask_...
f"Invalid box size (was {size}, expected larger than 0)") def _check_border(size): if int(size) < 0: raise ValueError("Invalid border value (was %s, expected 0 or larger than that)" % size) def _check_mask_pattern(mask_pattern):
64
64
86
8
56
Aayush3thoughtwin/nft_metaplex
QRCode_generator/.env/qrcode/lib/python3.8/site-packages/qrcode/main.py
Python
_check_mask_pattern
_check_mask_pattern
26
34
26
26
a9f38338470c876383d2b4b0b9aa6bd43e2d3c28
bigcode/the-stack
train
bae13e0cf175d5ac8d0451ce
train
class
class Unknown(Condition): def check(self): raise ExcusableError("no idea")
class Unknown(Condition):
def check(self): raise ExcusableError("no idea")
Integer from edera.requisites import shortcut from edera.workflow import WorkflowBuilder from edera.workflow.processors import WorkflowTrimmer class AlreadyComplete(Condition): def check(self): return True class StillIncomplete(Condition): def check(self): return False class Unknown(Condi...
64
64
19
5
58
thoughteer/edera
tests/unit/workflow/processors/test_workflow_trimmer.py
Python
Unknown
Unknown
26
29
26
27
d1499012d31f3113bac7af9e5843e26d81caebad
bigcode/the-stack
train
e878464d904e4eb267a96bfc
train
class
class AlreadyComplete(Condition): def check(self): return True
class AlreadyComplete(Condition):
def check(self): return True
from edera import Parameterizable from edera import Task from edera.exceptions import ExcusableError from edera.qualifiers import Integer from edera.requisites import shortcut from edera.workflow import WorkflowBuilder from edera.workflow.processors import WorkflowTrimmer class AlreadyComplete(Condition):
64
64
15
6
57
thoughteer/edera
tests/unit/workflow/processors/test_workflow_trimmer.py
Python
AlreadyComplete
AlreadyComplete
14
17
14
15
2dc1f347aadde5a2727ba792d92a6d465986c242
bigcode/the-stack
train
ab5a972d1ee88191b3de2625
train
function
@pytest.mark.parametrize("n", [1, 2, 3, 5, 10]) def test_workflow_trimmer_trims_nn_workflow_well(n): class T(Parameterizable, Task): i = Parameter(Integer) j = Parameter(Integer) s = Parameter(Integer) @shortcut def requisite(self): if self.i == 0: ...
@pytest.mark.parametrize("n", [1, 2, 3, 5, 10]) def test_workflow_trimmer_trims_nn_workflow_well(n):
class T(Parameterizable, Task): i = Parameter(Integer) j = Parameter(Integer) s = Parameter(Integer) @shortcut def requisite(self): if self.i == 0: return return (T(i=(self.i - 1), j=j, s=self.s) for j in range(n)) @property ...
immer().process(workflow) assert all(T(i=i, s=s) in workflow for i in range(s, n)) assert len(workflow) <= n - s + 3 @pytest.mark.parametrize("n", [1, 2, 3, 5, 10]) def test_workflow_trimmer_trims_nn_workflow_well(n):
76
76
255
36
39
thoughteer/edera
tests/unit/workflow/processors/test_workflow_trimmer.py
Python
test_workflow_trimmer_trims_nn_workflow_well
test_workflow_trimmer_trims_nn_workflow_well
65
96
65
67
23f18f49256ba239253af059cc53c21bd573c2de
bigcode/the-stack
train
edbefd78504e0b07cdb50f92
train
function
@pytest.mark.parametrize("n", [1, 2, 3, 5, 10, 19]) def test_workflow_trimmer_trims_linear_workflow_well(n): class T(Parameterizable, Task): i = Parameter(Integer) s = Parameter(Integer) @shortcut def requisite(self): if self.i == 0: return ...
@pytest.mark.parametrize("n", [1, 2, 3, 5, 10, 19]) def test_workflow_trimmer_trims_linear_workflow_well(n):
class T(Parameterizable, Task): i = Parameter(Integer) s = Parameter(Integer) @shortcut def requisite(self): if self.i == 0: return return T(i=(self.i - 1), s=self.s) @property def target(self): if self.i == self....
raise ExcusableError("no idea") class Broken(Condition): def check(self): raise RuntimeError("oops") @pytest.mark.parametrize("n", [1, 2, 3, 5, 10, 19]) def test_workflow_trimmer_trims_linear_workflow_well(n):
64
64
210
39
25
thoughteer/edera
tests/unit/workflow/processors/test_workflow_trimmer.py
Python
test_workflow_trimmer_trims_linear_workflow_well
test_workflow_trimmer_trims_linear_workflow_well
38
62
38
40
c73d600cd171797596d94a35bd6f6d212f566d55
bigcode/the-stack
train
6d7edfb4caa2a14a007f2b26
train
class
class Broken(Condition): def check(self): raise RuntimeError("oops")
class Broken(Condition):
def check(self): raise RuntimeError("oops")
edera.workflow.processors import WorkflowTrimmer class AlreadyComplete(Condition): def check(self): return True class StillIncomplete(Condition): def check(self): return False class Unknown(Condition): def check(self): raise ExcusableError("no idea") class Broken(Condition)...
64
64
17
5
59
thoughteer/edera
tests/unit/workflow/processors/test_workflow_trimmer.py
Python
Broken
Broken
32
35
32
33
f198fa885f8b6cc05b0fef22bbad31b0a6f69233
bigcode/the-stack
train
9dcea326014713906b0f11ef
train
class
class StillIncomplete(Condition): def check(self): return False
class StillIncomplete(Condition):
def check(self): return False
edera.exceptions import ExcusableError from edera.qualifiers import Integer from edera.requisites import shortcut from edera.workflow import WorkflowBuilder from edera.workflow.processors import WorkflowTrimmer class AlreadyComplete(Condition): def check(self): return True class StillIncomplete(Conditio...
64
64
15
6
57
thoughteer/edera
tests/unit/workflow/processors/test_workflow_trimmer.py
Python
StillIncomplete
StillIncomplete
20
23
20
21
6529553151baffb35a24ee389925e86954593f0b
bigcode/the-stack
train
3abf3820c60c7e041c63bc4d
train
function
def run_serial_forwarder(): # ----------------------------------------------------------------------- # # initialize the datastore(serial client) # ----------------------------------------------------------------------- # client = ModbusClient(method='ascii', port='/dev/pts/14') store = RemoteSlaveC...
def run_serial_forwarder(): # ----------------------------------------------------------------------- # # initialize the datastore(serial client) # ----------------------------------------------------------------------- #
client = ModbusClient(method='ascii', port='/dev/pts/14') store = RemoteSlaveContext(client) context = ModbusServerContext(slaves=store, single=True) # ----------------------------------------------------------------------- # # run the server you want # -----------------------------------------...
ModbusServerContext # --------------------------------------------------------------------------- # # configure the service logging # --------------------------------------------------------------------------- # import logging logging.basicConfig() log = logging.getLogger() log.setLevel(logging.DEBUG) def run_seria...
64
64
88
24
40
lightoyou/HoneyPot_CDSI_pymodbus
examples/contrib/serial_forwarder.py
Python
run_serial_forwarder
run_serial_forwarder
28
39
28
31
727e07204af7c38af676efa020df14b163add6de
bigcode/the-stack
train
91bcb39d7db1414fb0b04480
train
class
class RangeSlider(TethysGizmoOptions): """ Sliders can be used to request an input value from a range of possible values. A slider is configured with a dictionary of key-value options. The table below summarizes the options for sliders. Attributes: display_text(str): Display text for the label that...
class RangeSlider(TethysGizmoOptions):
""" Sliders can be used to request an input value from a range of possible values. A slider is configured with a dictionary of key-value options. The table below summarizes the options for sliders. Attributes: display_text(str): Display text for the label that accompanies slider name(str, r...
""" ******************************************************************************** * Name: range_slider.py * Author: Nathan Swain and Ezra Rice * Created On: May 2015 * Copyright: (c) Brigham Young University 2015 * License: BSD 2-Clause ********************************************************************************...
84
163
544
10
74
quyendong/tethys
tethys_gizmos/gizmo_options/range_slider.py
Python
RangeSlider
RangeSlider
15
91
15
15
d88da0dbb76d4c8ef18fd282e2e72d14e7c69774
bigcode/the-stack
train
077184a0588938ce3d9b4523
train
class
class TestUserAdminLdapWithHadoop(BaseUserAdminTests): requires_hadoop = True integration = True def test_ensure_home_directory_add_ldap_users(self): URL = reverse('useradmin:useradmin.views.add_ldap_users') # Set up LDAP tests to use a LdapTestConnection instead of an actual LDAP connection ldap_ac...
class TestUserAdminLdapWithHadoop(BaseUserAdminTests):
requires_hadoop = True integration = True def test_ensure_home_directory_add_ldap_users(self): URL = reverse('useradmin:useradmin.views.add_ldap_users') # Set up LDAP tests to use a LdapTestConnection instead of an actual LDAP connection ldap_access.CACHED_LDAP_CONN = LdapTestConnection() clust...
(URL)) finally: for finish in reset: finish() def test_ldap_exception_handling(self): # Set up LDAP tests to use a LdapTestConnection instead of an actual LDAP connection ldap_access.CACHED_LDAP_CONN = LdapTestConnection() c = make_logged_in_client('test', is_superuser=True) reset...
256
256
870
14
242
yetsun/hue
apps/useradmin/src/useradmin/test_ldap.py
Python
TestUserAdminLdapWithHadoop
TestUserAdminLdapWithHadoop
824
914
824
824
b0d1c3fedeffbf4b2f118c94097d338f99fd2eee
bigcode/the-stack
train
64165adc9e0db8d01b47f2fc
train
function
def get_multi_ldap_config(): return {'multi_ldap_conf': { 'users': {}, 'groups': {} }}
def get_multi_ldap_config():
return {'multi_ldap_conf': { 'users': {}, 'groups': {} }}
UserAdminTests, LdapTestConnection, reset_all_groups, reset_all_users, create_long_username if sys.version_info[0] > 2: from unittest.mock import patch, Mock, MagicMock else: from mock import patch, Mock, MagicMock def get_multi_ldap_config():
64
64
28
7
56
yetsun/hue
apps/useradmin/src/useradmin/test_ldap.py
Python
get_multi_ldap_config
get_multi_ldap_config
49
53
49
49
6949fb9d1683fd6152c3443a784f6732d36a144f
bigcode/the-stack
train
9d499fac767ad29278aeff6e
train
class
class TestUserAdminLdap(BaseUserAdminTests): def test_useradmin_ldap_user_group_membership_sync(self): settings.MIDDLEWARE.append('useradmin.middleware.LdapSynchronizationMiddleware') # Set up LDAP tests to use a LdapTestConnection instead of an actual LDAP connection ldap_access.CACHED_LDAP_CONN = LdapT...
class TestUserAdminLdap(BaseUserAdminTests):
def test_useradmin_ldap_user_group_membership_sync(self): settings.MIDDLEWARE.append('useradmin.middleware.LdapSynchronizationMiddleware') # Set up LDAP tests to use a LdapTestConnection instead of an actual LDAP connection ldap_access.CACHED_LDAP_CONN = LdapTestConnection() # Make sure LDAP groups e...
nose.plugins.attrib import attr from nose.plugins.skip import SkipTest from nose.tools import assert_true, assert_equal, assert_false, assert_raises import desktop.conf from desktop.lib.test_utils import grant_access from desktop.lib.django_test_util import make_logged_in_client from hadoop import pseudo_hdfs4 from h...
255
256
8,815
11
244
yetsun/hue
apps/useradmin/src/useradmin/test_ldap.py
Python
TestUserAdminLdap
TestUserAdminLdap
56
821
56
56
8319d7d8508b6ca3712af94f96f30d662dc07483
bigcode/the-stack
train
e5d0486a26b787800d9c9f12
train
class
class TestYml(unittest.TestCase): default_config = { "intermediate": { "plot": True, "zoom_scale": 0, "colorbars": True, "colormap": "plasma", "scaling": "linear", } , "final_im": ...
class TestYml(unittest.TestCase):
default_config = { "intermediate": { "plot": True, "zoom_scale": 0, "colorbars": True, "colormap": "plasma", "scaling": "linear", } , "final_im": { "plot": Tr...
isort:skip_file """ import yaml import unittest from shutil import copyfile import os import pandas as pd import numpy as np import astropy.io.fits as pyfits import simmer.add_dark_exp as ad import simmer.schemas.custom_validator as validator import simmer.schemas.read_yml as read import simmer.insts as i import sim...
216
216
723
8
207
cdressing/SImMER
src/simmer/tests/tests_io.py
Python
TestYml
TestYml
42
140
42
42
5dee2ad4f8d335f93154aa022a6e38f0902b1e99
bigcode/the-stack
train
ecc9ed4744c8063afcfcd07c
train
class
class TestPHAROSpecific(unittest.TestCase): inst = i.PHARO() def test_readpharo_quadrants(self): try: download_folder("readpharo_test") except: raise DataDownloadException( "Could not download test data for readpharo function." ) raw_d...
class TestPHAROSpecific(unittest.TestCase):
inst = i.PHARO() def test_readpharo_quadrants(self): try: download_folder("readpharo_test") except: raise DataDownloadException( "Could not download test data for readpharo function." ) raw_dir, new_dir, test_red_dir = ( "s...
frame.loc[20, "Start"] = np.nan frame.to_csv(nan_start_config_path) self.assertRaises( c.LogsheetError, c.create_config, nan_start_config_path, "created_frame.csv", tab, ) class TestPHAROSpecific(unittest.TestCase):
65
65
219
10
55
cdressing/SImMER
src/simmer/tests/tests_io.py
Python
TestPHAROSpecific
TestPHAROSpecific
234
255
234
234
fc3fb955b521efad0b02b3f50287f4efb71920ad
bigcode/the-stack
train
65593821f21d5e3416855874
train
function
@contextmanager def captured_output(): new_out, new_err = StringIO(), StringIO() old_out, old_err = sys.stdout, sys.stderr try: sys.stdout, sys.stderr = new_out, new_err yield sys.stdout, sys.stderr finally: sys.stdout, sys.stderr = old_out, old_err
@contextmanager def captured_output():
new_out, new_err = StringIO(), StringIO() old_out, old_err = sys.stdout, sys.stderr try: sys.stdout, sys.stderr = new_out, new_err yield sys.stdout, sys.stderr finally: sys.stdout, sys.stderr = old_out, old_err
as c import simmer.check_logsheet as check import simmer.search_headers as search from simmer.tests.tests_reduction import ( download_folder, delete_folder, DataDownloadException, ) from contextlib import contextmanager from io import StringIO import sys @contextmanager def captured_output():
64
64
74
8
55
cdressing/SImMER
src/simmer/tests/tests_io.py
Python
captured_output
captured_output
31
39
31
32
e4bea6c6a409896c5bac9cf809775d25522eee66
bigcode/the-stack
train
74d865bfb60818d7bbc6d9ea
train
class
class TestShARCSSpecific(unittest.TestCase): inst = i.ShARCS() def test_search_headers_no_framenum(self): """ Tests the search_headers function against the original file that caused the issue. """ try: download_folder("search_headers") except: ...
class TestShARCSSpecific(unittest.TestCase):
inst = i.ShARCS() def test_search_headers_no_framenum(self): """ Tests the search_headers function against the original file that caused the issue. """ try: download_folder("search_headers") except: raise DataDownloadException( ...
readpharo function." ) raw_dir, new_dir, test_red_dir = ( "src/simmer/tests/readpharo_test/raw/", "src/simmer/tests/readpharo_test/test_newdir/", "src/simmer/tests/readpharo_test/test_red/", ) self.inst.read_data(raw_dir, new_dir) compare_...
171
171
573
10
161
cdressing/SImMER
src/simmer/tests/tests_io.py
Python
TestShARCSSpecific
TestShARCSSpecific
258
336
258
258
efa37090d52bceefda2984ad22311c6fcaf1344e
bigcode/the-stack
train
57c8916b2aefbf8859eead57
train
class
class TestConfig(unittest.TestCase): def test_create_config_csv(self): try: download_folder("config_test") except: raise DataDownloadException( "Could not download test data for config_test." ) tab = "Sheet1" excel_path = "src/simme...
class TestConfig(unittest.TestCase):
def test_create_config_csv(self): try: download_folder("config_test") except: raise DataDownloadException( "Could not download test data for config_test." ) tab = "Sheet1" excel_path = "src/simmer/Examples/PHARO/logsheet.csv" ...
file.close() self.assertFalse(validated) def test_colormap_validator_valid(self): ss = validator.SimmerValidator() file = open("src/simmer/schemas/plotting_schema.yml") parsed_yaml_file = yaml.load(file, Loader=yaml.SafeLoader) document = {"final_im": {"colormap": "viridis"...
206
206
688
7
199
cdressing/SImMER
src/simmer/tests/tests_io.py
Python
TestConfig
TestConfig
143
231
143
143
33adc3dfb7df7e573802f56a74ea7d8bf4def4c7
bigcode/the-stack
train
361c69ac045b02d7afbfdf98
train
class
class UpdateEnvironmentRequest(proto.Message): r"""The request message for [Environments.UpdateEnvironment][google.cloud.dialogflow.v2.Environments.UpdateEnvironment]. Attributes: environment (google.cloud.dialogflow_v2.types.Environment): Required. The environment to update. up...
class UpdateEnvironmentRequest(proto.Message):
r"""The request message for [Environments.UpdateEnvironment][google.cloud.dialogflow.v2.Environments.UpdateEnvironment]. Attributes: environment (google.cloud.dialogflow_v2.types.Environment): Required. The environment to update. update_mask (google.protobuf.field_mask_pb2.Field...
new environment. """ parent = proto.Field( proto.STRING, number=1, ) environment = proto.Field( proto.MESSAGE, number=2, message="Environment", ) environment_id = proto.Field( proto.STRING, number=3, ) class UpdateEnvironm...
71
71
237
7
64
rkdfc93/python-dialogflow
google/cloud/dialogflow_v2/types/environment.py
Python
UpdateEnvironmentRequest
UpdateEnvironmentRequest
310
341
310
310
a55bdfab0ce7cad61ab42981fea0ff9155d7c5dd
bigcode/the-stack
train
4255dbf31191e17a1f35a20f
train
class
class DeleteEnvironmentRequest(proto.Message): r"""The request message for [Environments.DeleteEnvironment][google.cloud.dialogflow.v2.Environments.DeleteEnvironment]. Attributes: name (str): Required. The name of the environment to delete. / Format: - ``projects/<Project ...
class DeleteEnvironmentRequest(proto.Message):
r"""The request message for [Environments.DeleteEnvironment][google.cloud.dialogflow.v2.Environments.DeleteEnvironment]. Attributes: name (str): Required. The name of the environment to delete. / Format: - ``projects/<Project ID>/agent/environments/<Environment ID>`` ...
", ) update_mask = proto.Field( proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, ) allow_load_to_draft_and_discard_changes = proto.Field( proto.BOOL, number=3, ) class DeleteEnvironmentRequest(proto.Message):
64
64
127
7
57
rkdfc93/python-dialogflow
google/cloud/dialogflow_v2/types/environment.py
Python
DeleteEnvironmentRequest
DeleteEnvironmentRequest
344
361
344
344
e3c441064d76812390893429701017e4c5470cc7
bigcode/the-stack
train
dedf664c3dc0e9e4acd9d01c
train
class
class GetEnvironmentRequest(proto.Message): r"""The request message for [Environments.GetEnvironment][google.cloud.dialogflow.v2.Environments.GetEnvironment]. Attributes: name (str): Required. The name of the environment. Supported formats: - ``projects/<Project ID>/agent/...
class GetEnvironmentRequest(proto.Message):
r"""The request message for [Environments.GetEnvironment][google.cloud.dialogflow.v2.Environments.GetEnvironment]. Attributes: name (str): Required. The name of the environment. Supported formats: - ``projects/<Project ID>/agent/environments/<Environment ID>`` ...
@property def raw_page(self): return self environments = proto.RepeatedField( proto.MESSAGE, number=1, message="Environment", ) next_page_token = proto.Field( proto.STRING, number=2, ) class GetEnvironmentRequest(proto.Message):
64
64
125
7
57
rkdfc93/python-dialogflow
google/cloud/dialogflow_v2/types/environment.py
Python
GetEnvironmentRequest
GetEnvironmentRequest
257
274
257
257
02f5aee284249b5d7ae85e3b7bdf4a04d15327c2
bigcode/the-stack
train
2c2642d68ed74e0a4f61f8a2
train
class
class ListEnvironmentsRequest(proto.Message): r"""The request message for [Environments.ListEnvironments][google.cloud.dialogflow.v2.Environments.ListEnvironments]. Attributes: parent (str): Required. The agent to list all environments from. Format: - ``projects/<Project I...
class ListEnvironmentsRequest(proto.Message):
r"""The request message for [Environments.ListEnvironments][google.cloud.dialogflow.v2.Environments.ListEnvironments]. Attributes: parent (str): Required. The agent to list all environments from. Format: - ``projects/<Project ID>/agent`` - ``projects/<Project ...
sample_rate_hertz = proto.Field( proto.INT32, number=3, ) synthesize_speech_configs = proto.MapField( proto.STRING, proto.MESSAGE, number=4, message=audio_config.SynthesizeSpeechConfig, ) class ListEnvironmentsRequest(proto.Message):
64
64
201
8
56
rkdfc93/python-dialogflow
google/cloud/dialogflow_v2/types/environment.py
Python
ListEnvironmentsRequest
ListEnvironmentsRequest
194
224
194
194
2f15e2a745b2abb74b7a5fe669d073a6648251c8
bigcode/the-stack
train
fd9475b44983ce77407d42b7
train
class
class CreateEnvironmentRequest(proto.Message): r"""The request message for [Environments.CreateEnvironment][google.cloud.dialogflow.v2.Environments.CreateEnvironment]. Attributes: parent (str): Required. The agent to create an environment for. Supported formats: ...
class CreateEnvironmentRequest(proto.Message):
r"""The request message for [Environments.CreateEnvironment][google.cloud.dialogflow.v2.Environments.CreateEnvironment]. Attributes: parent (str): Required. The agent to create an environment for. Supported formats: - ``projects/<Project ID>/agent`` ...
>`` - ``projects/<Project ID>/locations/<Location ID>/agent/environments/<Environment ID>`` The environment ID for the default environment is ``-``. """ name = proto.Field( proto.STRING, number=1, ) class CreateEnvironmentRequest(proto.Message):
64
64
184
7
57
rkdfc93/python-dialogflow
google/cloud/dialogflow_v2/types/environment.py
Python
CreateEnvironmentRequest
CreateEnvironmentRequest
277
307
277
277
adf72f3e003e6889b8bbc886fa2a9070702c864b
bigcode/the-stack
train
53b3d2645a7c6400c5a3d954
train
class
class Environment(proto.Message): r"""You can create multiple versions of your agent and publish them to separate environments. When you edit an agent, you are editing the draft agent. At any point, you can save the draft agent as an agent version, which is an immutable snapshot of your agent. ...
class Environment(proto.Message):
r"""You can create multiple versions of your agent and publish them to separate environments. When you edit an agent, you are editing the draft agent. At any point, you can save the draft agent as an agent version, which is an immutable snapshot of your agent. When you save the draft agent, it...
# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing...
231
231
770
5
226
rkdfc93/python-dialogflow
google/cloud/dialogflow_v2/types/environment.py
Python
Environment
Environment
41
142
41
41
4044fe1d13127131a4a742056784ed904174a3f8
bigcode/the-stack
train
2f6e68548bdcc542d7a4535b
train
class
class TextToSpeechSettings(proto.Message): r"""Instructs the speech synthesizer on how to generate the output audio content. Attributes: enable_text_to_speech (bool): Optional. Indicates whether text to speech is enabled. Even when this field is false, other sett...
class TextToSpeechSettings(proto.Message):
r"""Instructs the speech synthesizer on how to generate the output audio content. Attributes: enable_text_to_speech (bool): Optional. Indicates whether text to speech is enabled. Even when this field is false, other settings in this proto are still retained. ...
.Field( proto.ENUM, number=4, enum=State, ) update_time = proto.Field( proto.MESSAGE, number=5, message=timestamp_pb2.Timestamp, ) text_to_speech_settings = proto.Field( proto.MESSAGE, number=7, message="TextToSpeechSettings", )...
110
110
368
8
102
rkdfc93/python-dialogflow
google/cloud/dialogflow_v2/types/environment.py
Python
TextToSpeechSettings
TextToSpeechSettings
145
191
145
145
830a3f1ab15391cfd2d1fd496074a1128b643a0d
bigcode/the-stack
train
947a2c2e78fbe65ddb14bca8
train
class
class GetEnvironmentHistoryRequest(proto.Message): r"""The request message for [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2.Environments.GetEnvironmentHistory]. Attributes: parent (str): Required. The name of the environment to retrieve history for. Suppor...
class GetEnvironmentHistoryRequest(proto.Message):
r"""The request message for [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2.Environments.GetEnvironmentHistory]. Attributes: parent (str): Required. The name of the environment to retrieve history for. Supported formats: - ``projects/<Project ID...
vironments/<Environment ID>`` - ``projects/<Project ID>/locations/<Location ID>/agent/environments/<Environment ID>`` The environment ID for the default environment is ``-``. """ name = proto.Field( proto.STRING, number=1, ) class GetEnvironmentHistoryRequest(proto...
69
69
230
8
61
rkdfc93/python-dialogflow
google/cloud/dialogflow_v2/types/environment.py
Python
GetEnvironmentHistoryRequest
GetEnvironmentHistoryRequest
364
397
364
364
f538a8baaab7f7cfaf65103b057e5c315665d329
bigcode/the-stack
train
3047456262cc5252a79c5b4b
train
class
class ListEnvironmentsResponse(proto.Message): r"""The response message for [Environments.ListEnvironments][google.cloud.dialogflow.v2.Environments.ListEnvironments]. Attributes: environments (Sequence[google.cloud.dialogflow_v2.types.Environment]): The list of agent environments. There...
class ListEnvironmentsResponse(proto.Message):
r"""The response message for [Environments.ListEnvironments][google.cloud.dialogflow.v2.Environments.ListEnvironments]. Attributes: environments (Sequence[google.cloud.dialogflow_v2.types.Environment]): The list of agent environments. There will be a maximum number of items ...
""" parent = proto.Field( proto.STRING, number=1, ) page_size = proto.Field( proto.INT32, number=2, ) page_token = proto.Field( proto.STRING, number=3, ) class ListEnvironmentsResponse(proto.Message):
64
64
174
8
56
rkdfc93/python-dialogflow
google/cloud/dialogflow_v2/types/environment.py
Python
ListEnvironmentsResponse
ListEnvironmentsResponse
227
254
227
227
fde52674f62cac7724dc4e2342d0d6ddf9ce25f5
bigcode/the-stack
train
8fef206ebc71c613dc40097f
train
class
class EnvironmentHistory(proto.Message): r"""The response message for [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2.Environments.GetEnvironmentHistory]. Attributes: parent (str): Output only. The name of the environment this history is for. Supported format...
class EnvironmentHistory(proto.Message):
r"""The response message for [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2.Environments.GetEnvironmentHistory]. Attributes: parent (str): Output only. The name of the environment this history is for. Supported formats: - ``projects/<Project ID...
``-``. page_size (int): Optional. The maximum number of items to return in a single page. By default 100 and at most 1000. page_token (str): Optional. The next_page_token value returned from a previous list request. """ parent = proto...
125
125
418
6
119
rkdfc93/python-dialogflow
google/cloud/dialogflow_v2/types/environment.py
Python
EnvironmentHistory
EnvironmentHistory
400
468
400
400
cfb3fa93fcb21f2d643451804d1aa4457b66ac77
bigcode/the-stack
train
ac65e087bbe5b4bfeca1103b
train
function
def test_t1w(): # create config real_bids_dir = "snakebids/tests/data/bids_t1w" derivatives = False pybids_inputs = { "t1": { "filters": {"suffix": "T1w"}, "wildcards": ["acquisition", "subject", "session", "run"], } } # Can't define particpant_label and ...
def test_t1w(): # create config
real_bids_dir = "snakebids/tests/data/bids_t1w" derivatives = False pybids_inputs = { "t1": { "filters": {"suffix": "T1w"}, "wildcards": ["acquisition", "subject", "session", "run"], } } # Can't define particpant_label and exclude_participant_label with p...
import os from bids import BIDSLayout import pytest from .. import generate_inputs, __get_lists_from_bids def test_t1w(): # create config
37
256
1,244
11
25
akhanf/snakebids
snakebids/tests/test_generate_inputs.py
Python
test_t1w
test_t1w
9
145
9
10
4e8b5b5d1f3cfc99126d136189fc86567c10e58d
bigcode/the-stack
train
6ad7da688a6429e6d622f3d0
train
function
def test_get_lists_from_bids(): bids_dir = "snakebids/tests/data/bids_t1w" wildcard_path_t1 = os.path.join( os.path.dirname(os.path.abspath(__file__)), "data/bids_t1w", "sub-{subject}/anat/sub-{subject}_acq-{acq}_T1w.nii.gz", ) wildcard_path_t2 = os.path.join( os.path.dir...
def test_get_lists_from_bids():
bids_dir = "snakebids/tests/data/bids_t1w" wildcard_path_t1 = os.path.join( os.path.dirname(os.path.abspath(__file__)), "data/bids_t1w", "sub-{subject}/anat/sub-{subject}_acq-{acq}_T1w.nii.gz", ) wildcard_path_t2 = os.path.join( os.path.dirname(os.path.abspath(__file__)),...
{"acq": ["mprage", "mprage"], "subject": ["001", "002"]}, {"acq": ["mprage", "mprage"], "subject": ["002", "001"]}, ] assert config["input_zip_lists"]["t2"] == {"subject": ["002"]} assert config["input_wildcards"] == { "t1": {"acq": "{acq}", "subject": "{subje...
180
180
601
8
172
akhanf/snakebids
snakebids/tests/test_generate_inputs.py
Python
test_get_lists_from_bids
test_get_lists_from_bids
148
205
148
148
b5ec065a13d03d959b106d1e1502ce91b2e0fbce
bigcode/the-stack
train
0d5c7c8993c08557e127b785
train
class
class WwtCorpus: def __init__(self, corpus_path: str, article_path: str): self.corpus_path = corpus_path self.article_path = article_path self._num_lines = count_file_lines(article_path) - 1 def __iter__(self) -> Iterator[Dict]: with open(self.corpus_path, "r") as fp: ...
class WwtCorpus:
def __init__(self, corpus_path: str, article_path: str): self.corpus_path = corpus_path self.article_path = article_path self._num_lines = count_file_lines(article_path) - 1 def __iter__(self) -> Iterator[Dict]: with open(self.corpus_path, "r") as fp: for line in tqd...
= os.path.join(output_path, "df_articles.csv") df_articles.to_csv(file_name, index=False) file_name = os.path.join(output_path, "xcv.npz") scipy.sparse.save_npz(file_name, xcv) file_name = os.path.join(output_path, "xbm25.npz") scipy.sparse.save_npz(file_name, xbm25) class WwtCorpus:
88
88
295
5
83
kensho-technologies/wikiwhatsthis
package/wikiwhatsthis/task_15_train_models.py
Python
WwtCorpus
WwtCorpus
65
102
65
65
a88c9c696b25ebc7845238525779d70842b3019a
bigcode/the-stack
train
131bdfcf4911eed0b9939c89
train
function
def count_file_lines(file_path: str) -> int: output = subprocess.check_output(["wc", "-l", file_path]) num_lines = int(output.split()[0]) return num_lines
def count_file_lines(file_path: str) -> int:
output = subprocess.check_output(["wc", "-l", file_path]) num_lines = int(output.split()[0]) return num_lines
ballStemmer from wikiwhatsthis import argconfig import warnings warnings.filterwarnings( "ignore", category=UserWarning, message="Your stop_words may be inconsistent with your preprocessing.", ) logger = logging.getLogger(__name__) def count_file_lines(file_path: str) -> int:
64
64
42
12
52
kensho-technologies/wikiwhatsthis
package/wikiwhatsthis/task_15_train_models.py
Python
count_file_lines
count_file_lines
31
34
31
31
c511612bc267ff9ac6ba1c2b3835393999db5fd8
bigcode/the-stack
train
e203702ec49a109cb4a87d0d
train
function
def main( wp_yyyymmdd: str, data_path: str = argconfig.DEFAULT_KWNLP_DATA_PATH, ) -> None: output_path = os.path.join("/data/wiki-whats-this", wp_yyyymmdd) stemmer = SnowballStemmer("english") stop_words = frozenset( [stemmer.stem(token) for token in json.load(open("english_stop_words.json...
def main( wp_yyyymmdd: str, data_path: str = argconfig.DEFAULT_KWNLP_DATA_PATH, ) -> None:
output_path = os.path.join("/data/wiki-whats-this", wp_yyyymmdd) stemmer = SnowballStemmer("english") stop_words = frozenset( [stemmer.stem(token) for token in json.load(open("english_stop_words.json", "r"))] ) corpora_names = [ "feat", "good", "mini", "smal...
paragraph": for page in self: if page["paragraphs"]: yield page["paragraphs"][0]["plaintext_snowball"] else: yield "" elif scope == "intro": for page in self: if page["paragraphs"]: ...
202
203
677
31
172
kensho-technologies/wikiwhatsthis
package/wikiwhatsthis/task_15_train_models.py
Python
main
main
105
196
105
109
3b28c73b6409d3ab7df42312a4e3fc5b29edd11f
bigcode/the-stack
train
88195dbc8fc3122f760754cf
train
function
def dump( wwt_config: Dict, cv: CountVectorizer, df_articles: pd.DataFrame, xcv: scipy.sparse.csr_matrix, xbm25: scipy.sparse.csr_matrix, output_path: str = "", ) -> None: os.makedirs(output_path, exist_ok=True) file_name = os.path.join(output_path, "wwt_config.json") with open(file...
def dump( wwt_config: Dict, cv: CountVectorizer, df_articles: pd.DataFrame, xcv: scipy.sparse.csr_matrix, xbm25: scipy.sparse.csr_matrix, output_path: str = "", ) -> None:
os.makedirs(output_path, exist_ok=True) file_name = os.path.join(output_path, "wwt_config.json") with open(file_name, "w") as fp: json.dump(wwt_config, fp, indent=4) cv.stop_words_ = set() file_name = os.path.join(output_path, "cv.joblib") joblib.dump(cv, file_name) file_name = os...
.split()[0]) return num_lines def dump( wwt_config: Dict, cv: CountVectorizer, df_articles: pd.DataFrame, xcv: scipy.sparse.csr_matrix, xbm25: scipy.sparse.csr_matrix, output_path: str = "", ) -> None:
68
68
229
59
8
kensho-technologies/wikiwhatsthis
package/wikiwhatsthis/task_15_train_models.py
Python
dump
dump
37
62
37
44
d33593e16918b507d8f8e363fa461aa7a3c2a73b
bigcode/the-stack
train
506758ef46da31ec93f06d13
train
function
def _port(): port = os.environ.get("SDK_SPEAK_PORT", None) if port is None: raise RuntimeError( "CTOAI_PYSDK-8080: The CTO.ai Ops SDK requires a daemon process to be running; this does not appear to be the case." ) return port
def _port():
port = os.environ.get("SDK_SPEAK_PORT", None) if port is None: raise RuntimeError( "CTOAI_PYSDK-8080: The CTO.ai Ops SDK requires a daemon process to be running; this does not appear to be the case." ) return port
import requests import os import json def _port():
13
64
70
4
8
cto-ai/sdk-python
cto_ai/daemon_request.py
Python
_port
_port
6
12
6
6
e31a43559d24e51224836bb3366ce588e6f55516
bigcode/the-stack
train
b70aa9889f40afb556817183
train
function
def _make_sync_requester(endpoint, method='POST'): """Wrapper for sync requests to daemon. Parameters ---------- endpoint : str daemon endpoint to call method : str, optional method to call daemon with, (default POST) Raises ------ HTTPError if error calling the...
def _make_sync_requester(endpoint, method='POST'):
"""Wrapper for sync requests to daemon. Parameters ---------- endpoint : str daemon endpoint to call method : str, optional method to call daemon with, (default POST) Raises ------ HTTPError if error calling the daemon occurs """ def requester(body): ...
= _make_requester("progress-bar/stop") track = _make_requester("track") start_op = _make_requester("track") set_state = _make_requester("state/set") set_config = _make_requester("config/set") def _make_sync_requester(endpoint, method='POST'):
64
64
166
12
52
cto-ai/sdk-python
cto_ai/daemon_request.py
Python
_make_sync_requester
_make_sync_requester
33
59
33
33
be9c83c41422059c87890d6acc0a7c30b6291b89
bigcode/the-stack
train
9de5224097e9610af65d3fbc
train
function
def _make_async_requester(endpoint): def requester(body): response = requests.post(f"http://127.0.0.1:{_port()}/{endpoint}", json=body) response.raise_for_status() response_data = response.json() with open(response_data["replyFilename"]) as infile: return json.load(infi...
def _make_async_requester(endpoint):
def requester(body): response = requests.post(f"http://127.0.0.1:{_port()}/{endpoint}", json=body) response.raise_for_status() response_data = response.json() with open(response_data["replyFilename"]) as infile: return json.load(infile) return requester
er("config/get-all") delete_config = _make_sync_requester("config/delete") events = _make_sync_requester("events") get_user = _make_sync_requester("user", 'GET') get_team = _make_sync_requester("team", 'GET') def _make_async_requester(endpoint):
64
64
75
8
56
cto-ai/sdk-python
cto_ai/daemon_request.py
Python
_make_async_requester
_make_async_requester
72
82
72
72
4693a5cca4789fc7a646f3952cd7c7e4af9f1097
bigcode/the-stack
train
d3d370074d8dc7ebc537f560
train
function
def _make_requester(endpoint): return lambda data: requests.post( f"http://127.0.0.1:{_port()}/{endpoint}", json=data ).raise_for_status()
def _make_requester(endpoint):
return lambda data: requests.post( f"http://127.0.0.1:{_port()}/{endpoint}", json=data ).raise_for_status()
PEAK_PORT", None) if port is None: raise RuntimeError( "CTOAI_PYSDK-8080: The CTO.ai Ops SDK requires a daemon process to be running; this does not appear to be the case." ) return port def _make_requester(endpoint):
64
64
42
7
56
cto-ai/sdk-python
cto_ai/daemon_request.py
Python
_make_requester
_make_requester
15
18
15
15
de7299cb2300fd615c5200174623737c8449c4c6
bigcode/the-stack
train
530d2de4d342add41ff4da76
train
function
def suite(): s = DocutilsTestSupport.ParserTestSuite() s.generateTests(totest) return s
def suite():
s = DocutilsTestSupport.ParserTestSuite() s.generateTests(totest) return s
2016-07-28 21:56:00Z milde $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for images.py figure directives. """ from __init__ import DocutilsTestSupport def suite():
64
64
26
3
60
kokosing/hue
desktop/core/ext-py/docutils-0.14/test/test_parsers/test_rst/test_directives/test_figures.py
Python
suite
suite
13
16
13
13
d037c224ee684e170ade234b69b606c471063639
bigcode/the-stack
train
b8278c22779ad9dcb4f1cfdb
train
class
class _Annotation(object): def __init__(self, name, value, keep): self.name = name self.value = value self.keep = keep
class _Annotation(object):
def __init__(self, name, value, keep): self.name = name self.value = value self.keep = keep
') self.untracked = self.printer('untracked', fg='red') class DiffColoring(Coloring): def __init__(self, config): Coloring.__init__(self, config, 'diff') self.project = self.printer('header', attr='bold') class _Annotation(object):
64
64
36
5
59
yuyiyu2017/repo
project.py
Python
_Annotation
_Annotation
231
236
231
232
8c1ee52cbc1362b9964a05e1057828c4f4081a74
bigcode/the-stack
train
40834db4efb48522a20aa1a3
train
class
class _DirtyError(Exception): def __str__(self): return 'contains uncommitted changes'
class _DirtyError(Exception):
def __str__(self): return 'contains uncommitted changes'
n') and r.index('\n') == len(r) - 1: return r[:-1] return r return runner class _PriorSyncFailedError(Exception): def __str__(self): return 'prior sync failed; rebase still in progress' class _DirtyError(Exception):
64
64
22
6
58
yuyiyu2017/repo
project.py
Python
_DirtyError
_DirtyError
2,883
2,886
2,883
2,884
ad2ec5ac2ede4bf5c6689dfe5d1ee0131537a498
bigcode/the-stack
train
0b87d235fdfe4da69549f74d
train
class
class StatusColoring(Coloring): def __init__(self, config): Coloring.__init__(self, config, 'status') self.project = self.printer('header', attr='bold') self.branch = self.printer('header', attr='bold') self.nobranch = self.printer('nobranch', fg='red') self.important = self.printer('important', ...
class StatusColoring(Coloring):
def __init__(self, config): Coloring.__init__(self, config, 'status') self.project = self.printer('header', attr='bold') self.branch = self.printer('header', attr='bold') self.nobranch = self.printer('nobranch', fg='red') self.important = self.printer('important', fg='red') self.added = self....
shReviewUrl(self.project.UserEmail), 'refs/changes/*') for line in output.split('\n'): try: (sha, ref) = line.split() refs[sha] = ref except ValueError: pass return refs class StatusColoring(Coloring):
64
64
134
7
56
yuyiyu2017/repo
project.py
Python
StatusColoring
StatusColoring
210
221
210
211
8b732bad8f446058e41adb44f6c861c6e23c7030
bigcode/the-stack
train
783e721849f44149c77b0d3b
train
class
class DownloadedChange(object): _commit_cache = None def __init__(self, project, base, change_id, ps_id, commit): self.project = project self.base = base self.change_id = change_id self.ps_id = ps_id self.commit = commit @property def commits(self): if self._commit_cache is None: ...
class DownloadedChange(object):
_commit_cache = None def __init__(self, project, base, change_id, ps_id, commit): self.project = project self.base = base self.change_id = change_id self.ps_id = ps_id self.commit = commit @property def commits(self): if self._commit_cache is None: self._commit_cache = self.proje...
: d = platform_utils.realpath(os.path.abspath(os.path.dirname(__file__))) d = os.path.join(d, 'hooks') _project_hook_list = [os.path.join(d, x) for x in platform_utils.listdir(d)] return _project_hook_list class DownloadedChange(object):
64
64
146
6
57
yuyiyu2017/repo
project.py
Python
DownloadedChange
DownloadedChange
110
131
110
110
40323d935eae375865906bd57e2cfd87a0c16dfe
bigcode/the-stack
train
f2c7064b31d844ad79742a15
train
function
def _error(fmt, *args): msg = fmt % args print('error: %s' % msg, file=sys.stderr)
def _error(fmt, *args):
msg = fmt % args print('error: %s' % msg, file=sys.stderr)
'%s.lock' % path fd = open(lock, 'w') try: fd.write(content) finally: fd.close() try: platform_utils.rename(lock, path) except OSError: platform_utils.remove(lock) raise def _error(fmt, *args):
64
64
30
8
55
yuyiyu2017/repo
project.py
Python
_error
_error
70
72
70
70
4e3657dc7aa06e0736f9d013075ad375eaf72310
bigcode/the-stack
train
6fe79616d462489f72f2b2e7
train
class
class MetaProject(Project): """A special project housed under .repo. """ def __init__(self, manifest, name, gitdir, worktree): Project.__init__(self, manifest=manifest, name=name, gitdir=gitdir, objdir=gitdir, ...
class MetaProject(Project):
"""A special project housed under .repo. """ def __init__(self, manifest, name, gitdir, worktree): Project.__init__(self, manifest=manifest, name=name, gitdir=gitdir, objdir=gitdir, worktree=worktree, ...
def _RunLater(self): for q in ['_later_queue1', '_later_queue2']: if not self._RunQueue(q): return def _RunQueue(self, queue): for m in getattr(self, queue): if not m.Run(self): self._MarkUnclean() return False setattr(self, queue, []) return True def _Print...
134
135
450
5
129
yuyiyu2017/repo
project.py
Python
MetaProject
MetaProject
3,007
3,077
3,007
3,008
a204d8bd2b29c43a3e773e52751a9164a59d52b4
bigcode/the-stack
train
3aaacf3c905b8930c509a824
train
function
def _warn(fmt, *args): msg = fmt % args print('warn: %s' % msg, file=sys.stderr)
def _warn(fmt, *args):
msg = fmt % args print('warn: %s' % msg, file=sys.stderr)
() try: platform_utils.rename(lock, path) except OSError: platform_utils.remove(lock) raise def _error(fmt, *args): msg = fmt % args print('error: %s' % msg, file=sys.stderr) def _warn(fmt, *args):
64
64
30
8
56
yuyiyu2017/repo
project.py
Python
_warn
_warn
75
77
75
75
90d412a9b16d74441dcebc8b42af82fc2a51a681
bigcode/the-stack
train
9af7eeeb89c888787eabdfc3
train
class
class ReviewableBranch(object): _commit_cache = None def __init__(self, project, branch, base): self.project = project self.branch = branch self.base = base @property def name(self): return self.branch.name @property def commits(self): if self._commit_cache is None: self._commit...
class ReviewableBranch(object):
_commit_cache = None def __init__(self, project, branch, base): self.project = project self.branch = branch self.base = base @property def name(self): return self.branch.name @property def commits(self): if self._commit_cache is None: self._commit_cache = self.project.bare_git.r...
, base, change_id, ps_id, commit): self.project = project self.base = base self.change_id = change_id self.ps_id = ps_id self.commit = commit @property def commits(self): if self._commit_cache is None: self._commit_cache = self.project.bare_git.rev_list('--abbrev=8', ...
131
131
439
6
124
yuyiyu2017/repo
project.py
Python
ReviewableBranch
ReviewableBranch
134
207
134
134
d27ca139fe8f0d2cb1100506837eb33fc86c75a5
bigcode/the-stack
train
db95dacf58a7ccfb91f747da
train
class
class _Later(object): def __init__(self, project, action): self.project = project self.action = action def Run(self, syncbuf): out = syncbuf.out out.project('project %s/', self.project.relpath) out.nl() try: self.action() out.nl() return True except GitError: ou...
class _Later(object):
def __init__(self, project, action): self.project = project self.action = action def Run(self, syncbuf): out = syncbuf.out out.project('project %s/', self.project.relpath) out.nl() try: self.action() out.nl() return True except GitError: out.nl() return Fal...
self, project, why): self.project = project self.why = why def Print(self, syncbuf): syncbuf.out.fail('error: %s/: %s', self.project.relpath, str(self.why)) syncbuf.out.nl() class _Later(object):
64
64
88
5
59
yuyiyu2017/repo
project.py
Python
_Later
_Later
2,913
2,929
2,913
2,914
50a20b0e22cc4b6bf8c8c312a9359cc1c9e990a8
bigcode/the-stack
train
59aa32155427a1a7b6bae3ad
train
class
class RepoHook(object): """A RepoHook contains information about a script to run as a hook. Hooks are used to run a python script before running an upload (for instance, to run presubmit checks). Eventually, we may have hooks for other actions. This shouldn't be confused with files in the 'repo/hooks' direc...
class RepoHook(object):
"""A RepoHook contains information about a script to run as a hook. Hooks are used to run a python script before running an upload (for instance, to run presubmit checks). Eventually, we may have hooks for other actions. This shouldn't be confused with files in the 'repo/hooks' directory. Those files are ...
DestDir) else: absSrcFiles = glob.glob(absSrc) for absSrcFile in absSrcFiles: # Create a releative path from source dir to destination dir absSrcDir = os.path.dirname(absSrcFile) relSrcDir = os.path.relpath(absSrcDir, absDestDir) # Get the source file name ...
256
256
2,688
5
250
yuyiyu2017/repo
project.py
Python
RepoHook
RepoHook
346
638
346
347
01493820fa7def7c5b974e1021af30a1e94aa57c
bigcode/the-stack
train
59cc06da17cf654eae2f568a
train
function
def _lwrite(path, content): lock = '%s.lock' % path fd = open(lock, 'w') try: fd.write(content) finally: fd.close() try: platform_utils.rename(lock, path) except OSError: platform_utils.remove(lock) raise
def _lwrite(path, content):
lock = '%s.lock' % path fd = open(lock, 'w') try: fd.write(content) finally: fd.close() try: platform_utils.rename(lock, path) except OSError: platform_utils.remove(lock) raise
UB, R_M from pyversion import is_python3 if is_python3(): import urllib.parse else: import imp import urlparse urllib = imp.new_module('urllib') urllib.parse = urlparse input = raw_input def _lwrite(path, content):
64
64
67
8
55
yuyiyu2017/repo
project.py
Python
_lwrite
_lwrite
54
67
54
54
37fb97528405840a6c0e950fe3087708100a24e6
bigcode/the-stack
train
5e09314d114e6f944ec6a988
train
function
def _ProjectHooks(): """List the hooks present in the 'hooks' directory. These hooks are project hooks and are copied to the '.git/hooks' directory of all subprojects. This function caches the list of hooks (based on the contents of the 'repo/hooks' directory) on the first call. Returns: A list of ab...
def _ProjectHooks():
"""List the hooks present in the 'hooks' directory. These hooks are project hooks and are copied to the '.git/hooks' directory of all subprojects. This function caches the list of hooks (based on the contents of the 'repo/hooks' directory) on the first call. Returns: A list of absolute paths to all o...
msg = fmt % args print('warn: %s' % msg, file=sys.stderr) def not_rev(r): return '^' + r def sq(r): return "'" + r.replace("'", "'\''") + "'" _project_hook_list = None def _ProjectHooks():
64
64
163
5
58
yuyiyu2017/repo
project.py
Python
_ProjectHooks
_ProjectHooks
90
107
90
90
778e5dad6cc23c2b34dab9863ac716825ebcb9ce
bigcode/the-stack
train
46c58bd9081df9b7c3a642b6
train
class
class RemoteSpec(object): def __init__(self, name, url=None, pushUrl=None, review=None, revision=None, orig_name=None, fetchUrl=None): self.name = name self.url = url self.pushUrl = pushUrl self.r...
class RemoteSpec(object):
def __init__(self, name, url=None, pushUrl=None, review=None, revision=None, orig_name=None, fetchUrl=None): self.name = name self.url = url self.pushUrl = pushUrl self.review = review self.rev...
will be # absolute for the desintaiton and relative for the srouce. absDest = os.path.join(absDestDir, srcFile) relSrc = os.path.join(relSrcDir, srcFile) self.__linkIt(relSrc, absDest) class RemoteSpec(object):
64
64
91
5
59
yuyiyu2017/repo
project.py
Python
RemoteSpec
RemoteSpec
327
343
327
328
a0e77a44e76d5f7f87d9181d42f1f5f07a47e670
bigcode/the-stack
train
544b43268e832cd781442695
train
class
class _LinkFile(object): def __init__(self, git_worktree, src, dest, relsrc, absdest): self.git_worktree = git_worktree self.src = src self.dest = dest self.src_rel_to_dest = relsrc self.abs_dest = absdest def __linkIt(self, relSrc, absDest): # link file if it does not exist or is out of d...
class _LinkFile(object):
def __init__(self, git_worktree, src, dest, relsrc, absdest): self.git_worktree = git_worktree self.src = src self.dest = dest self.src_rel_to_dest = relsrc self.abs_dest = absdest def __linkIt(self, relSrc, absDest): # link file if it does not exist or is out of date if not platform_ut...
or is out of date if not os.path.exists(dest) or not filecmp.cmp(src, dest): try: # remove existing file first, since it might be read-only if os.path.exists(dest): platform_utils.remove(dest) else: dest_dir = os.path.dirname(dest) if not platform_utils.i...
167
167
559
6
161
yuyiyu2017/repo
project.py
Python
_LinkFile
_LinkFile
269
324
269
270
8e9ee8609519d6de92ce392a24521c1b62532a4b
bigcode/the-stack
train
9fd5a8b67d946f4a60beccec
train
class
class _PriorSyncFailedError(Exception): def __str__(self): return 'prior sync failed; rebase still in progress'
class _PriorSyncFailedError(Exception):
def __str__(self): return 'prior sync failed; rebase still in progress'
try: r = r.decode('utf-8') except AttributeError: pass if r.endswith('\n') and r.index('\n') == len(r) - 1: return r[:-1] return r return runner class _PriorSyncFailedError(Exception):
64
64
28
8
55
yuyiyu2017/repo
project.py
Python
_PriorSyncFailedError
_PriorSyncFailedError
2,877
2,880
2,877
2,878
b66550e2344f2ca13e85c36870028f0714cfbc56
bigcode/the-stack
train
d700073c6c4e7aae7805172c
train
class
class _SyncColoring(Coloring): def __init__(self, config): Coloring.__init__(self, config, 'reposync') self.project = self.printer('header', attr='bold') self.info = self.printer('info') self.fail = self.printer('fail', fg='red')
class _SyncColoring(Coloring):
def __init__(self, config): Coloring.__init__(self, config, 'reposync') self.project = self.printer('header', attr='bold') self.info = self.printer('info') self.fail = self.printer('fail', fg='red')
, syncbuf): out = syncbuf.out out.project('project %s/', self.project.relpath) out.nl() try: self.action() out.nl() return True except GitError: out.nl() return False class _SyncColoring(Coloring):
64
64
68
8
55
yuyiyu2017/repo
project.py
Python
_SyncColoring
_SyncColoring
2,932
2,938
2,932
2,933
6ad740a6087003a2f283fea0e45a5bf03a0e59ea
bigcode/the-stack
train
fa0435cf2f8325d9740393de
train
class
class SyncBuffer(object): def __init__(self, config, detach_head=False): self._messages = [] self._failures = [] self._later_queue1 = [] self._later_queue2 = [] self.out = _SyncColoring(config) self.out.redirect(sys.stderr) self.detach_head = detach_head self.clean = True self.r...
class SyncBuffer(object):
def __init__(self, config, detach_head=False): self._messages = [] self._failures = [] self._later_queue1 = [] self._later_queue2 = [] self.out = _SyncColoring(config) self.out.redirect(sys.stderr) self.detach_head = detach_head self.clean = True self.recent_clean = True def i...
out.project('project %s/', self.project.relpath) out.nl() try: self.action() out.nl() return True except GitError: out.nl() return False class _SyncColoring(Coloring): def __init__(self, config): Coloring.__init__(self, config, 'reposync') self.project = self.prin...
117
117
392
5
112
yuyiyu2017/repo
project.py
Python
SyncBuffer
SyncBuffer
2,941
3,004
2,941
2,942
d2c1dd1cb54839ce97da35d3dc7e73e68b9b4dc4
bigcode/the-stack
train
7e20a65060a7ef36894591fc
train
class
class _Failure(object): def __init__(self, project, why): self.project = project self.why = why def Print(self, syncbuf): syncbuf.out.fail('error: %s/: %s', self.project.relpath, str(self.why)) syncbuf.out.nl()
class _Failure(object):
def __init__(self, project, why): self.project = project self.why = why def Print(self, syncbuf): syncbuf.out.fail('error: %s/: %s', self.project.relpath, str(self.why)) syncbuf.out.nl()
Message(object): def __init__(self, project, text): self.project = project self.text = text def Print(self, syncbuf): syncbuf.out.info('%s/: %s', self.project.relpath, self.text) syncbuf.out.nl() class _Failure(object):
64
64
69
5
59
yuyiyu2017/repo
project.py
Python
_Failure
_Failure
2,900
2,910
2,900
2,901
fe7210b94ea41008275e04fb148f8cfb8233d5e0
bigcode/the-stack
train
3ed508795d1a25b3b9ea1a10
train
function
def not_rev(r): return '^' + r
def not_rev(r):
return '^' + r
_error(fmt, *args): msg = fmt % args print('error: %s' % msg, file=sys.stderr) def _warn(fmt, *args): msg = fmt % args print('warn: %s' % msg, file=sys.stderr) def not_rev(r):
64
64
12
5
59
yuyiyu2017/repo
project.py
Python
not_rev
not_rev
80
81
80
80
9677c72ddd76decf32cd5c7eaa90ea1ef61ad64c
bigcode/the-stack
train
abfd2cc6cc8eeee4a3e3f3ce
train
class
class DiffColoring(Coloring): def __init__(self, config): Coloring.__init__(self, config, 'diff') self.project = self.printer('header', attr='bold')
class DiffColoring(Coloring):
def __init__(self, config): Coloring.__init__(self, config, 'diff') self.project = self.printer('header', attr='bold')
important = self.printer('important', fg='red') self.added = self.printer('added', fg='green') self.changed = self.printer('changed', fg='red') self.untracked = self.printer('untracked', fg='red') class DiffColoring(Coloring):
64
64
42
7
57
yuyiyu2017/repo
project.py
Python
DiffColoring
DiffColoring
224
228
224
225
42e978d811385d8f348ca36a294e226880f79c58
bigcode/the-stack
train
7fd8cb7e682e644091aa575f
train
class
class _CopyFile(object): def __init__(self, src, dest, abssrc, absdest): self.src = src self.dest = dest self.abs_src = abssrc self.abs_dest = absdest def _Copy(self): src = self.abs_src dest = self.abs_dest # copy file if it does not exist or is out of date if not os.path.exists(d...
class _CopyFile(object):
def __init__(self, src, dest, abssrc, absdest): self.src = src self.dest = dest self.abs_src = abssrc self.abs_dest = absdest def _Copy(self): src = self.abs_src dest = self.abs_dest # copy file if it does not exist or is out of date if not os.path.exists(dest) or not filecmp.cmp(sr...
self, config): Coloring.__init__(self, config, 'diff') self.project = self.printer('header', attr='bold') class _Annotation(object): def __init__(self, name, value, keep): self.name = name self.value = value self.keep = keep class _CopyFile(object):
72
72
243
6
65
yuyiyu2017/repo
project.py
Python
_CopyFile
_CopyFile
239
266
239
240
cadab82423c7e90cb23856773981e15a94522bfa
bigcode/the-stack
train
a12a870ddadb882187ef21e2
train
function
def sq(r): return "'" + r.replace("'", "'\''") + "'"
def sq(r):
return "'" + r.replace("'", "'\''") + "'"
% args print('error: %s' % msg, file=sys.stderr) def _warn(fmt, *args): msg = fmt % args print('warn: %s' % msg, file=sys.stderr) def not_rev(r): return '^' + r def sq(r):
64
64
19
4
59
yuyiyu2017/repo
project.py
Python
sq
sq
84
85
84
84
ae2db2804b3d247ee6c8e89fe38e8e29aca86a06
bigcode/the-stack
train
be912f9d55e8a7f045ab5e8e
train
class
class Project(object): # These objects can be shared between several working trees. shareable_files = ['description', 'info'] shareable_dirs = ['hooks', 'objects', 'rr-cache', 'svn'] # These objects can only be used by a single working tree. working_tree_files = ['config', 'packed-refs', 'shallow'] working_...
class Project(object): # These objects can be shared between several working trees.
shareable_files = ['description', 'info'] shareable_dirs = ['hooks', 'objects', 'rr-cache', 'svn'] # These objects can only be used by a single working tree. working_tree_files = ['config', 'packed-refs', 'shallow'] working_tree_dirs = ['logs', 'refs'] def __init__(self, manifest, ...
hook--we'll just assume it's OK to run it. kwargs: Keyword arguments to pass to the hook. These are often specific to the hook type. For instance, pre-upload hooks will contain a project_list. Raises: HookError: If there was a problem finding the hook or the user decline...
256
256
16,688
16
240
yuyiyu2017/repo
project.py
Python
Project
Project
641
2,874
641
642
35d188cb37bf9c62ea8763651528f05e4116fbbf
bigcode/the-stack
train
f077a128e2dfe41300ef1c46
train
class
class _InfoMessage(object): def __init__(self, project, text): self.project = project self.text = text def Print(self, syncbuf): syncbuf.out.info('%s/: %s', self.project.relpath, self.text) syncbuf.out.nl()
class _InfoMessage(object):
def __init__(self, project, text): self.project = project self.text = text def Print(self, syncbuf): syncbuf.out.info('%s/: %s', self.project.relpath, self.text) syncbuf.out.nl()
return r return runner class _PriorSyncFailedError(Exception): def __str__(self): return 'prior sync failed; rebase still in progress' class _DirtyError(Exception): def __str__(self): return 'contains uncommitted changes' class _InfoMessage(object):
64
64
62
6
58
yuyiyu2017/repo
project.py
Python
_InfoMessage
_InfoMessage
2,889
2,897
2,889
2,890
644b23181deaaf920e0ef5fbcd3acaee65bcaee5
bigcode/the-stack
train
42dd220af872243c0df1eb93
train
class
class RLSVIAgent(AgentWithSimplePolicy): """ RLSVI algorithm from [1,2] with Gaussian noise. Notes ----- The recommended policy after all the episodes is computed with the empirical MDP. The std of the noise is of the form: scale/sqrt(n)+ V_max/n as for simplified Bernstein bonuses....
class RLSVIAgent(AgentWithSimplePolicy):
""" RLSVI algorithm from [1,2] with Gaussian noise. Notes ----- The recommended policy after all the episodes is computed with the empirical MDP. The std of the noise is of the form: scale/sqrt(n)+ V_max/n as for simplified Bernstein bonuses. Parameters ---------- env :...
import logging import numpy as np import gym.spaces as spaces from rlberry.agents import AgentWithSimplePolicy from rlberry.exploration_tools.discrete_counter import DiscreteCounter from rlberry.agents.dynprog.utils import ( backward_induction_in_place, backward_induction_reward_sd, backward_induction_sd, ...
93
256
1,957
12
81
akrouriad/rlberry
rlberry/agents/rlsvi/rlsvi.py
Python
RLSVIAgent
RLSVIAgent
16
267
16
16
162d82ba37b591818c1df902ae6de08dc7f63bbc
bigcode/the-stack
train
06722b7d45f7b52c4e6c01a6
train
function
def non_verbose_warning_formatter(message, category, filename, lineno, line=None): if issubclass(category, UserWarning): return str(message) + "\n" else: return default_warning_formatter(message, category, filename, lineno, line)
def non_verbose_warning_formatter(message, category, filename, lineno, line=None):
if issubclass(category, UserWarning): return str(message) + "\n" else: return default_warning_formatter(message, category, filename, lineno, line)
if type == BadlyFormedJSONError: sys.stderr.write("JSON error: {}\n".format(value)) else: sys.stderr.write(str(value) + "\n") default_warning_formatter = warnings.formatwarning def non_verbose_warning_formatter(message, category, filename, lineno, line=None):
64
64
55
17
46
Xtuden-com/flatten-tool
flattentool/cli.py
Python
non_verbose_warning_formatter
non_verbose_warning_formatter
313
317
313
313
d162744d32af23220f11725bc66368a4ae601d15
bigcode/the-stack
train
79df1210ed3e55c1bbcfd8f5
train
function
def non_verbose_error_handler(type, value, traceback): if type == BadlyFormedJSONError: sys.stderr.write("JSON error: {}\n".format(value)) else: sys.stderr.write(str(value) + "\n")
def non_verbose_error_handler(type, value, traceback):
if type == BadlyFormedJSONError: sys.stderr.write("JSON error: {}\n".format(value)) else: sys.stderr.write(str(value) + "\n")
kwargs_from_parsed_args(args): """ Transforms argparse's parsed args object into a dictionary to be passed as kwargs. """ return {k: v for k, v in vars(args).items() if v is not None} def non_verbose_error_handler(type, value, traceback):
64
64
50
11
53
Xtuden-com/flatten-tool
flattentool/cli.py
Python
non_verbose_error_handler
non_verbose_error_handler
303
307
303
303
a3525a27acbf50cdc3d5a6089f5179a53922ce60
bigcode/the-stack
train
6b5a14b17a8ae9fd1f252c26
train
function
def kwargs_from_parsed_args(args): """ Transforms argparse's parsed args object into a dictionary to be passed as kwargs. """ return {k: v for k, v in vars(args).items() if v is not None}
def kwargs_from_parsed_args(args):
""" Transforms argparse's parsed args object into a dictionary to be passed as kwargs. """ return {k: v for k, v in vars(args).items() if v is not None}
help="Disable local refs when parsing JSON Schema.", ) parser_unflatten.add_argument( "--xml-comment", required=False, default="XML generated by flatten-tool", help="String comment of what generates the xml file", ) return parser def kwargs_from_parsed_args(args)...
64
64
54
8
55
Xtuden-com/flatten-tool
flattentool/cli.py
Python
kwargs_from_parsed_args
kwargs_from_parsed_args
294
300
294
294
ab3d4631e7b4d8a05e308e4e4cd25115b29b0412
bigcode/the-stack
train
d7304b0a6a49cad806e6812f
train
function
def create_parser(): """ Create an argparse ArgumentParser for our commandline arguments Defaults are not set here, but rather given in the appropriate function. (This is split out as it's own function primarily so it can be tested.) """ parser = argparse.ArgumentParser() subparsers = pa...
def create_parser():
""" Create an argparse ArgumentParser for our commandline arguments Defaults are not set here, but rather given in the appropriate function. (This is split out as it's own function primarily so it can be tested.) """ parser = argparse.ArgumentParser() subparsers = parser.add_subparsers(d...
from __future__ import print_function import argparse import sys import warnings from flattentool import create_template, flatten, unflatten from flattentool.input import FORMATS as INPUT_FORMATS from flattentool.json_input import BadlyFormedJSONError from flattentool.output import FORMATS as OUTPUT_FORMATS """ This...
144
256
2,164
4
140
Xtuden-com/flatten-tool
flattentool/cli.py
Python
create_parser
create_parser
24
291
24
24
260a75f492f698a615db5db471e4779985a495f2
bigcode/the-stack
train
7da061788ee47b00264237ad
train
function
def main(): """ Use ``create_parser`` to get the commandline arguments, and pass them to the appropriate function in __init__.py (create_template, flatten or unflatten). """ parser = create_parser() # Store the supplied arguments in args args = parser.parse_args() if args.subparser...
def main():
""" Use ``create_parser`` to get the commandline arguments, and pass them to the appropriate function in __init__.py (create_template, flatten or unflatten). """ parser = create_parser() # Store the supplied arguments in args args = parser.parse_args() if args.subparser_name is Non...
(value) + "\n") default_warning_formatter = warnings.formatwarning def non_verbose_warning_formatter(message, category, filename, lineno, line=None): if issubclass(category, UserWarning): return str(message) + "\n" else: return default_warning_formatter(message, category, filename, lineno, l...
72
72
243
3
69
Xtuden-com/flatten-tool
flattentool/cli.py
Python
main
main
320
351
320
320
f710cf42934067810c39b469283c63736b050716
bigcode/the-stack
train
be6d55b508e824ad736eb93f
train
function
@app.shared_task() def index_contract_metadata() -> int: """ Call `index_contracts_metadata` in the `contracts` app to index contracts with missing metadata :return: """ batch = 100 processed = 0 while True: addresses = MultisigTransaction.objects.not_indexed_metadata_contract_addre...
@app.shared_task() def index_contract_metadata() -> int:
""" Call `index_contracts_metadata` in the `contracts` app to index contracts with missing metadata :return: """ batch = 100 processed = 0 while True: addresses = MultisigTransaction.objects.not_indexed_metadata_contract_addresses()[:batch] if not addresses: brea...
: logger.warning('Failed status code %d posting to host=%s with content=%s', r.status_code, host, r.content) sent_requests += 1 return sent_requests finally: close_gevent_db_connection() @app.shared_task() def index_contract_metadata() -> i...
64
64
107
12
52
bigman1208000/safe-transaction-service
safe_transaction_service/history/tasks.py
Python
index_contract_metadata
index_contract_metadata
257
273
257
258
a05eeaf7618db3a397af08aca4e148ba2b92ea96
bigcode/the-stack
train
78dfacdcb7a9ef306759bfd3
train
function
@app.shared_task(bind=True, soft_time_limit=SOFT_TIMEOUT) def index_new_proxies_task(self) -> Optional[int]: """ :return: Number of proxies created """ with contextlib.suppress(LockError): with ony_one_running_task(self): logger.info('Start indexing of new proxies') numbe...
@app.shared_task(bind=True, soft_time_limit=SOFT_TIMEOUT) def index_new_proxies_task(self) -> Optional[int]:
""" :return: Number of proxies created """ with contextlib.suppress(LockError): with ony_one_running_task(self): logger.info('Start indexing of new proxies') number_proxies = ProxyFactoryIndexerProvider().start() if number_proxies: logger.info(...
: ACTIVE_LOCKS.add(lock_name) yield lock ACTIVE_LOCKS.remove(lock_name) close_gevent_db_connection() # Need for django-db-geventpool @app.shared_task(bind=True, soft_time_limit=SOFT_TIMEOUT) def index_new_proxies_task(self) -> Optional[int]:
64
64
105
26
37
bigman1208000/safe-transaction-service
safe_transaction_service/history/tasks.py
Python
index_new_proxies_task
index_new_proxies_task
94
105
94
95
34466b2e776e1e51fef797ef639ef40b7116a369
bigcode/the-stack
train
9d2e4117808e06242e2481d0
train
function
@app.shared_task(bind=True, soft_time_limit=SOFT_TIMEOUT) def index_erc20_events_task(self) -> Optional[int]: """ Find and process internal txs for monitored addresses :return: Number of addresses processed """ with contextlib.suppress(LockError): with ony_one_running_task(self): ...
@app.shared_task(bind=True, soft_time_limit=SOFT_TIMEOUT) def index_erc20_events_task(self) -> Optional[int]:
""" Find and process internal txs for monitored addresses :return: Number of addresses processed """ with contextlib.suppress(LockError): with ony_one_running_task(self): logger.info('Start indexing of erc20/721 events') number_events = Erc20EventsIndexerProvider().st...
number_traces) if number_traces: logger.info('Calling task to process decoded traces') process_decoded_internal_txs_task.delay() return number_traces @app.shared_task(bind=True, soft_time_limit=SOFT_TIMEOUT) def index_erc20_events_task(self) -> Optional[int]:
64
64
123
27
36
bigman1208000/safe-transaction-service
safe_transaction_service/history/tasks.py
Python
index_erc20_events_task
index_erc20_events_task
126
137
126
127
39b0c64509d5c7f287e22ee9036b736496d1f682
bigcode/the-stack
train
6952f189629a1381f128e348
train
function
@app.shared_task() def send_webhook_task(address: Optional[str], payload: Dict[str, Any]) -> int: if not (address and payload): return 0 try: webhooks = WebHook.objects.matching_for_address(address) if not webhooks: return 0 sent_requests = 0 for webhook in ...
@app.shared_task() def send_webhook_task(address: Optional[str], payload: Dict[str, Any]) -> int:
if not (address and payload): return 0 try: webhooks = WebHook.objects.matching_for_address(address) if not webhooks: return 0 sent_requests = 0 for webhook in webhooks: webhook_type = WebHookType[payload['type']] if webhook_type == W...
_block_number = reorg_service.check_reorgs() if first_reorg_block_number: logger.warning('Reorg found for block-number=%d', first_reorg_block_number) # Stopping running tasks is not possible with gevent reorg_service.recover_from_reorg(first_reorg_block_number...
106
106
355
24
81
bigman1208000/safe-transaction-service
safe_transaction_service/history/tasks.py
Python
send_webhook_task
send_webhook_task
215
254
215
216
748196ed85d6d740e926d88f4753ff5093ad9eb6
bigcode/the-stack
train
61ba32d4cba8de77d6baac58
train
function
@worker_shutting_down.connect def worker_shutting_down_handler(sig, how, exitcode, **kwargs): logger.warning('Worker shutting down') gevent.spawn(shutdown_worker) # If not raises a `BlockingSwitchOutError`
@worker_shutting_down.connect def worker_shutting_down_handler(sig, how, exitcode, **kwargs):
logger.warning('Worker shutting down') gevent.spawn(shutdown_worker) # If not raises a `BlockingSwitchOutError`
patch_psycopg logger.info('Patching psycopg for gevent') patch_psycopg() except ImportError: pass patch_psycopg() @worker_shutting_down.connect def worker_shutting_down_handler(sig, how, exitcode, **kwargs):
64
64
51
23
41
bigman1208000/safe-transaction-service
safe_transaction_service/history/tasks.py
Python
worker_shutting_down_handler
worker_shutting_down_handler
48
51
48
49
8c41e23530880a996e413b07057f18224440689c
bigcode/the-stack
train
aee67dd1b9257068f814f88a
train
function
@app.shared_task(bind=True, soft_time_limit=SOFT_TIMEOUT) def process_decoded_internal_txs_task(self) -> Optional[int]: try: with ony_one_running_task(self): count = InternalTxDecoded.objects.pending_for_safes().count() if not count: logger.info('No decoded internal t...
@app.shared_task(bind=True, soft_time_limit=SOFT_TIMEOUT) def process_decoded_internal_txs_task(self) -> Optional[int]:
try: with ony_one_running_task(self): count = InternalTxDecoded.objects.pending_for_safes().count() if not count: logger.info('No decoded internal txs to process') else: logger.info('%d decoded internal txs to process', count) ...
Erc20EventsIndexerProvider().start() logger.info('Indexing of erc20/721 events task processed %d events', number_events) return number_events @app.shared_task(bind=True, soft_time_limit=SOFT_TIMEOUT) def process_decoded_internal_txs_task(self) -> Optional[int]:
64
64
130
28
35
bigman1208000/safe-transaction-service
safe_transaction_service/history/tasks.py
Python
process_decoded_internal_txs_task
process_decoded_internal_txs_task
140
152
140
141
dcff8bb68bda3d1bb547135df19df9b55d65848b
bigcode/the-stack
train
5daa47a8766c7da5ab4730f4
train
function
@app.shared_task(bind=True, soft_time_limit=SOFT_TIMEOUT) def index_internal_txs_task(self) -> Optional[int]: """ Find and process internal txs for monitored addresses :return: Number of addresses processed """ with contextlib.suppress(LockError): with ony_one_running_task(self): ...
@app.shared_task(bind=True, soft_time_limit=SOFT_TIMEOUT) def index_internal_txs_task(self) -> Optional[int]:
""" Find and process internal txs for monitored addresses :return: Number of addresses processed """ with contextlib.suppress(LockError): with ony_one_running_task(self): logger.info('Start indexing of internal txs') number_traces = InternalTxIndexerProvider().start(...
number_proxies = ProxyFactoryIndexerProvider().start() if number_proxies: logger.info('Indexed new %d proxies', number_proxies) return number_proxies @app.shared_task(bind=True, soft_time_limit=SOFT_TIMEOUT) def index_internal_txs_task(self) -> Optional[int]:
64
64
142
26
37
bigman1208000/safe-transaction-service
safe_transaction_service/history/tasks.py
Python
index_internal_txs_task
index_internal_txs_task
108
123
108
109
cb4cd2490bd6993ee0f1c1beb34b8e3ffbf743d7
bigcode/the-stack
train
378ef0362f6b4859c50321e2
train
function
@contextlib.contextmanager def ony_one_running_task(task: CeleryTask, lock_name_suffix: Optional[str] = None, blocking_timeout: int = 1, lock_timeout: Optional[int] = LOCK_TIMEOUT): """ Ensures one running task at the same, using `task` ...
@contextlib.contextmanager def ony_one_running_task(task: CeleryTask, lock_name_suffix: Optional[str] = None, blocking_timeout: int = 1, lock_timeout: Optional[int] = LOCK_TIMEOUT):
""" Ensures one running task at the same, using `task` name as a unique key :param task: CeleryTask :param lock_name_suffix: A suffix for the lock name, in the case that the same task can be run at the same time when it has different arguments :param blocking_timeout: Waiting blocking timeout, i...
Force releasing of redis locks %s', ACTIVE_LOCKS) get_redis().delete(*ACTIVE_LOCKS) logger.warning('Released redis locks') else: logger.warning('No redis locks to release') @contextlib.contextmanager def ony_one_running_task(task: CeleryTask, lock_name_suffix: Option...
92
92
307
48
44
bigman1208000/safe-transaction-service
safe_transaction_service/history/tasks.py
Python
ony_one_running_task
ony_one_running_task
64
91
64
68
9220c4c9da7369b3516bb16723f3644c09d011f9
bigcode/the-stack
train
861cc5bdb630a83e241e18f1
train
function
@celeryd_init.connect def configure_workers(sender=None, conf=None, **kwargs): def patch_psycopg(): """ Patch postgresql to be friendly with gevent """ try: from psycogreen.gevent import patch_psycopg logger.info('Patching psycopg for gevent') patc...
@celeryd_init.connect def configure_workers(sender=None, conf=None, **kwargs):
def patch_psycopg(): """ Patch postgresql to be friendly with gevent """ try: from psycogreen.gevent import patch_psycopg logger.info('Patching psycopg for gevent') patch_psycopg() except ImportError: pass patch_psycopg()
60 * 10 # 10 minutes ACTIVE_LOCKS: Set[str] = set() # Active redis locks, release them when worker stops WORKER_STOPPED = set() # Worker status @celeryd_init.connect def configure_workers(sender=None, conf=None, **kwargs):
64
64
95
19
44
bigman1208000/safe-transaction-service
safe_transaction_service/history/tasks.py
Python
configure_workers
configure_workers
33
45
33
34
71071df997865af0626a4e59f7dfe36e562c084b
bigcode/the-stack
train
ba1f287c37080341e78e9d49
train
function
def shutdown_worker(): WORKER_STOPPED.add(True) if ACTIVE_LOCKS: logger.warning('Force releasing of redis locks %s', ACTIVE_LOCKS) get_redis().delete(*ACTIVE_LOCKS) logger.warning('Released redis locks') else: logger.warning('No redis locks to release')
def shutdown_worker():
WORKER_STOPPED.add(True) if ACTIVE_LOCKS: logger.warning('Force releasing of redis locks %s', ACTIVE_LOCKS) get_redis().delete(*ACTIVE_LOCKS) logger.warning('Released redis locks') else: logger.warning('No redis locks to release')
patch_psycopg() @worker_shutting_down.connect def worker_shutting_down_handler(sig, how, exitcode, **kwargs): logger.warning('Worker shutting down') gevent.spawn(shutdown_worker) # If not raises a `BlockingSwitchOutError` def shutdown_worker():
63
64
66
4
59
bigman1208000/safe-transaction-service
safe_transaction_service/history/tasks.py
Python
shutdown_worker
shutdown_worker
54
61
54
54
3e39ddc321432a057fb0d9790d1e0a7c93c93f8d
bigcode/the-stack
train
cd1c5026042c801ed1b96e48
train
function
@app.shared_task(bind=True, soft_time_limit=SOFT_TIMEOUT, task_time_limit=LOCK_TIMEOUT) def process_decoded_internal_txs_for_safe_task(self, safe_address: str) -> Optional[int]: """ Process decoded internal txs for one Safe. Processing decoded transactions is very slow and this way multiple Safes can be pro...
@app.shared_task(bind=True, soft_time_limit=SOFT_TIMEOUT, task_time_limit=LOCK_TIMEOUT) def process_decoded_internal_txs_for_safe_task(self, safe_address: str) -> Optional[int]:
""" Process decoded internal txs for one Safe. Processing decoded transactions is very slow and this way multiple Safes can be processed at the same time :param safe_address: :return: """ try: with ony_one_running_task(self, lock_name_suffix=safe_address): logger.info('St...
es().count() if not count: logger.info('No decoded internal txs to process') else: logger.info('%d decoded internal txs to process', count) for safe_to_process in InternalTxDecoded.objects.safes_pending_to_be_processed(): proces...
122
122
408
42
79
bigman1208000/safe-transaction-service
safe_transaction_service/history/tasks.py
Python
process_decoded_internal_txs_for_safe_task
process_decoded_internal_txs_for_safe_task
155
193
155
156
7c0781dd4024823af13cba5743ffd3497a2581e5
bigcode/the-stack
train
333c66a28b407abe333eca50
train
function
@app.shared_task(bind=True, soft_time_limit=SOFT_TIMEOUT) def check_reorgs_task(self) -> Optional[int]: """ :return: Number of oldest block with reorg detected. `None` if not reorg found """ try: with ony_one_running_task(self): logger.info('Start checking of reorgs') reo...
@app.shared_task(bind=True, soft_time_limit=SOFT_TIMEOUT) def check_reorgs_task(self) -> Optional[int]:
""" :return: Number of oldest block with reorg detected. `None` if not reorg found """ try: with ony_one_running_task(self): logger.info('Start checking of reorgs') reorg_service: ReorgService = ReorgServiceProvider() first_reorg_block_number = reorg_service.c...
_processed: logger.info('%d decoded internal txs successfully processed for safe %s', number_processed, safe_address) return number_processed except LockError: pass @app.shared_task(bind=True, soft_time_limit=SOFT_TIMEOUT) def check_reorgs_task(sel...
64
64
174
26
37
bigman1208000/safe-transaction-service
safe_transaction_service/history/tasks.py
Python
check_reorgs_task
check_reorgs_task
196
212
196
197
8d0155ac9b4647120f3f70cc76d48ecda4aee95e
bigcode/the-stack
train
80575f10082b7f8a324cf1cf
train
class
class IReadOnlyDictionary2(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_ma...
class IReadOnlyDictionary2(object):
"""NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name ...
# coding: utf-8 """ Speech Services API v2.0 Speech Services API v2.0. # noqa: E501 OpenAPI spec version: v2.0 Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class IReadOnlyDictionary2(object):
82
256
1,714
7
74
networthdata/generated-swagger-client
swagger_client/models/i_read_only_dictionary2.py
Python
IReadOnlyDictionary2
IReadOnlyDictionary2
20
271
20
20
aa76fc843ce8e24a18ce252837f5bfd3722f0b9f
bigcode/the-stack
train
67c8ac83e54b16203f575570
train
class
class TestCompareXLSXFiles(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename('chart_order01.xlsx') def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = ...
class TestCompareXLSXFiles(ExcelComparisonTest):
""" Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename('chart_order01.xlsx') def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got_filename) worksheet1 =...
############################################################################### # # Tests for XlsxWriter. # # Copyright (c), 2013-2021, John McNamara, jmcnamara@cpan.org # from ..excel_comparison_test import ExcelComparisonTest from ...workbook import Workbook class TestCompareXLSXFiles(ExcelComparisonTest):
67
160
534
12
54
eddiechapman/XlsxWriter
xlsxwriter/test/comparison/test_chart_order02.py
Python
TestCompareXLSXFiles
TestCompareXLSXFiles
12
72
12
12
4f9c3cb5c7db8ed6d6d9ce6f272947547073b1f9
bigcode/the-stack
train
80626500ff2e81061e520052
train
class
class IntegrationTest(unittest.TestCase): def setUp(self): super().setUp() self.data = { 'report_counts': [ dict(city_name='New York', num_symptoms=9666, num_deaths=123), dict(city_name='Los Angeles', num_symptoms=5000, num_deaths=23), dict...
class IntegrationTest(unittest.TestCase):
def setUp(self): super().setUp() self.data = { 'report_counts': [ dict(city_name='New York', num_symptoms=9666, num_deaths=123), dict(city_name='Los Angeles', num_symptoms=5000, num_deaths=23), dict(city_name='Boston', num_symptoms=800, num...
import unittest import json import os import textwrap from open_captcha.common_types import ServerContext, RenderingOptions from open_captcha.captcha_generator import CaptchaGenerator from open_captcha.challenge_templates import render_bar_chart class IntegrationTest(unittest.TestCase):
56
256
889
7
48
hasadna/OpenCaptcha
tests/test_integration.py
Python
IntegrationTest
IntegrationTest
10
91
10
10
9e4959c327d3dbf72b17e3b537aa4aa39a1ecc98
bigcode/the-stack
train
e52dbe15bc4c4fb611a5a362
train
function
def overwrite_or_not(parent): msgBox = QtWidgets.QMessageBox(parent) msgBox.setIcon(QtWidgets.QMessageBox.Question) msgBox.setText('Do you want to overwrite your labels with these predictions, or only import the predictions' ' for frames you haven''t labeled?') overwrite = msgBox.addB...
def overwrite_or_not(parent):
msgBox = QtWidgets.QMessageBox(parent) msgBox.setIcon(QtWidgets.QMessageBox.Question) msgBox.setText('Do you want to overwrite your labels with these predictions, or only import the predictions' ' for frames you haven''t labeled?') overwrite = msgBox.addButton('Overwrite', QtWidgets.Q...
, 'Message', message, QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.No) return reply == QtWidgets.QMessageBox.Yes # https://stackoverflow.com/questions/15682665/how-to-add-custom-button-to-a-qmessagebox-in-pyqt4 def overwrite_or_not(parent):
64
64
144
6
57
monajalal/deepethogram
deepethogram/gui/menus_and_popups.py
Python
overwrite_or_not
overwrite_or_not
14
27
14
14
70bda1e3f68af4fc9d26f6a862e700a66189f72f
bigcode/the-stack
train
cfd5145212d80878f1e8e797
train
class
class CreateProject(QtWidgets.QDialog): def __init__(self, parent=None): super().__init__(parent) string = 'Pick directory for your project. SHOULD BE ON YOUR FASTEST HARD DRIVE. VIDEOS WILL BE COPIED HERE' project_directory = QtWidgets.QFileDialog.getExistingDirectory(self, string) ...
class CreateProject(QtWidgets.QDialog):
def __init__(self, parent=None): super().__init__(parent) string = 'Pick directory for your project. SHOULD BE ON YOUR FASTEST HARD DRIVE. VIDEOS WILL BE COPIED HERE' project_directory = QtWidgets.QFileDialog.getExistingDirectory(self, string) if len(project_directory) == 0: ...
=None): super().__init__(parent) msgBox = QtWidgets.QMessageBox() msgBox.setText('Do you want to overwrite your labels with these predictions, or only import the predictions' ' for frames you haven''t labeled?') msgBox.addButton(QtWidgets.QPushButton('Overwrite'),...
112
112
374
8
104
monajalal/deepethogram
deepethogram/gui/menus_and_popups.py
Python
CreateProject
CreateProject
41
77
41
41
c5d29829866c80413e0843fbf299f36df94a1b4e
bigcode/the-stack
train
61a72620d8926206c99859e0
train
class
class OverwriteOrNot(QtWidgets.QDialog): def __init__(self, parent=None): super().__init__(parent) msgBox = QtWidgets.QMessageBox() msgBox.setText('Do you want to overwrite your labels with these predictions, or only import the predictions' ' for frames you haven''t l...
class OverwriteOrNot(QtWidgets.QDialog):
def __init__(self, parent=None): super().__init__(parent) msgBox = QtWidgets.QMessageBox() msgBox.setText('Do you want to overwrite your labels with these predictions, or only import the predictions' ' for frames you haven''t labeled?') msgBox.addButton(QtWidg...
Only import unlabeled', QtWidgets.QMessageBox.NoRole) msgBox.exec_() if msgBox.clickedButton() is overwrite: return True elif msgBox.clickedButton() is unlabeled: return False else: return class OverwriteOrNot(QtWidgets.QDialog):
64
64
122
10
53
monajalal/deepethogram
deepethogram/gui/menus_and_popups.py
Python
OverwriteOrNot
OverwriteOrNot
29
38
29
29
1c6225eab83e9247a468c18180962b90ee98d611
bigcode/the-stack
train
c1658e9b891c904fab122b06
train
function
def simple_popup_question(parent, message: str): # message = 'You have unsaved changes. Are you sure you want to quit?' reply = QtWidgets.QMessageBox.question(parent, 'Message', message, QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.No) return reply == QtWidgets...
def simple_popup_question(parent, message: str): # message = 'You have unsaved changes. Are you sure you want to quit?'
reply = QtWidgets.QMessageBox.question(parent, 'Message', message, QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.No) return reply == QtWidgets.QMessageBox.Yes
import warnings from PySide2 import QtCore, QtWidgets def simple_popup_question(parent, message: str): # message = 'You have unsaved changes. Are you sure you want to quit?'
44
64
72
30
13
monajalal/deepethogram
deepethogram/gui/menus_and_popups.py
Python
simple_popup_question
simple_popup_question
6
10
6
7
56d1f9e59e2508dbd234c12dd2352a7ad2a7e832
bigcode/the-stack
train
c65165eabc291e661aa97502
train
class
class ShouldRunInference(QtWidgets.QDialog): def __init__(self, record_keys: list, should_start_checked: list): super(ShouldRunInference, self).__init__() self.createFormGroupBox(record_keys, should_start_checked) buttonBox = QtWidgets.QDialogButtonBox(QtWidgets.QDialogButtonBox.Ok | QtWi...
class ShouldRunInference(QtWidgets.QDialog):
def __init__(self, record_keys: list, should_start_checked: list): super(ShouldRunInference, self).__init__() self.createFormGroupBox(record_keys, should_start_checked) buttonBox = QtWidgets.QDialogButtonBox(QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel) buttonB...
.Ok | QtWidgets.QDialogButtonBox.Cancel) button_box.accepted.connect(self.accept) button_box.rejected.connect(self.reject) layout = QtWidgets.QFormLayout() layout.addRow(self.project_box) layout.addRow(self.labeler_box) layout.addRow(self.behaviors_box) # layout....
139
139
465
9
130
monajalal/deepethogram
deepethogram/gui/menus_and_popups.py
Python
ShouldRunInference
ShouldRunInference
81
132
81
82
b9eba0d1f2262d68b9048a0037308376c091e3ee
bigcode/the-stack
train
a29f7b555b4542f6a6c51676
train
class
class SampClient(object): """ Client class for communicating with SA-MP Query API http://wiki.sa-mp.com/wiki/Query_Mechanism """ timeout = 1.0 def __init__(self, address='127.0.0.1', port=7777, rcon_password=None): super(SampClient, self).__init__() assert isinstance(address, ba...
class SampClient(object):
""" Client class for communicating with SA-MP Query API http://wiki.sa-mp.com/wiki/Query_Mechanism """ timeout = 1.0 def __init__(self, address='127.0.0.1', port=7777, rcon_password=None): super(SampClient, self).__init__() assert isinstance(address, basestring) self.add...
from __future__ import unicode_literals, absolute_import import socket from past.builtins import basestring from future.builtins import bytes, str from samp_client_ES.constants import * from samp_client_ES.exceptions import SampError, RconError, InvalidRconPassword, ConnectionError from samp_client_ES.models import Se...
110
256
3,065
5
104
thenooblol2003/samp-client-s
samp_client_ES/client.py
Python
SampClient
SampClient
12
387
12
12
fea8db916d2f0e85a2f8be28731bee2b0c1cb2db
bigcode/the-stack
train