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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
02450a26a5c08719975e8640 | train | class | @requires_bz2()
class Bzip2WriterTests(AbstractWriterTests, unittest.TestCase):
compression = zipfile.ZIP_BZIP2
| @requires_bz2()
class Bzip2WriterTests(AbstractWriterTests, unittest.TestCase):
| compression = zipfile.ZIP_BZIP2
| unittest.TestCase):
compression = zipfile.ZIP_STORED
@requires_zlib()
class DeflateWriterTests(AbstractWriterTests, unittest.TestCase):
compression = zipfile.ZIP_DEFLATED
@requires_bz2()
class Bzip2WriterTests(AbstractWriterTests, unittest.TestCase):
| 64 | 64 | 31 | 20 | 43 | oleksandr-pavlyk/cpython | Lib/test/test_zipfile.py | Python | Bzip2WriterTests | Bzip2WriterTests | 1,131 | 1,133 | 1,131 | 1,132 | e2a8562674c70902ce7b64ed0f49cb26be065e5f | bigcode/the-stack | train |
cb8e3efaa6951a378f891cf5 | train | class | @requires_zlib()
class DeflateTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
unittest.TestCase):
compression = zipfile.ZIP_DEFLATED
| @requires_zlib()
class DeflateTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
unittest.TestCase):
| compression = zipfile.ZIP_DEFLATED
| _random_open_test(f, self.compression)
class StoredTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
unittest.TestCase):
compression = zipfile.ZIP_STORED
@requires_zlib()
class DeflateTestsWithRandomBinaryFiles(AbstractTestsWithRandomBinaryFiles,
... | 64 | 64 | 36 | 25 | 38 | oleksandr-pavlyk/cpython | Lib/test/test_zipfile.py | Python | DeflateTestsWithRandomBinaryFiles | DeflateTestsWithRandomBinaryFiles | 2,346 | 2,349 | 2,346 | 2,348 | 22de4c182ba399925b51b6696f7e9b1c5a6a41aa | bigcode/the-stack | train |
44934647ba949ff64c688dbb | train | class | @requires_bz2()
class Bzip2BadCrcTests(AbstractBadCrcTests, unittest.TestCase):
compression = zipfile.ZIP_BZIP2
zip_with_bad_crc = (
b'PK\x03\x04\x14\x03\x00\x00\x0c\x00nu\x0c=FA'
b'KE8\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
b'ileBZh91AY&SY\xd4\xa8\xca'
b'\x7f\x00\x00\x0f\x1... | @requires_bz2()
class Bzip2BadCrcTests(AbstractBadCrcTests, unittest.TestCase):
| compression = zipfile.ZIP_BZIP2
zip_with_bad_crc = (
b'PK\x03\x04\x14\x03\x00\x00\x0c\x00nu\x0c=FA'
b'KE8\x00\x00\x00n\x00\x00\x00\x05\x00\x00\x00af'
b'ileBZh91AY&SY\xd4\xa8\xca'
b'\x7f\x00\x00\x0f\x11\x80@\x00\x06D\x90\x80 \x00 \xa5'
b'P\xd9!\x03\x03\x13\x13\x13\x89\xa9\... | \x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x01\x00\x00\x00'
b'\x00afilePK\x05\x06\x00\x00\x00\x00\x01\x00'
b'\x01\x003\x00\x00\x003\x00\x00\x00\x00\x00')
@requires_bz2()
class Bzip2BadCrcTests(AbstractBadCrcTests, unittest.TestCase):
| 101 | 101 | 337 | 24 | 77 | oleksandr-pavlyk/cpython | Lib/test/test_zipfile.py | Python | Bzip2BadCrcTests | Bzip2BadCrcTests | 2,104 | 2,118 | 2,104 | 2,105 | 67a26e2ecf19b80f0248887f56a60b45680109a1 | bigcode/the-stack | train |
86106cc7a52381fb9e771c39 | train | class | class PyZipFileTests(unittest.TestCase):
def assertCompiledIn(self, name, namelist):
if name + 'o' not in namelist:
self.assertIn(name + 'c', namelist)
def requiresWriteAccess(self, path):
# effective_ids unavailable on windows
if not os.access(path, os.W_OK,
... | class PyZipFileTests(unittest.TestCase):
| def assertCompiledIn(self, name, namelist):
if name + 'o' not in namelist:
self.assertIn(name + 'c', namelist)
def requiresWriteAccess(self, path):
# effective_ids unavailable on windows
if not os.access(path, os.W_OK,
effective_ids=os.access in os.s... | test', 'w')
w.write(data)
w.close()
self.assertTrue(w.closed)
w.close()
self.assertTrue(w.closed)
self.assertEqual(zipf.read('test'), data)
def test_write_after_close(self):
data = b'content'
with zipfile.ZipFile(TESTFN2, "w", ... | 256 | 256 | 1,754 | 9 | 246 | oleksandr-pavlyk/cpython | Lib/test/test_zipfile.py | Python | PyZipFileTests | PyZipFileTests | 1,140 | 1,330 | 1,140 | 1,140 | 67d918f64c23e5a24d90a27f603fdcef7ebecb65 | bigcode/the-stack | train |
f205458dda575e1dc263d69d | train | class | class StoredTestsWithSourceFile(AbstractTestsWithSourceFile,
unittest.TestCase):
compression = zipfile.ZIP_STORED
test_low_compression = None
def zip_test_writestr_permissions(self, f, compression):
# Make sure that writestr and open(... mode='w') create files with
... | class StoredTestsWithSourceFile(AbstractTestsWithSourceFile,
unittest.TestCase):
| compression = zipfile.ZIP_STORED
test_low_compression = None
def zip_test_writestr_permissions(self, f, compression):
# Make sure that writestr and open(... mode='w') create files with
# mode 0600, when they are passed a name rather than a ZipInfo
# instance.
self.make_test... | ()
count = None
with zipfile.ZipFile(testfile, 'w', self.compression) as zipfp:
with zipfp.open('file1', 'w') as f:
f.write(b'data1')
count = 0
try:
with zipfp.open('file2', 'w') as f:
... | 256 | 256 | 2,156 | 17 | 239 | oleksandr-pavlyk/cpython | Lib/test/test_zipfile.py | Python | StoredTestsWithSourceFile | StoredTestsWithSourceFile | 453 | 644 | 453 | 454 | 4754775aebdb4270e9f5c31ba65f3a9712b75215 | bigcode/the-stack | train |
e2502aa7731802a1fac4b37b | train | class | @requires_zlib()
class TestsWithMultipleOpens(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.data1 = b'111' + randbytes(10000)
cls.data2 = b'222' + randbytes(10000)
def make_test_archive(self, f):
# Create the ZIP archive
with zipfile.ZipFile(f, "w", zipfile.ZIP_D... | @requires_zlib()
class TestsWithMultipleOpens(unittest.TestCase):
@classmethod
| def setUpClass(cls):
cls.data1 = b'111' + randbytes(10000)
cls.data2 = b'222' + randbytes(10000)
def make_test_archive(self, f):
# Create the ZIP archive
with zipfile.ZipFile(f, "w", zipfile.ZIP_DEFLATED) as zipfp:
zipfp.writestr('ones', self.data1)
zipfp... | as zipf:
with zipf.open('ones') as zopen:
self.assertEqual(zopen.read(), b'111')
with zipf.open('twos') as zopen:
self.assertEqual(zopen.read(), b'222')
def test_open_write(self):
for wrapper in (lambda f: f), Tellable... | 256 | 256 | 1,335 | 19 | 237 | oleksandr-pavlyk/cpython | Lib/test/test_zipfile.py | Python | TestsWithMultipleOpens | TestsWithMultipleOpens | 2,444 | 2,567 | 2,444 | 2,446 | 30836113a834807e7f2075df624e937b2b0522cc | bigcode/the-stack | train |
1825487762ca11b5b0aafe3e | train | class | @requires_zlib()
class DeflateTestsWithSourceFile(AbstractTestsWithSourceFile,
unittest.TestCase):
compression = zipfile.ZIP_DEFLATED
def test_per_file_compression(self):
"""Check that files within a Zip archive can have different
compression options."""
... | @requires_zlib()
class DeflateTestsWithSourceFile(AbstractTestsWithSourceFile,
unittest.TestCase):
| compression = zipfile.ZIP_DEFLATED
def test_per_file_compression(self):
"""Check that files within a Zip archive can have different
compression options."""
with zipfile.ZipFile(TESTFN2, "w") as zipfp:
zipfp.write(TESTFN, 'storeme', zipfile.ZIP_STORED)
zipfp.write... | FN)
zinfo = zipfp.getinfo(TESTFN)
self.assertEqual(zinfo.date_time, (2107, 12, 31, 23, 59, 59))
@requires_zlib()
class DeflateTestsWithSourceFile(AbstractTestsWithSourceFile,
unittest.TestCase):
| 64 | 64 | 175 | 23 | 41 | oleksandr-pavlyk/cpython | Lib/test/test_zipfile.py | Python | DeflateTestsWithSourceFile | DeflateTestsWithSourceFile | 647 | 661 | 647 | 649 | c00de059bb0e11caa7261866df26f6030dd23056 | bigcode/the-stack | train |
3d79590c97870edb943218dd | train | class | @requires_lzma()
class LzmaTestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
unittest.TestCase):
compression = zipfile.ZIP_LZMA
| @requires_lzma()
class LzmaTestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
unittest.TestCase):
| compression = zipfile.ZIP_LZMA
| ()
class Bzip2TestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
unittest.TestCase):
compression = zipfile.ZIP_BZIP2
@requires_lzma()
class LzmaTestZip64InSmallFiles(AbstractTestZip64InSmallFiles,
unittest.TestCase):
| 64 | 64 | 40 | 29 | 34 | oleksandr-pavlyk/cpython | Lib/test/test_zipfile.py | Python | LzmaTestZip64InSmallFiles | LzmaTestZip64InSmallFiles | 1,092 | 1,095 | 1,092 | 1,094 | 9e016a693815d3741c64ceb6c77f9e186dc135c5 | bigcode/the-stack | train |
c6d12dc55d3548cbb4b7fc68 | train | function | def biconcat(input1: str, input2: str):
return input1 + input2 # pragma: no cover
| def biconcat(input1: str, input2: str):
| return input1 + input2 # pragma: no cover
| import ModularPipelineError
# Different dummy func based on the number of arguments
def constant_output():
return "output" # pragma: no cover
def identity(input1: str):
return input1 # pragma: no cover
def biconcat(input1: str, input2: str):
| 64 | 64 | 28 | 14 | 49 | iamkuldeepsingh/kedro | tests/pipeline/test_pipeline_helper.py | Python | biconcat | biconcat | 44 | 45 | 44 | 44 | cb950e6f3f1674464127e7e861a0fc631adc92d9 | bigcode/the-stack | train |
b5aacb341c42ce5f97399d6c | train | function | def constant_output():
return "output" # pragma: no cover
| def constant_output():
| return "output" # pragma: no cover
| or on software.
#
# See the License for the specific language governing permissions and
# limitations under the License.
import pytest
from kedro.pipeline import Pipeline, node, pipeline
from kedro.pipeline.modular_pipeline import ModularPipelineError
# Different dummy func based on the number of arguments
def const... | 64 | 64 | 16 | 4 | 59 | iamkuldeepsingh/kedro | tests/pipeline/test_pipeline_helper.py | Python | constant_output | constant_output | 36 | 37 | 36 | 36 | 56acea8ef2a7b59aeef4ccad68974c4c2629c262 | bigcode/the-stack | train |
b4c75649da0a6cc4c9da615f | train | function | def identity(input1: str):
return input1 # pragma: no cover
| def identity(input1: str):
| return input1 # pragma: no cover
| under the License.
import pytest
from kedro.pipeline import Pipeline, node, pipeline
from kedro.pipeline.modular_pipeline import ModularPipelineError
# Different dummy func based on the number of arguments
def constant_output():
return "output" # pragma: no cover
def identity(input1: str):
| 64 | 64 | 18 | 7 | 56 | iamkuldeepsingh/kedro | tests/pipeline/test_pipeline_helper.py | Python | identity | identity | 40 | 41 | 40 | 40 | 521e7db90afd753a3f4e2b15a9798159b24b588b | bigcode/the-stack | train |
532117054f8cc152b95c6ae1 | train | class | class TestPipelineHelper:
def test_transform_dataset_names(self):
"""
Rename some datasets, test string, list and dict formats.
"""
raw_pipeline = Pipeline(
[
node(identity, "A", "B", name="node1"),
node(biconcat, ["C", "D"], ["E", "F"], na... | class TestPipelineHelper:
| def test_transform_dataset_names(self):
"""
Rename some datasets, test string, list and dict formats.
"""
raw_pipeline = Pipeline(
[
node(identity, "A", "B", name="node1"),
node(biconcat, ["C", "D"], ["E", "F"], name="node2"),
... | THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
# The QuantumBlack Visual Analytics Limited ("QuantumBlack") name and logo
# (either separately or in combination, "QuantumBlack Trademarks") are
# trademarks of QuantumBlack. The License does not grant you any right or
# license to the QuantumBlack Trademarks. You may not ... | 256 | 256 | 2,961 | 5 | 250 | iamkuldeepsingh/kedro | tests/pipeline/test_pipeline_helper.py | Python | TestPipelineHelper | TestPipelineHelper | 48 | 354 | 48 | 48 | ea342208a0181dc2a6b278858bd097fe88e6b9b1 | bigcode/the-stack | train |
d94f72f31a3c990165b7153b | train | function | def exercise(driver):
element = WebDriverWait(driver,10).until(EC.presence_of_element_located((By.ID, "open1")))
element.click()
element = WebDriverWait(driver,10).until(EC.presence_of_element_located((By.ID, "l35")))
element.click()
WebDriverWait(driver,10).until(lambda driver: driver.execute_scrip... | def exercise(driver):
| element = WebDriverWait(driver,10).until(EC.presence_of_element_located((By.ID, "open1")))
element.click()
element = WebDriverWait(driver,10).until(EC.presence_of_element_located((By.ID, "l35")))
element.click()
WebDriverWait(driver,10).until(lambda driver: driver.execute_script("return window.World... | limitations under the License.
# Author: Manu Sridharan
from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0
from selenium.webdriver.support import expected_conditions as EC # available since 2.26.0
from selenium.webdriver.common.by import By
def exercise(driver):
| 64 | 64 | 124 | 4 | 59 | ChangXiaoning/jalangi2 | tests/tizen/annex/app_exercise.py | Python | exercise | exercise | 21 | 28 | 21 | 21 | dffee004dd27c6a7da09de7df1a7eda449a921b7 | bigcode/the-stack | train |
5fca710da8514123fa0dcff5 | train | function | @pytest.mark.parametrize("index_names", [
["", ""],
["foo", ""],
["", "bar"],
["foo", "bar"],
["NotReallyUnnamed", "Unnamed: 0"],
])
def test_multi_index_naming(all_parsers, index_names):
parser = all_parsers
# We don't want empty index names being replaced with "Unnamed: 0"
data = ",".... | @pytest.mark.parametrize("index_names", [
["", ""],
["foo", ""],
["", "bar"],
["foo", "bar"],
["NotReallyUnnamed", "Unnamed: 0"],
])
def test_multi_index_naming(all_parsers, index_names):
| parser = all_parsers
# We don't want empty index names being replaced with "Unnamed: 0"
data = ",".join(index_names + ["col\na,c,1\na,d,2\nb,c,3\nb,d,4"])
result = parser.read_csv(StringIO(data), index_col=[0, 1])
expected = DataFrame({"col": [1, 2, 3, 4]},
index=MultiInde... | _frame_equal(result, expected)
@pytest.mark.parametrize("index_names", [
["", ""],
["foo", ""],
["", "bar"],
["foo", "bar"],
["NotReallyUnnamed", "Unnamed: 0"],
])
def test_multi_index_naming(all_parsers, index_names):
| 64 | 64 | 200 | 58 | 6 | developing-coder/pandas | pandas/tests/io/parser/test_index_col.py | Python | test_multi_index_naming | test_multi_index_naming | 119 | 137 | 119 | 126 | e4936061ea7037e600a9cc9c195c0d946c3c0a3c | bigcode/the-stack | train |
1f9b39cbbf39d98f2da43549 | train | function | def test_index_col_is_true(all_parsers):
# see gh-9798
data = "a,b\n1,2"
parser = all_parsers
with pytest.raises(ValueError, match="The value of index_col "
"couldn't be 'True'"):
parser.read_csv(StringIO(data), index_col=True)
| def test_index_col_is_true(all_parsers):
# see gh-9798
| data = "a,b\n1,2"
parser = all_parsers
with pytest.raises(ValueError, match="The value of index_col "
"couldn't be 'True'"):
parser.read_csv(StringIO(data), index_col=True)
| names = ["a", "b", "c", "d", "message"]
result = parser.read_csv(StringIO(data), names=names,
index_col=["message"])
tm.assert_frame_equal(result, expected)
def test_index_col_is_true(all_parsers):
# see gh-9798
| 64 | 64 | 72 | 18 | 46 | developing-coder/pandas | pandas/tests/io/parser/test_index_col.py | Python | test_index_col_is_true | test_index_col_is_true | 59 | 66 | 59 | 60 | c4ca3bd0b7ba9e1a7f3daa878314c25628ba3b69 | bigcode/the-stack | train |
231a3033909f6408e7556961 | train | function | def test_index_col_named2(all_parsers):
parser = all_parsers
data = """\
1,2,3,4,hello
5,6,7,8,world
9,10,11,12,foo
"""
expected = DataFrame({"a": [1, 5, 9], "b": [2, 6, 10],
"c": [3, 7, 11], "d": [4, 8, 12]},
index=Index(["hello", "world", "foo"],
... | def test_index_col_named2(all_parsers):
| parser = all_parsers
data = """\
1,2,3,4,hello
5,6,7,8,world
9,10,11,12,foo
"""
expected = DataFrame({"a": [1, 5, 9], "b": [2, 6, 10],
"c": [3, 7, 11], "d": [4, 8, 12]},
index=Index(["hello", "world", "foo"],
name="mess... | _index("ID")
tm.assert_frame_equal(result, expected)
else:
data = no_header
msg = "Index ID invalid"
with pytest.raises(ValueError, match=msg):
parser.read_csv(StringIO(data), index_col="ID")
def test_index_col_named2(all_parsers):
| 64 | 64 | 172 | 10 | 54 | developing-coder/pandas | pandas/tests/io/parser/test_index_col.py | Python | test_index_col_named2 | test_index_col_named2 | 40 | 56 | 40 | 40 | fb3e6a26fb6e1d3e243893d6e433d0d0241ba699 | bigcode/the-stack | train |
59ed55f326657401615c9f2f | train | function | @pytest.mark.parametrize("index_col,kwargs", [
(None, dict(columns=["x", "y", "z"])),
(False, dict(columns=["x", "y", "z"])),
(0, dict(columns=["y", "z"], index=Index([], name="x"))),
(1, dict(columns=["x", "z"], index=Index([], name="y"))),
("x", dict(columns=["y", "z"], index=Index([], name="x")))... | @pytest.mark.parametrize("index_col,kwargs", [
(None, dict(columns=["x", "y", "z"])),
(False, dict(columns=["x", "y", "z"])),
(0, dict(columns=["y", "z"], index=Index([], name="x"))),
(1, dict(columns=["x", "z"], index=Index([], name="y"))),
("x", dict(columns=["y", "z"], index=Index([], name="x")))... | data = "x,y,z"
parser = all_parsers
result = parser.read_csv(StringIO(data), index_col=index_col)
expected = DataFrame(**kwargs)
tm.assert_frame_equal(result, expected)
| @pytest.mark.parametrize("index_col,kwargs", [
(None, dict(columns=["x", "y", "z"])),
(False, dict(columns=["x", "y", "z"])),
(0, dict(columns=["y", "z"], index=Index([], name="x"))),
(1, dict(columns=["x", "z"], index=Index([], name="y"))),
("x", dict(columns=["y", "z"], index=Index([], name="x")))... | 280 | 98 | 327 | 280 | 0 | developing-coder/pandas | pandas/tests/io/parser/test_index_col.py | Python | test_index_col_empty_data | test_index_col_empty_data | 84 | 106 | 84 | 100 | 9ebbdeccb2aab118ce3936d984ca2629033ec0ec | bigcode/the-stack | train |
5b4328b5ff4df5d5f783a304 | train | function | def test_empty_with_index_col_false(all_parsers):
# see gh-10413
data = "x,y"
parser = all_parsers
result = parser.read_csv(StringIO(data), index_col=False)
expected = DataFrame(columns=["x", "y"])
tm.assert_frame_equal(result, expected)
| def test_empty_with_index_col_false(all_parsers):
# see gh-10413
| data = "x,y"
parser = all_parsers
result = parser.read_csv(StringIO(data), index_col=False)
expected = DataFrame(columns=["x", "y"])
tm.assert_frame_equal(result, expected)
| = "x,y,z"
parser = all_parsers
result = parser.read_csv(StringIO(data), index_col=index_col)
expected = DataFrame(**kwargs)
tm.assert_frame_equal(result, expected)
def test_empty_with_index_col_false(all_parsers):
# see gh-10413
| 64 | 64 | 68 | 19 | 45 | developing-coder/pandas | pandas/tests/io/parser/test_index_col.py | Python | test_empty_with_index_col_false | test_empty_with_index_col_false | 109 | 116 | 109 | 110 | f531a975623104a7bedb2237d3689192edf910b6 | bigcode/the-stack | train |
afa68501184688aca08986e1 | train | function | @pytest.mark.parametrize("with_header", [True, False])
def test_index_col_named(all_parsers, with_header):
parser = all_parsers
no_header = """\
KORD1,19990127, 19:00:00, 18:56:00, 0.8100, 2.8100, 7.2000, 0.0000, 280.0000
KORD2,19990127, 20:00:00, 19:56:00, 0.0100, 2.2100, 7.2000, 0.0000, 260.0000
KORD3,1999012... | @pytest.mark.parametrize("with_header", [True, False])
def test_index_col_named(all_parsers, with_header):
| parser = all_parsers
no_header = """\
KORD1,19990127, 19:00:00, 18:56:00, 0.8100, 2.8100, 7.2000, 0.0000, 280.0000
KORD2,19990127, 20:00:00, 19:56:00, 0.0100, 2.2100, 7.2000, 0.0000, 260.0000
KORD3,19990127, 21:00:00, 20:56:00, -0.5900, 2.2100, 5.7000, 0.0000, 280.0000
KORD4,19990127, 21:00:00, 21:18:00, -0.990... | """
Tests that the specified index column (a.k.a "index_col")
is properly handled or inferred during parsing for all of
the parsers defined in parsers.py
"""
from io import StringIO
import pytest
from pandas import DataFrame, Index, MultiIndex
import pandas.util.testing as tm
@pytest.mark.parametrize("with_header", [... | 87 | 145 | 484 | 24 | 62 | developing-coder/pandas | pandas/tests/io/parser/test_index_col.py | Python | test_index_col_named | test_index_col_named | 14 | 37 | 14 | 15 | 8e8330dcbebf811270ce1e9623162250586e7064 | bigcode/the-stack | train |
949126a6fbb03c2d787a23ac | train | function | def test_infer_index_col(all_parsers):
data = """A,B,C
foo,1,2,3
bar,4,5,6
baz,7,8,9
"""
parser = all_parsers
result = parser.read_csv(StringIO(data))
expected = DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]],
index=["foo", "bar", "baz"],
columns=["A", "B"... | def test_infer_index_col(all_parsers):
| data = """A,B,C
foo,1,2,3
bar,4,5,6
baz,7,8,9
"""
parser = all_parsers
result = parser.read_csv(StringIO(data))
expected = DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]],
index=["foo", "bar", "baz"],
columns=["A", "B", "C"])
tm.assert_frame_equal(resul... | data = "a,b\n1,2"
parser = all_parsers
with pytest.raises(ValueError, match="The value of index_col "
"couldn't be 'True'"):
parser.read_csv(StringIO(data), index_col=True)
def test_infer_index_col(all_parsers):
| 64 | 64 | 123 | 10 | 54 | developing-coder/pandas | pandas/tests/io/parser/test_index_col.py | Python | test_infer_index_col | test_infer_index_col | 69 | 81 | 69 | 69 | 1392de8156c49460df0f29afc81778872f1634fe | bigcode/the-stack | train |
7290f4aa8db68f7bd15df489 | train | function | def test_multi_index_naming_not_all_at_beginning(all_parsers):
parser = all_parsers
data = ",Unnamed: 2,\na,c,1\na,d,2\nb,c,3\nb,d,4"
result = parser.read_csv(StringIO(data), index_col=[0, 2])
expected = DataFrame({"Unnamed: 2": ["c", "d", "c", "d"]},
index=MultiIndex(
... | def test_multi_index_naming_not_all_at_beginning(all_parsers):
| parser = all_parsers
data = ",Unnamed: 2,\na,c,1\na,d,2\nb,c,3\nb,d,4"
result = parser.read_csv(StringIO(data), index_col=[0, 2])
expected = DataFrame({"Unnamed: 2": ["c", "d", "c", "d"]},
index=MultiIndex(
levels=[['a', 'b'], [1, 2, 3, 4]],
... | ]},
index=MultiIndex.from_product([["a", "b"],
["c", "d"]]))
expected.index.names = [name if name else None for name in index_names]
tm.assert_frame_equal(result, expected)
def test_multi_index_naming_not_all_at_beginning(all_parse... | 64 | 64 | 156 | 15 | 49 | developing-coder/pandas | pandas/tests/io/parser/test_index_col.py | Python | test_multi_index_naming_not_all_at_beginning | test_multi_index_naming_not_all_at_beginning | 140 | 149 | 140 | 140 | 766aea957f6414397ea2aa665a2d560f86a1e325 | bigcode/the-stack | train |
bf37b46fa08e1c0e51da33fa | train | class | class TestCustomObjectMaker(unittest.TestCase):
config = {'worker_config': {'handler_cfaua': {
'input_resources_api_token': 'resources_api_token',
'output_resources_api_token': 'resources_api_token',
'resources_api_version': 'resources_api_version',
'input_resources_api_server': 'res... | class TestCustomObjectMaker(unittest.TestCase):
| config = {'worker_config': {'handler_cfaua': {
'input_resources_api_token': 'resources_api_token',
'output_resources_api_token': 'resources_api_token',
'resources_api_version': 'resources_api_version',
'input_resources_api_server': 'resources_api_server',
'input_public_resour... | import unittest
from copy import deepcopy
from datetime import datetime
from mock import patch, MagicMock, call
from openprocurement_client.exceptions import (
RequestFailed,
ResourceNotFound,
ResourceGone
)
from openprocurement.bridge.basic.tests.base import AdaptiveCache
from openprocurement.bridge.bas... | 168 | 256 | 1,241 | 9 | 159 | EBRD-ProzorroSale/openprocurement.bridge.basic | openprocurement/bridge/basic/tests/handlers.py | Python | TestCustomObjectMaker | TestCustomObjectMaker | 28 | 160 | 28 | 28 | f371dd4a93eaab1c076875430b4ff46e9a2c67b1 | bigcode/the-stack | train |
44de3b64340b7adec150bc2f | train | class | class CustomObjectMaker(HandlerTemplate):
def __init__(self, config, cache_db):
logger.info("Init Close Framework Agreement UA Handler.")
self.handler_name = 'handler_cfaua'
super(CustomObjectMaker, self).__init__(config, cache_db)
self.basket = {}
self.keys_from_tender = ('... | class CustomObjectMaker(HandlerTemplate):
| def __init__(self, config, cache_db):
logger.info("Init Close Framework Agreement UA Handler.")
self.handler_name = 'handler_cfaua'
super(CustomObjectMaker, self).__init__(config, cache_db)
self.basket = {}
self.keys_from_tender = ('procuringEntity',)
| _client.exceptions import (
RequestFailed,
ResourceNotFound,
ResourceGone
)
from openprocurement.bridge.basic.tests.base import AdaptiveCache
from openprocurement.bridge.basic.handlers import HandlerTemplate, logger
from openprocurement.bridge.basic.utils import DataBridgeConfigError
class CustomObjectMake... | 64 | 64 | 76 | 8 | 55 | EBRD-ProzorroSale/openprocurement.bridge.basic | openprocurement/bridge/basic/tests/handlers.py | Python | CustomObjectMaker | CustomObjectMaker | 18 | 25 | 18 | 19 | 04816b918670d9958e66f8b940215f45594ef296 | bigcode/the-stack | train |
e6337f561a0f20543d0ebbcc | train | function | def suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(TestCustomObjectMaker))
return suite
| def suite():
| suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(TestCustomObjectMaker))
return suite
| handler = CustomObjectMaker(self.config, cache_db)
new_date = datetime.now()
resource = {'id': '0' * 32, 'dateModified': new_date}
handler._put_resource_in_cache(resource)
self.assertEquals(cache_db.get(resource['id']), new_date)
def suite():
| 64 | 64 | 26 | 3 | 61 | EBRD-ProzorroSale/openprocurement.bridge.basic | openprocurement/bridge/basic/tests/handlers.py | Python | suite | suite | 163 | 166 | 163 | 163 | 858ad88d6f6645af5b17ffba3ba0f731ee21c31d | bigcode/the-stack | train |
c4dffcdd9be13d331829ebd6 | train | class | class BandwidthFileLiner:
"""
Parses :class:`BandwidthFileToken` s into :class:`BandwidthFileTimestamp`,
:class:`BandwidthFileHeaderLine` s and :class:`BandwidthFileRelayLine`. By
default this is a strict implementation of the Tor Bandwidth File
Specification version 1.4.0 [bandwidth-file-spec]_, bu... | class BandwidthFileLiner:
| """
Parses :class:`BandwidthFileToken` s into :class:`BandwidthFileTimestamp`,
:class:`BandwidthFileHeaderLine` s and :class:`BandwidthFileRelayLine`. By
default this is a strict implementation of the Tor Bandwidth File
Specification version 1.4.0 [bandwidth-file-spec]_, but this can be relaxed
... | """
Bandwidth files.
"""
# TODO: Write better docstring
import base64
import collections
import datetime
import enum
import logging
import re
import textwrap
import nacl.signing
import nacl.encoding
from bushel.document import BaseDocument
LOG = logging.getLogger('bushel')
class BandwidthFileLineError(enum.Enum):
... | 189 | 256 | 1,046 | 7 | 182 | irl/bushel | bushel/bandwidth/file.py | Python | BandwidthFileLiner | BandwidthFileLiner | 37 | 159 | 37 | 37 | 40936f7068e00e5d203b8876c6c5691d847ccde2 | bigcode/the-stack | train |
37ca6f4a90616331e54e090e | train | class | class BandwidthFileToken(collections.namedtuple('BandwidthFileToken', ['kind', 'value', 'line', 'column'])):
"""
:var str kind: the kind of token
:var bytes value: kind-dependent value
:var int line: line number
:var int column: column number
"""
| class BandwidthFileToken(collections.namedtuple('BandwidthFileToken', ['kind', 'value', 'line', 'column'])):
| """
:var str kind: the kind of token
:var bytes value: kind-dependent value
:var int line: line number
:var int column: column number
"""
| = mo.end()
line_num += 1
column = mo.end() - line_start
yield BandwidthFileToken('EOF', None, line_num, column)
class BandwidthFileToken(collections.namedtuple('BandwidthFileToken', ['kind', 'value', 'line', 'column'])):
| 64 | 64 | 70 | 27 | 37 | irl/bushel | bushel/bandwidth/file.py | Python | BandwidthFileToken | BandwidthFileToken | 228 | 234 | 228 | 228 | d6b3d2f1b77201fbf6e9cd373eae7fc3f57b5f03 | bigcode/the-stack | train |
3228215a87823eeb82ff6ced | train | class | class BandwidthFile(BaseDocument):
def __init__(self, raw_content):
super().__init__(raw_content)
self.PARSE_FUNCTIONS = dict()
def parse(self):
for line in self.lines():
if item.keyword in self.PARSE_FUNCTIONS:
self.PARSE_FUNCTIONS[line.keyword](item)
... | class BandwidthFile(BaseDocument):
| def __init__(self, raw_content):
super().__init__(raw_content)
self.PARSE_FUNCTIONS = dict()
def parse(self):
for line in self.lines():
if item.keyword in self.PARSE_FUNCTIONS:
self.PARSE_FUNCTIONS[line.keyword](item)
def lines(self, allowed_errors=None)... | self.expected_not_found("space or newline")
elif self.state == 'RELAY-LINE-SP':
if token.kind == 'KEYVALUE':
self.state = 'RELAY-LINE-KV'
return
else:
self.expected_not_found("keyvalue")
raise RuntimeError("Bad state transition")
... | 183 | 183 | 613 | 7 | 176 | irl/bushel | bushel/bandwidth/file.py | Python | BandwidthFile | BandwidthFile | 161 | 225 | 161 | 162 | 2ae8c972325689182fdab61c98de9351dde5f716 | bigcode/the-stack | train |
dd3156af648fceb7fd54a8ba | train | class | class BandwidthFileLineError(enum.Enum):
"""
Enumeration of forgivable errors that may be encountered during parsing of
lines in a bandwidth file.
======================= ===========
Name Description
======================= ===========
SHORT_TERMINATOR A terminator... | class BandwidthFileLineError(enum.Enum):
| """
Enumeration of forgivable errors that may be encountered during parsing of
lines in a bandwidth file.
======================= ===========
Name Description
======================= ===========
SHORT_TERMINATOR A terminator with 4 `=` instead of 5.
... | better docstring
import base64
import collections
import datetime
import enum
import logging
import re
import textwrap
import nacl.signing
import nacl.encoding
from bushel.document import BaseDocument
LOG = logging.getLogger('bushel')
class BandwidthFileLineError(enum.Enum):
| 64 | 64 | 118 | 9 | 55 | irl/bushel | bushel/bandwidth/file.py | Python | BandwidthFileLineError | BandwidthFileLineError | 21 | 35 | 21 | 21 | e3d19cbf27909128797ef24cbf8138207f8d2060 | bigcode/the-stack | train |
e67c6ed6a0c01109be0feb21 | train | class | class YieldTest(unittest.TestCase):
"""Test that regular expressions give the right lists."""
def testSimpleCases(self):
self.assertSequenceEqual(
sre_yield.AllStrings("1(234?|49?)"), ["123", "1234", "14", "149"]
)
self.assertSequenceEqual(sre_yield.AllStrings("asd|def"), ["... | class YieldTest(unittest.TestCase):
| """Test that regular expressions give the right lists."""
def testSimpleCases(self):
self.assertSequenceEqual(
sre_yield.AllStrings("1(234?|49?)"), ["123", "1234", "14", "149"]
)
self.assertSequenceEqual(sre_yield.AllStrings("asd|def"), ["asd", "def"])
self.assertSeq... | #!/usr/bin/env python3
#
# Copyright 2011-2016 Google Inc.
# Copyright 2018-2019 Tim Hatch
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
... | 178 | 256 | 2,286 | 7 | 170 | L3viathan/sre_yield | sre_yield/tests/test_sre_yield.py | Python | YieldTest | YieldTest | 27 | 227 | 27 | 27 | 15f8c35febc0d4be2de1281994abfcd7ed1b2fb4 | bigcode/the-stack | train |
3709c668b72c9f7a44259270 | train | function | def splitAudioFile(inputFilePath, outputFilePath, fileName):
for count in range(3):
resultPath = os.path.join(
outputFilePath, fileName + "_" + str(count) + ".wav")
start, end = audioLength[count]
command = "ffmpeg -ss " + str(start) + " -to " + str(end) + \
" -i " + ... | def splitAudioFile(inputFilePath, outputFilePath, fileName):
| for count in range(3):
resultPath = os.path.join(
outputFilePath, fileName + "_" + str(count) + ".wav")
start, end = audioLength[count]
command = "ffmpeg -ss " + str(start) + " -to " + str(end) + \
" -i " + inputFilePath + " " + resultPath
popen = subprocess.P... | (), "trimAudioSet")
SPLIT_TRIM_AUDIOSET_PATH = os.path.join(os.getcwd(), "splitTrimAudioSet")
audioLength = [[1, 4], [4, 7], [7, 10]]
def splitAudioFile(inputFilePath, outputFilePath, fileName):
| 63 | 64 | 131 | 15 | 48 | itlockit2/smartBabyWatch | splitAudio.py | Python | splitAudioFile | splitAudioFile | 10 | 19 | 10 | 10 | 502dee7ca3f11928b792d067ebf0cb0c3d136122 | bigcode/the-stack | train |
458601c34522c07665f783f1 | train | class | class Ds(AutotoolsPackage):
"""SAOImage DS9 is an astronomical imaging and data visualization
application."""
homepage = "http://ds9.si.edu/"
url = "http://ds9.si.edu/download/source/ds9.8.0.tar.gz"
version('9.8.0', sha256='f3bdb46c1653997202f98c6f76632a4eb444707f4b64c14f8b96863d9c890304')... | class Ds(AutotoolsPackage):
| """SAOImage DS9 is an astronomical imaging and data visualization
application."""
homepage = "http://ds9.si.edu/"
url = "http://ds9.si.edu/download/source/ds9.8.0.tar.gz"
version('9.8.0', sha256='f3bdb46c1653997202f98c6f76632a4eb444707f4b64c14f8b96863d9c890304')
depends_on('autoconf',... | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from os import symlink
from spack import *
class Ds(AutotoolsPackage):
| 68 | 136 | 456 | 8 | 60 | padamson/spack | var/spack/repos/builtin/packages/ds/package.py | Python | Ds | Ds | 11 | 59 | 11 | 11 | 936fe331e0d0a2c6e9b44598228124d59e59743d | bigcode/the-stack | train |
f207070f8b97f63b72d37915 | train | class | class renderbutton:
def __init__(self, tk, *, args=None, kwargs=None):
self.tk =tk
self.value = args if args != None else kwargs
if type(self.value) is str:
pass
elif type(self.value) is dict:
for key, value in self.value.items():
if key == 'co... | class renderbutton:
| def __init__(self, tk, *, args=None, kwargs=None):
self.tk =tk
self.value = args if args != None else kwargs
if type(self.value) is str:
pass
elif type(self.value) is dict:
for key, value in self.value.items():
if key == 'cor':
... | from tkinter import *
params = []
class renderbutton:
| 11 | 64 | 111 | 4 | 7 | JohnnyDev2001/gblue | Behavior/Behavior_button.py | Python | renderbutton | renderbutton | 5 | 19 | 5 | 5 | 66771f7196bf414df8e9f9839a63fe692968ecaf | bigcode/the-stack | train |
c49fef12d883cfac3a8781c9 | train | class | class TransferTicketRequestController(EricaRequestController):
def generate_json(self, pyeric_response: PyericResponse):
response = super().generate_json(pyeric_response)
if pyeric_response.server_response:
response['transfer_ticket'] = get_transfer_ticket_from_xml(pyeric_response.serve... | class TransferTicketRequestController(EricaRequestController):
| def generate_json(self, pyeric_response: PyericResponse):
response = super().generate_json(pyeric_response)
if pyeric_response.server_response:
response['transfer_ticket'] = get_transfer_ticket_from_xml(pyeric_response.server_response)
return response
| : PyericResponse):
response = {}
if self.include_elster_responses:
response['eric_response'] = pyeric_response.eric_response
response['server_response'] = pyeric_response.server_response
return response
class TransferTicketRequestController(EricaRequestController):
| 64 | 64 | 71 | 11 | 52 | punknoir101/erica-1 | erica/erica_legacy/request_processing/requests_controller.py | Python | TransferTicketRequestController | TransferTicketRequestController | 71 | 77 | 71 | 72 | e5bb4a29641029563ff1824093634e38a85c230b | bigcode/the-stack | train |
2f6964413e7140c262be3fa6 | train | class | class EricaRequestController(object):
"""
Generic class to handle any request to the eric api. That is processing the input data,
performing the needed procedures and generating the response. Any request should inherit from this function.
"""
_PYERIC_CONTROLLER = None
def __init__(self, input_... | class EricaRequestController(object):
| """
Generic class to handle any request to the eric api. That is processing the input data,
performing the needed procedures and generating the response. Any request should inherit from this function.
"""
_PYERIC_CONTROLLER = None
def __init__(self, input_data, include_elster_responses: bool =... | RequestData, EstData
SPECIAL_TESTMERKER_IDNR = ['04452397687',
'02259674819',
'04452317681',
'09952417688',
'03352417692',
'03352419681',
'03352417981',
... | 88 | 88 | 295 | 6 | 82 | punknoir101/erica-1 | erica/erica_legacy/request_processing/requests_controller.py | Python | EricaRequestController | EricaRequestController | 33 | 68 | 33 | 33 | 6914a84e172ae1765230e5c8a289990e94e9fdb4 | bigcode/the-stack | train |
019dfc4b25526b77d830fb0a | train | class | class UnlockCodeActivationRequestController(TransferTicketRequestController):
_PYERIC_CONTROLLER = UnlockCodeActivationPyericProcessController
def generate_full_xml(self, use_testmerker):
return elster_xml_generator.generate_full_vast_activation_xml(self.input_data.__dict__,
... | class UnlockCodeActivationRequestController(TransferTicketRequestController):
| _PYERIC_CONTROLLER = UnlockCodeActivationPyericProcessController
def generate_full_xml(self, use_testmerker):
return elster_xml_generator.generate_full_vast_activation_xml(self.input_data.__dict__,
use_testmerker=use_testmerker)
... | ):
response = super().generate_json(pyeric_response)
response["elster_request_id"] = get_antrag_id_from_xml(pyeric_response.server_response)
response["idnr"] = self.input_data.idnr
return response
class UnlockCodeActivationRequestController(TransferTicketRequestController):
| 64 | 64 | 135 | 12 | 51 | punknoir101/erica-1 | erica/erica_legacy/request_processing/requests_controller.py | Python | UnlockCodeActivationRequestController | UnlockCodeActivationRequestController | 155 | 166 | 155 | 155 | 08f33efdde25d3228c914c1859bf919775d90c26 | bigcode/the-stack | train |
acd923dd17fe7b54e82121bd | train | class | class GetBelegeRequestController(EricaRequestController):
"""This serves as an abstract class to implement all request controllers that request belege.
Override the following constants in the subclasses."""
_BELEG_ID_REQUEST_PYERIC_CONTROLLER = BelegIdRequestPyericProcessController
_BELEG_REQUEST_PYERIC... | class GetBelegeRequestController(EricaRequestController):
| """This serves as an abstract class to implement all request controllers that request belege.
Override the following constants in the subclasses."""
_BELEG_ID_REQUEST_PYERIC_CONTROLLER = BelegIdRequestPyericProcessController
_BELEG_REQUEST_PYERIC_CONTROLLER = BelegRequestPyericProcessController
_NEE... | Controller.generate_json(False)
result = CheckTaxNumberPyericController.get_eric_response(full_tax_number)
return CheckTaxNumberRequestController.generate_json(result)
@staticmethod
def _generate_tax_number(state_abbreviation, tax_number):
return est_mapping.generate_electronic_steuernu... | 125 | 125 | 418 | 12 | 112 | punknoir101/erica-1 | erica/erica_legacy/request_processing/requests_controller.py | Python | GetBelegeRequestController | GetBelegeRequestController | 209 | 241 | 209 | 209 | 218641aa9920f7329719969c2a5ed8ad2a7c3a92 | bigcode/the-stack | train |
55dac62a5227d4124e61b28c | train | class | class UnlockCodeRevocationRequestController(TransferTicketRequestController):
_PYERIC_CONTROLLER = UnlockCodeRevocationPyericProcessController
def generate_full_xml(self, use_testmerker):
return elster_xml_generator.generate_full_vast_revocation_xml(self.input_data.__dict__,
... | class UnlockCodeRevocationRequestController(TransferTicketRequestController):
| _PYERIC_CONTROLLER = UnlockCodeRevocationPyericProcessController
def generate_full_xml(self, use_testmerker):
return elster_xml_generator.generate_full_vast_revocation_xml(self.input_data.__dict__,
use_testmerker=use_testmerker)
... | response = super().generate_json(pyeric_response)
response["elster_request_id"] = get_antrag_id_from_xml(pyeric_response.server_response)
response["idnr"] = self.input_data.idnr
return response
class UnlockCodeRevocationRequestController(TransferTicketRequestController):
| 64 | 64 | 125 | 13 | 50 | punknoir101/erica-1 | erica/erica_legacy/request_processing/requests_controller.py | Python | UnlockCodeRevocationRequestController | UnlockCodeRevocationRequestController | 169 | 179 | 169 | 169 | 8d405319c249462171d559c33007e0252b3f84f2 | bigcode/the-stack | train |
95be37114362b856a7817d36 | train | class | class UnlockCodeRequestController(TransferTicketRequestController):
_PYERIC_CONTROLLER = UnlockCodeRequestPyericProcessController
def __init__(self, input_data: UnlockCodeRequestData, include_elster_responses: bool = False):
super().__init__(input_data, include_elster_responses)
def generate_full_... | class UnlockCodeRequestController(TransferTicketRequestController):
| _PYERIC_CONTROLLER = UnlockCodeRequestPyericProcessController
def __init__(self, input_data: UnlockCodeRequestData, include_elster_responses: bool = False):
super().__init__(input_data, include_elster_responses)
def generate_full_xml(self, use_testmerker):
return elster_xml_generator.gener... | icProcessController
def generate_json(self, pyeric_response: PyericResponse):
response = super().generate_json(pyeric_response)
response['pdf'] = base64.b64encode(pyeric_response.pdf)
return response
class UnlockCodeRequestController(TransferTicketRequestController):
| 64 | 64 | 182 | 11 | 52 | punknoir101/erica-1 | erica/erica_legacy/request_processing/requests_controller.py | Python | UnlockCodeRequestController | UnlockCodeRequestController | 135 | 152 | 135 | 135 | 6137072c702827230554c699d329f725518a3af5 | bigcode/the-stack | train |
92099f03357035f19603f8c4 | train | class | class EstValidationRequestController(TransferTicketRequestController):
_PYERIC_CONTROLLER = EstValidationPyericProcessController
def __init__(self, input_data: EstData, include_elster_responses: bool = False):
super().__init__(input_data, include_elster_responses)
def _is_testmerker_used(self):
... | class EstValidationRequestController(TransferTicketRequestController):
| _PYERIC_CONTROLLER = EstValidationPyericProcessController
def __init__(self, input_data: EstData, include_elster_responses: bool = False):
super().__init__(input_data, include_elster_responses)
def _is_testmerker_used(self):
return self.input_data.est_data.person_a_idnr in SPECIAL_TESTMERK... | _IDNR
def generate_json(self, pyeric_response: PyericResponse):
response = {}
if self.include_elster_responses:
response['eric_response'] = pyeric_response.eric_response
response['server_response'] = pyeric_response.server_response
return response
class TransferTic... | 148 | 148 | 496 | 11 | 136 | punknoir101/erica-1 | erica/erica_legacy/request_processing/requests_controller.py | Python | EstValidationRequestController | EstValidationRequestController | 80 | 123 | 80 | 80 | 02b8c3e482382e0baedec94c2bbe4669eea5445c | bigcode/the-stack | train |
88719e29eab1bb81444b12dc | train | class | class GetAddressRequestController(GetBelegeRequestController):
_NEEDED_BELEG_ART = ['VaSt_Pers1']
def generate_json(self, pyeric_response: PyericResponse):
response = super().generate_json(pyeric_response)
response['address'] = get_address_from_xml(pyeric_response.server_response)
retur... | class GetAddressRequestController(GetBelegeRequestController):
| _NEEDED_BELEG_ART = ['VaSt_Pers1']
def generate_json(self, pyeric_response: PyericResponse):
response = super().generate_json(pyeric_response)
response['address'] = get_address_from_xml(pyeric_response.server_response)
return response
| atenpaket')
def _request_decrypted_belege(self, encrypted_belege):
decrypted_belege = DecryptBelegePyericController().get_decrypted_belege(encrypted_belege)
return get_belege_xml(decrypted_belege)
class GetAddressRequestController(GetBelegeRequestController):
| 64 | 64 | 76 | 11 | 53 | punknoir101/erica-1 | erica/erica_legacy/request_processing/requests_controller.py | Python | GetAddressRequestController | GetAddressRequestController | 244 | 250 | 244 | 244 | 3a9a0ab463ade512144c0d76179811d9f0b7a37d | bigcode/the-stack | train |
c10b625d9964b7f66fe506ba | train | class | class CheckTaxNumberRequestController:
"""This handles any request that wants to check if a tax number is valid"""
@staticmethod
def process(state_abbreviation: str, tax_number: str):
try:
full_tax_number = CheckTaxNumberRequestController._generate_tax_number(state_abbreviation.upper(),... | class CheckTaxNumberRequestController:
| """This handles any request that wants to check if a tax number is valid"""
@staticmethod
def process(state_abbreviation: str, tax_number: str):
try:
full_tax_number = CheckTaxNumberRequestController._generate_tax_number(state_abbreviation.upper(), tax_number)
except InvalidBufa... | merker)
def generate_json(self, pyeric_response: PyericResponse):
response = super().generate_json(pyeric_response)
response["elster_request_id"] = get_antrag_id_from_xml(pyeric_response.server_response)
return response
class CheckTaxNumberRequestController:
| 64 | 64 | 194 | 7 | 56 | punknoir101/erica-1 | erica/erica_legacy/request_processing/requests_controller.py | Python | CheckTaxNumberRequestController | CheckTaxNumberRequestController | 182 | 206 | 182 | 182 | 97ff796a794e84d8d8a7e8bee557126128e4f417 | bigcode/the-stack | train |
c28b9f988c5a4a1bf63b1a45 | train | class | class EstRequestController(EstValidationRequestController):
_PYERIC_CONTROLLER = EstPyericProcessController
def generate_json(self, pyeric_response: PyericResponse):
response = super().generate_json(pyeric_response)
response['pdf'] = base64.b64encode(pyeric_response.pdf)
return response... | class EstRequestController(EstValidationRequestController):
| _PYERIC_CONTROLLER = EstPyericProcessController
def generate_json(self, pyeric_response: PyericResponse):
response = super().generate_json(pyeric_response)
response['pdf'] = base64.b64encode(pyeric_response.pdf)
return response
| ker=self._is_testmerker_used())
pyeric_controller = self._PYERIC_CONTROLLER(xml, self.input_data.meta_data.year)
pyeric_response = pyeric_controller.get_eric_response()
return self.generate_json(pyeric_response)
class EstRequestController(EstValidationRequestController):
| 64 | 64 | 72 | 10 | 54 | punknoir101/erica-1 | erica/erica_legacy/request_processing/requests_controller.py | Python | EstRequestController | EstRequestController | 126 | 132 | 126 | 126 | ef018da99b791b89a6b5996594398531bbe84fcf | bigcode/the-stack | train |
e1e1b843620014d53f461948 | train | function | def main(args):
max_depth = args.max_depth
seed = args.seed
model_name = args.model_name
## You can change 'default' experiment name:
mlflow.set_experiment("iris")
## Auto-log sklearn metrics
mlflow.sklearn.autolog(log_models=False)
## Load and split dataset
iris = datasets.load_i... | def main(args):
| max_depth = args.max_depth
seed = args.seed
model_name = args.model_name
## You can change 'default' experiment name:
mlflow.set_experiment("iris")
## Auto-log sklearn metrics
mlflow.sklearn.autolog(log_models=False)
## Load and split dataset
iris = datasets.load_iris()
x_trai... | MENTS_TXT = "{}/../requirements.txt".format(CURRENT_DIR)
def get_parser():
p = ArgumentParser(description="Run model prediction on a given input")
p.add_argument(
"--seed",
type=int,
default=42,
)
p.add_argument("--max-depth", type=int, default=6)
p.add_argument("--model-na... | 96 | 96 | 323 | 4 | 91 | atemate/case-mlflow | iris-sklearn/src/train.py | Python | main | main | 28 | 68 | 28 | 28 | cfc5ab53ac973b66a687906a207db4bc726788b1 | bigcode/the-stack | train |
edef8e247dbcb48573eff03c | train | function | def get_parser():
p = ArgumentParser(description="Run model prediction on a given input")
p.add_argument(
"--seed",
type=int,
default=42,
)
p.add_argument("--max-depth", type=int, default=6)
p.add_argument("--model-name", default=os.getenv("MY_MODEL_NAME", "iris"))
return... | def get_parser():
| p = ArgumentParser(description="Run model prediction on a given input")
p.add_argument(
"--seed",
type=int,
default=42,
)
p.add_argument("--max-depth", type=int, default=6)
p.add_argument("--model-name", default=os.getenv("MY_MODEL_NAME", "iris"))
return p
| pd
from mlflow.models.signature import infer_signature
from sklearn import datasets
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
CURRENT_DIR = os.path.dirname(__file__)
REQUIREMENTS_TXT = "{}/../requirements.txt".format(CURRENT_DIR)
def get_parser():
| 64 | 64 | 77 | 4 | 60 | atemate/case-mlflow | iris-sklearn/src/train.py | Python | get_parser | get_parser | 16 | 25 | 16 | 16 | da37f94d855b59c8e230d1692009d165840f63d6 | bigcode/the-stack | train |
4bf883abe8616a47e3991c18 | train | function | def test_glr_recovery_custom_unsuccessful():
"""
Test unsuccessful error recovery.
"""
def custom_recovery(context, error):
return None, None
parser = GLRParser(g, actions=actions, error_recovery=custom_recovery)
with pytest.raises(ParseError) as e:
parser.parse('1 + 5 8 - 2')... | def test_glr_recovery_custom_unsuccessful():
| """
Test unsuccessful error recovery.
"""
def custom_recovery(context, error):
return None, None
parser = GLRParser(g, actions=actions, error_recovery=custom_recovery)
with pytest.raises(ParseError) as e:
parser.parse('1 + 5 8 - 2')
error = e.value
assert error.locati... | 1 + 5 8 - 2')
assert len(parser.errors) == 1
assert len(results) == 5
assert len(set(results)) == 2
assert -4 in results
assert 0 in results
def test_glr_recovery_custom_unsuccessful():
| 64 | 64 | 96 | 11 | 52 | Hyldrean/parglare | tests/func/parsing/test_glr_error_recovery.py | Python | test_glr_recovery_custom_unsuccessful | test_glr_recovery_custom_unsuccessful | 105 | 119 | 105 | 105 | 17ac03904ec40f381a424dd3902d93c0ad134266 | bigcode/the-stack | train |
2bd6b329d9f6fafed4cd4151 | train | function | def test_glr_recovery_custom_new_token():
"""
Test that custom recovery that introduces new token works.
"""
def custom_recovery(context, error):
# Here we will introduce missing operation token
return Token(g.get_terminal('-'), '-', length=0), None
parser = GLRParser(g, actions=ac... | def test_glr_recovery_custom_new_token():
| """
Test that custom recovery that introduces new token works.
"""
def custom_recovery(context, error):
# Here we will introduce missing operation token
return Token(g.get_terminal('-'), '-', length=0), None
parser = GLRParser(g, actions=actions, error_recovery=custom_recovery)
... | assert len(parser.errors) == 1
assert len(results) == 2
assert len(set(results)) == 1
# Calculate results should be '1 + 5 - 2'
assert results[0] == 4
def test_glr_recovery_custom_new_token():
| 64 | 64 | 138 | 10 | 53 | Hyldrean/parglare | tests/func/parsing/test_glr_error_recovery.py | Python | test_glr_recovery_custom_new_token | test_glr_recovery_custom_new_token | 85 | 102 | 85 | 85 | e0de4f39eb48ba1bd0ec1a75168a667753a46179 | bigcode/the-stack | train |
9e7b298e5f04cff70c8a7fd1 | train | function | def test_glr_recovery_custom_new_position():
"""
Test that custom recovery that increment position works.
"""
def custom_recovery(context, error):
# This recovery will just skip over erroneous part of input '& 89'.
return None, context.position + 4
parser = GLRParser(g, actions=act... | def test_glr_recovery_custom_new_position():
| """
Test that custom recovery that increment position works.
"""
def custom_recovery(context, error):
# This recovery will just skip over erroneous part of input '& 89'.
return None, context.position + 4
parser = GLRParser(g, actions=actions, error_recovery=custom_recovery,
... | # There are 5 trees for '1 + 2 + 3 - 5'
# All results are the same
assert len(results) == 5
assert len(set(results)) == 1
assert 1 in set(results)
def test_glr_recovery_custom_new_position():
| 64 | 64 | 154 | 10 | 54 | Hyldrean/parglare | tests/func/parsing/test_glr_error_recovery.py | Python | test_glr_recovery_custom_new_position | test_glr_recovery_custom_new_position | 64 | 82 | 64 | 64 | 39e2d950d190eb10cba658b5fe1b0256a5338bd3 | bigcode/the-stack | train |
5f7dbc2f7a091be29fd96ffe | train | function | def test_glr_recovery_default():
"""
Test default error recovery in GLR parsing. Default recovery should report
the error, drop current input at position and try to recover.
In case of multiple subsequent errouneous chars only one error should be
reported.
"""
parser = GLRParser(g, actions=a... | def test_glr_recovery_default():
| """
Test default error recovery in GLR parsing. Default recovery should report
the error, drop current input at position and try to recover.
In case of multiple subsequent errouneous chars only one error should be
reported.
"""
parser = GLRParser(g, actions=actions, error_recovery=True, debu... | lambda _, nodes: nodes[0] * nodes[2],
lambda _, nodes: nodes[0] / nodes[2],
lambda _, nodes: nodes[0] ** nodes[2],
pass_inner,
pass_single],
"number": lambda _, value: float(value),
}
g = Grammar.from_string(grammar)
def test_glr_recovery_default():
| 76 | 76 | 255 | 8 | 68 | Hyldrean/parglare | tests/func/parsing/test_glr_error_recovery.py | Python | test_glr_recovery_default | test_glr_recovery_default | 35 | 61 | 35 | 35 | b98a934cb913ce9245ae508722a2f9aab1c684a9 | bigcode/the-stack | train |
6ce9d03919c6977d42570f9d | train | class | class DelayedShuffleProxyActor(ShuffleProxyActor):
def _start_successors(self):
_write_state_file('SHUFFLE_ALL_PRED_FINISHED_FILE')
if 'SHUFFLE_START_SUCC_FILE' in os.environ:
while not os.path.exists(os.environ['SHUFFLE_START_SUCC_FILE']):
self.ctx.sleep(0.1)
s... | class DelayedShuffleProxyActor(ShuffleProxyActor):
| def _start_successors(self):
_write_state_file('SHUFFLE_ALL_PRED_FINISHED_FILE')
if 'SHUFFLE_START_SUCC_FILE' in os.environ:
while not os.path.exists(os.environ['SHUFFLE_START_SUCC_FILE']):
self.ctx.sleep(0.1)
super(DelayedShuffleProxyActor, self)._start_success... | 1)
super(DelayedOperandActor, self)._on_ready()
def _on_finished(self):
super(DelayedOperandActor, self)._on_finished()
if self._is_terminal:
_write_state_file('OP_TERMINATE_STATE_FILE')
class DelayedShuffleProxyActor(ShuffleProxyActor):
| 64 | 64 | 184 | 11 | 53 | sighingnow/mars | mars/scheduler/tests/integrated/op_delayer.py | Python | DelayedShuffleProxyActor | DelayedShuffleProxyActor | 49 | 67 | 49 | 49 | b4ff12ffe562286f67bb6dd4a67d3a20611ab974 | bigcode/the-stack | train |
ec5d0523aef5ef81ba9157d0 | train | function | def _write_state_file(var_name):
if var_name in os.environ:
try:
open(os.environ[var_name], 'w').close()
except OSError:
pass
os.environ.pop(var_name)
| def _write_state_file(var_name):
| if var_name in os.environ:
try:
open(os.environ[var_name], 'w').close()
except OSError:
pass
os.environ.pop(var_name)
| OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
from mars.scheduler.operands import OperandActor, ShuffleProxyActor
from mars.actors.core import register_actor_implementation
def _write_state_file(v... | 64 | 64 | 46 | 8 | 55 | sighingnow/mars | mars/scheduler/tests/integrated/op_delayer.py | Python | _write_state_file | _write_state_file | 21 | 27 | 21 | 21 | cdafab4dbefb14b0f986c503c92d8bbad33de09c | bigcode/the-stack | train |
973bb3d8fed1222a4af4997f | train | class | class DelayedOperandActor(OperandActor):
def _on_ready(self):
for ctrl_file_var in ('OP_DELAY_STATE_FILE', 'SHUFFLE_ALL_PRED_FINISHED_FILE',
'SHUFFLE_ALL_SUCC_FINISH_FILE'):
if ctrl_file_var in os.environ and os.path.exists(os.environ[ctrl_file_var]):
... | class DelayedOperandActor(OperandActor):
| def _on_ready(self):
for ctrl_file_var in ('OP_DELAY_STATE_FILE', 'SHUFFLE_ALL_PRED_FINISHED_FILE',
'SHUFFLE_ALL_SUCC_FINISH_FILE'):
if ctrl_file_var in os.environ and os.path.exists(os.environ[ctrl_file_var]):
self.ctx.sleep(1)
while 'SHUFF... | .actors.core import register_actor_implementation
def _write_state_file(var_name):
if var_name in os.environ:
try:
open(os.environ[var_name], 'w').close()
except OSError:
pass
os.environ.pop(var_name)
class DelayedOperandActor(OperandActor):
| 64 | 64 | 172 | 9 | 55 | sighingnow/mars | mars/scheduler/tests/integrated/op_delayer.py | Python | DelayedOperandActor | DelayedOperandActor | 30 | 46 | 30 | 30 | 3a1056071d529874e1e1dff26baffa372f5d0f65 | bigcode/the-stack | train |
1fb9933d413d92d6d88180e2 | train | class | class AudioProvider:
"""
Base class for all other providers. Provides some common functionality.
Handles the yt-dlp audio handler.
"""
def __init__(
self,
output_format: str = "mp3",
cookie_file: Optional[str] = None,
search_query: Optional[str] = None,
filte... | class AudioProvider:
| """
Base class for all other providers. Provides some common functionality.
Handles the yt-dlp audio handler.
"""
def __init__(
self,
output_format: str = "mp3",
cookie_file: Optional[str] = None,
search_query: Optional[str] = None,
filter_results: bool = Tru... | """
Base audio provider module.
"""
from typing import Dict, Optional
from yt_dlp import YoutubeDL
from spotdl.types import Song
from spotdl.utils.config import get_temp_path
class AudioProviderError(Exception):
"""
Base class for all exceptions related to audio searching/downloading.
"""
class YTDLL... | 206 | 214 | 715 | 4 | 202 | spotDL/spotdl-v4 | spotdl/providers/audio/base.py | Python | AudioProvider | AudioProvider | 43 | 162 | 43 | 43 | 0b965d3c5cbf478248a508f25f909aab609fd636 | bigcode/the-stack | train |
26500298e4ea4a32dc63d4f6 | train | class | class AudioProviderError(Exception):
"""
Base class for all exceptions related to audio searching/downloading.
"""
| class AudioProviderError(Exception):
| """
Base class for all exceptions related to audio searching/downloading.
"""
| """
Base audio provider module.
"""
from typing import Dict, Optional
from yt_dlp import YoutubeDL
from spotdl.types import Song
from spotdl.utils.config import get_temp_path
class AudioProviderError(Exception):
| 45 | 64 | 23 | 6 | 38 | spotDL/spotdl-v4 | spotdl/providers/audio/base.py | Python | AudioProviderError | AudioProviderError | 13 | 16 | 13 | 13 | 47fbfce340d9ac7f2e30bad6f1232df8d39a0174 | bigcode/the-stack | train |
ca54aede4acd91f3b2a299f9 | train | class | class YTDLLogger:
"""
Custom YT-dlp logger.
"""
def debug(self, msg): # pylint: disable=R0201
"""
YTDL uses this to print debug messages.
"""
pass # pylint: disable=W0107
def warning(self, msg): # pylint: disable=R0201
"""
YTDL uses this to print ... | class YTDLLogger:
| """
Custom YT-dlp logger.
"""
def debug(self, msg): # pylint: disable=R0201
"""
YTDL uses this to print debug messages.
"""
pass # pylint: disable=W0107
def warning(self, msg): # pylint: disable=R0201
"""
YTDL uses this to print warnings.
... | .
"""
from typing import Dict, Optional
from yt_dlp import YoutubeDL
from spotdl.types import Song
from spotdl.utils.config import get_temp_path
class AudioProviderError(Exception):
"""
Base class for all exceptions related to audio searching/downloading.
"""
class YTDLLogger:
| 63 | 64 | 139 | 6 | 57 | spotDL/spotdl-v4 | spotdl/providers/audio/base.py | Python | YTDLLogger | YTDLLogger | 19 | 40 | 19 | 19 | 0f3bb4c0bd81a3cf35041672b0cd065a5ddd4479 | bigcode/the-stack | train |
d51fac0ea82235b196c7bda7 | train | class | class _DefaultDistributionContext(object):
"""Context manager setting the default `tf.distribute.Strategy`."""
__slots__ = ["_var_creator_scope", "_strategy", "_nested_count"]
def __init__(self, strategy):
def creator(next_creator, **kwargs):
_require_strategy_scope_strategy(strategy)
return ne... | class _DefaultDistributionContext(object):
| """Context manager setting the default `tf.distribute.Strategy`."""
__slots__ = ["_var_creator_scope", "_strategy", "_nested_count"]
def __init__(self, strategy):
def creator(next_creator, **kwargs):
_require_strategy_scope_strategy(strategy)
return next_creator(**kwargs)
self._var_creator... | _creating_default_strategy_singleton:
raise RuntimeError("Should only create a single instance of "
"_DefaultDistributionStrategy")
super(_DefaultDistributionStrategy, self).__init__(
_DefaultDistributionExtended(self))
def __deepcopy__(self, memo):
del memo
raise ... | 84 | 84 | 283 | 7 | 77 | nyiritb/tensorflow | tensorflow/python/distribute/distribute_lib.py | Python | _DefaultDistributionContext | _DefaultDistributionContext | 3,035 | 3,069 | 3,035 | 3,035 | 9270758ea9995ea9383fd2c7cd2e1219664440d1 | bigcode/the-stack | train |
e047bea42e5fff1c85c01749 | train | function | def require_replica_context(replica_ctx):
"""Verify in `replica_ctx` replica context."""
context = _get_per_thread_mode()
if context.replica_context is replica_ctx: return
# We have an error to report, figure out the right message.
if context.replica_context is None:
raise RuntimeError("Need to be inside ... | def require_replica_context(replica_ctx):
| """Verify in `replica_ctx` replica context."""
context = _get_per_thread_mode()
if context.replica_context is replica_ctx: return
# We have an error to report, figure out the right message.
if context.replica_context is None:
raise RuntimeError("Need to be inside `call_for_each_replica()`")
if context.s... | 'Need to be inside "with strategy.scope()" for %s' %
(strategy,))
else:
raise RuntimeError(
"Mixing different tf.distribute.Strategy objects: %s is not %s" %
(context.strategy, strategy))
def require_replica_context(replica_ctx):
| 64 | 64 | 152 | 9 | 55 | nyiritb/tensorflow | tensorflow/python/distribute/distribute_lib.py | Python | require_replica_context | require_replica_context | 327 | 339 | 327 | 327 | b15df5eed2c56586c1610765637aef9876aeb8b3 | bigcode/the-stack | train |
8369fc551279f60aceccd2a1 | train | function | def get_update_replica_id():
"""Get the current device if in a `tf.distribute.Strategy.update()` call."""
try:
return _update_replica_id.current
except AttributeError:
return None
| def get_update_replica_id():
| """Get the current device if in a `tf.distribute.Strategy.update()` call."""
try:
return _update_replica_id.current
except AttributeError:
return None
| lib
from tensorflow.python.util.deprecation import deprecated
from tensorflow.python.util.tf_export import tf_export
from tensorflow.tools.docs import doc_controls
# ------------------------------------------------------------------------------
# Context tracking whether in a strategy.update() or .update_non_slot() c... | 64 | 64 | 47 | 7 | 57 | nyiritb/tensorflow | tensorflow/python/distribute/distribute_lib.py | Python | get_update_replica_id | get_update_replica_id | 242 | 247 | 242 | 242 | 1ec5401709501748e6ad351b335b13ea1ff10116 | bigcode/the-stack | train |
8718342d94a743e20d901c6d | train | function | def _require_strategy_scope_strategy(strategy):
"""Verify in a `strategy.scope()` in this thread."""
context = _get_per_thread_mode()
if context.strategy is strategy: return
_wrong_strategy_scope(strategy, context)
| def _require_strategy_scope_strategy(strategy):
| """Verify in a `strategy.scope()` in this thread."""
context = _get_per_thread_mode()
if context.strategy is strategy: return
_wrong_strategy_scope(strategy, context)
| ReplicaContexts with the same tf.distribute.Strategy.
raise RuntimeError("Mismatching ReplicaContext.")
raise RuntimeError(
"Mismatching tf.distribute.Strategy objects: %s is not %s." %
(context.strategy, replica_ctx.strategy))
def _require_strategy_scope_strategy(strategy):
| 64 | 64 | 48 | 8 | 56 | nyiritb/tensorflow | tensorflow/python/distribute/distribute_lib.py | Python | _require_strategy_scope_strategy | _require_strategy_scope_strategy | 342 | 346 | 342 | 342 | 63b12d1bb45e9f6530f660c6e93097645ed076a9 | bigcode/the-stack | train |
9e604000fc0e97d7d1e84927 | train | class | class _DefaultDistributionStrategy(StrategyV1):
"""Default `tf.distribute.Strategy` if none is explicitly selected."""
def __init__(self):
if not _creating_default_strategy_singleton:
raise RuntimeError("Should only create a single instance of "
"_DefaultDistributionStrategy")
... | class _DefaultDistributionStrategy(StrategyV1):
| """Default `tf.distribute.Strategy` if none is explicitly selected."""
def __init__(self):
if not _creating_default_strategy_singleton:
raise RuntimeError("Should only create a single instance of "
"_DefaultDistributionStrategy")
super(_DefaultDistributionStrategy, self).__in... | """Returns the destinations for batch all-reduce."""
if isinstance(x, ops.Tensor):
# If this is a one device strategy.
return x.device
else:
return x
# ------------------------------------------------------------------------------
_creating_default_strategy_singleton = False
class _DefaultDistribu... | 64 | 64 | 113 | 10 | 53 | nyiritb/tensorflow | tensorflow/python/distribute/distribute_lib.py | Python | _DefaultDistributionStrategy | _DefaultDistributionStrategy | 3,019 | 3,032 | 3,019 | 3,019 | 0b5dc0ab1ae55b5e1070385cc9b7886e59543c50 | bigcode/the-stack | train |
904ac9f294d8855614c08d16 | train | class | @tf_export("distribute.InputOptions", v1=[])
class InputOptions(
collections.namedtuple("InputOptions", [
"experimental_prefetch_to_device",
])):
"""Run options for `experimental_distribute_dataset(s_from_function)`.
This can be used to hold some strategy specific configs.
```python
# Setup TP... | @tf_export("distribute.InputOptions", v1=[])
class InputOptions(
collections.namedtuple("InputOptions", [
"experimental_prefetch_to_device",
])):
| """Run options for `experimental_distribute_dataset(s_from_function)`.
This can be used to hold some strategy specific configs.
```python
# Setup TPUStrategy
resolver = tf.distribute.cluster_resolver.TPUClusterResolver(tpu='')
tf.config.experimental_connect_to_cluster(resolver)
tf.tpu.experimental.initi... | experimental_enable_dynamic_batch_size=True,
experimental_bucketizing_dynamic_shape=False):
return super(RunOptions,
cls).__new__(cls, experimental_enable_dynamic_batch_size,
experimental_bucketizing_dynamic_shape)
@tf_export("distribute.InputOptions", v... | 79 | 79 | 265 | 37 | 42 | nyiritb/tensorflow | tensorflow/python/distribute/distribute_lib.py | Python | InputOptions | InputOptions | 615 | 648 | 615 | 619 | c1add2739c7ca3d3c6553da517be49fec4ab5ad1 | bigcode/the-stack | train |
19f6d4edaa5eb1d76475752f | train | class | class StrategyBase(object):
"""A state & compute distribution policy on a list of devices.
See [the guide](https://www.tensorflow.org/guide/distributed_training)
for overview and examples. See `tf.distribute.StrategyExtended` and
[`tf.distribute`](https://www.tensorflow.org/api_docs/python/tf/distribute)
for... | class StrategyBase(object):
| """A state & compute distribution policy on a list of devices.
See [the guide](https://www.tensorflow.org/guide/distributed_training)
for overview and examples. See `tf.distribute.StrategyExtended` and
[`tf.distribute`](https://www.tensorflow.org/api_docs/python/tf/distribute)
for a glossory of concepts ment... |
# Setup TPUStrategy
resolver = tf.distribute.cluster_resolver.TPUClusterResolver(tpu='')
tf.config.experimental_connect_to_cluster(resolver)
tf.tpu.experimental.initialize_tpu_system(resolver)
strategy = tf.distribute.TPUStrategy(resolver)
dataset = tf.data.Dataset.range(16)
distributed_dataset_on_host ... | 256 | 256 | 9,709 | 5 | 250 | nyiritb/tensorflow | tensorflow/python/distribute/distribute_lib.py | Python | StrategyBase | StrategyBase | 657 | 1,577 | 657 | 657 | bfaa28bba5668d3c5b3164215cb6326f8fb66e29 | bigcode/the-stack | train |
3a947b90e15b9b7deb9086a3 | train | function | def _batch_reduce_destination(x):
"""Returns the destinations for batch all-reduce."""
if isinstance(x, ops.Tensor):
# If this is a one device strategy.
return x.device
else:
return x
| def _batch_reduce_destination(x):
| """Returns the destinations for batch all-reduce."""
if isinstance(x, ops.Tensor):
# If this is a one device strategy.
return x.device
else:
return x
| was needed.
# * When constructing a graph, it could batch up all reduction requests up
# to that point that the first result is needed. Most likely this can be
# implemented in terms of `merge_call()` and `batch_reduce_to()`.
def _batch_reduce_destination(x):
| 64 | 64 | 48 | 7 | 57 | nyiritb/tensorflow | tensorflow/python/distribute/distribute_lib.py | Python | _batch_reduce_destination | _batch_reduce_destination | 3,004 | 3,010 | 3,004 | 3,004 | 375efe27ad65658e3b2d6ea131ffa7ea1d81d5eb | bigcode/the-stack | train |
88902de44a3ddcf12cf5ce6e | train | class | @tf_export("distribute.StrategyExtended", v1=[])
class StrategyExtendedV2(object):
"""Additional APIs for algorithms that need to be distribution-aware.
Note: For most usage of `tf.distribute.Strategy`, there should be no need to
call these methods, since TensorFlow libraries (such as optimizers) already
call ... | @tf_export("distribute.StrategyExtended", v1=[])
class StrategyExtendedV2(object):
| """Additional APIs for algorithms that need to be distribution-aware.
Note: For most usage of `tf.distribute.Strategy`, there should be no need to
call these methods, since TensorFlow libraries (such as optimizers) already
call these methods when needed on your behalf.
Some common use cases of functions on... | sync), or `Tensor` (if running on a
single replica).
"""
return super(StrategyV1, self).experimental_run(
fn, input_iterator)
def reduce(self, reduce_op, value, axis=None):
return super(StrategyV1, self).reduce(reduce_op, value, axis)
reduce.__doc__ = StrategyBase.reduce.__doc__
def ... | 256 | 256 | 5,983 | 21 | 235 | nyiritb/tensorflow | tensorflow/python/distribute/distribute_lib.py | Python | StrategyExtendedV2 | StrategyExtendedV2 | 1,995 | 2,611 | 1,995 | 1,996 | 0c2bdee72bc2686de9e5e83838090dca710bcdac | bigcode/the-stack | train |
10158d9e73c491aabadeea66 | train | class | @tf_export("distribute.ReplicaContext")
class ReplicaContext(object):
"""`tf.distribute.Strategy` API when in a replica context.
You can use `tf.distribute.get_replica_context` to get an instance of
`ReplicaContext`. This should be inside your replicated step function, such
as in a `tf.distribute.Strategy.run`... | @tf_export("distribute.ReplicaContext")
class ReplicaContext(object):
| """`tf.distribute.Strategy` API when in a replica context.
You can use `tf.distribute.get_replica_context` to get an instance of
`ReplicaContext`. This should be inside your replicated step function, such
as in a `tf.distribute.Strategy.run` call.
"""
def __init__(self, strategy, replica_id_in_sync_group)... | # A note about the difference between the context managers
# `ReplicaContext` (defined here) and `_CurrentDistributionContext`
# (defined above) used by `tf.distribute.Strategy.scope()`:
#
# * a ReplicaContext is only present during a `run()`
# call (except during a `merge_run` call) and in such a scope it
# will b... | 256 | 256 | 1,579 | 16 | 240 | nyiritb/tensorflow | tensorflow/python/distribute/distribute_lib.py | Python | ReplicaContext | ReplicaContext | 2,825 | 2,991 | 2,825 | 2,826 | 3e48ee489858b03e7312621a80d0261a3e7141b2 | bigcode/the-stack | train |
8461a50176cf128b7749a74c | train | class | class _CurrentDistributionContext(object):
"""Context manager setting the current `tf.distribute.Strategy`.
Also: overrides the variable creator and optionally the current device.
"""
def __init__(self,
strategy,
var_creator_scope,
var_scope=None,
de... | class _CurrentDistributionContext(object):
| """Context manager setting the current `tf.distribute.Strategy`.
Also: overrides the variable creator and optionally the current device.
"""
def __init__(self,
strategy,
var_creator_scope,
var_scope=None,
default_device=None):
self._context = dis... | context.strategy, replica_ctx.strategy))
def _require_strategy_scope_strategy(strategy):
"""Verify in a `strategy.scope()` in this thread."""
context = _get_per_thread_mode()
if context.strategy is strategy: return
_wrong_strategy_scope(strategy, context)
def _require_strategy_scope_extended(extended):
""... | 154 | 154 | 516 | 7 | 146 | nyiritb/tensorflow | tensorflow/python/distribute/distribute_lib.py | Python | _CurrentDistributionContext | _CurrentDistributionContext | 363 | 429 | 363 | 363 | 57a431c7c58ffd6e8ac107432bbfe79a21f71fa1 | bigcode/the-stack | train |
12b4b03f02111df96235a53f | train | function | @tf_export(v1=["distribute.get_loss_reduction"])
def get_loss_reduction():
"""`tf.distribute.ReduceOp` corresponding to the last loss reduction.
This is used to decide whether loss should be scaled in optimizer (used only
for estimator + v1 optimizer use case).
Returns:
`tf.distribute.ReduceOp` correspond... | @tf_export(v1=["distribute.get_loss_reduction"])
def get_loss_reduction():
| """`tf.distribute.ReduceOp` corresponding to the last loss reduction.
This is used to decide whether loss should be scaled in optimizer (used only
for estimator + v1 optimizer use case).
Returns:
`tf.distribute.ReduceOp` corresponding to the last loss reduction for
estimator and v1 optimizer use case.... | self._replica_id
def __exit__(self, exception_type, exception_value, traceback):
del exception_type, exception_value, traceback
_update_replica_id.current = self._old_replica_id
# ------------------------------------------------------------------------------
# Public utility functions.
@tf_export(v1=["dis... | 73 | 73 | 244 | 19 | 54 | nyiritb/tensorflow | tensorflow/python/distribute/distribute_lib.py | Python | get_loss_reduction | get_loss_reduction | 272 | 291 | 272 | 273 | 3fdf63f663f02ba8d86c963c4b54de527c1d6a4d | bigcode/the-stack | train |
e06f7c23bce297e085ea2503 | train | function | def _wrong_strategy_scope(strategy, context):
# Figure out the right error message.
if not distribution_strategy_context.has_strategy():
raise RuntimeError(
'Need to be inside "with strategy.scope()" for %s' %
(strategy,))
else:
raise RuntimeError(
"Mixing different tf.distribute.S... | def _wrong_strategy_scope(strategy, context):
# Figure out the right error message.
| if not distribution_strategy_context.has_strategy():
raise RuntimeError(
'Need to be inside "with strategy.scope()" for %s' %
(strategy,))
else:
raise RuntimeError(
"Mixing different tf.distribute.Strategy objects: %s is not %s" %
(context.strategy, strategy))
| :
_wrong_strategy_scope(strategy, context)
assert cross_replica is None
raise RuntimeError("Method requires being in cross-replica context, use "
"get_replica_context().merge_call()")
def _wrong_strategy_scope(strategy, context):
# Figure out the right error message.
| 64 | 64 | 87 | 18 | 46 | nyiritb/tensorflow | tensorflow/python/distribute/distribute_lib.py | Python | _wrong_strategy_scope | _wrong_strategy_scope | 315 | 324 | 315 | 316 | bb93d2f93853ec98672e66704bef01b34b494d15 | bigcode/the-stack | train |
34e18c6469fba23775747f67 | train | class | @tf_export("distribute.InputReplicationMode")
class InputReplicationMode(enum.Enum):
"""Replication mode for input function.
* `PER_WORKER`: The input function will be called on each worker
independently, creating as many input pipelines as number of workers.
Replicas will dequeue from the local Dataset on... | @tf_export("distribute.InputReplicationMode")
class InputReplicationMode(enum.Enum):
| """Replication mode for input function.
* `PER_WORKER`: The input function will be called on each worker
independently, creating as many input pipelines as number of workers.
Replicas will dequeue from the local Dataset on their worker.
`tf.distribute.Strategy` doesn't manage any state sharing between ... | ("Variable scope nesting error: move call to "
"tf.distribute.set_strategy() out of `with` scope."),
e)
_pop_per_thread_mode()
# TODO(yuefengz): add more replication modes.
@tf_export("distribute.InputReplicationMode")
class InputReplicationMode(enum.Enum):
| 64 | 64 | 101 | 17 | 47 | nyiritb/tensorflow | tensorflow/python/distribute/distribute_lib.py | Python | InputReplicationMode | InputReplicationMode | 433 | 443 | 433 | 434 | 323c017c58b2c0978eb3d476c5d4d3b720ab2036 | bigcode/the-stack | train |
9da774a3df4d20b58e2b16ca | train | function | def _require_cross_replica_or_default_context_extended(extended):
"""Verify in cross-replica context."""
context = _get_per_thread_mode()
cross_replica = context.cross_replica_context
if cross_replica is not None and cross_replica.extended is extended:
return
if context is _get_default_replica_mode():
... | def _require_cross_replica_or_default_context_extended(extended):
| """Verify in cross-replica context."""
context = _get_per_thread_mode()
cross_replica = context.cross_replica_context
if cross_replica is not None and cross_replica.extended is extended:
return
if context is _get_default_replica_mode():
return
strategy = extended._container_strategy() # pylint: dis... | UM or
last_reduction == loss_reduction.ReductionV2.SUM):
return reduce_util.ReduceOp.SUM
return reduce_util.ReduceOp.MEAN
# ------------------------------------------------------------------------------
# Internal API for validating the current thread mode
def _require_cross_replica_or_default_context_ext... | 64 | 64 | 162 | 13 | 50 | nyiritb/tensorflow | tensorflow/python/distribute/distribute_lib.py | Python | _require_cross_replica_or_default_context_extended | _require_cross_replica_or_default_context_extended | 298 | 312 | 298 | 298 | 1b03c7deaf9237701444fa983992e77bb5287426 | bigcode/the-stack | train |
345696f8baa5b1cfbaa46697 | train | class | class UpdateContext(object):
"""Context manager when you are in `update()` or `update_non_slot()`."""
__slots__ = ["_replica_id", "_old_replica_id"]
def __init__(self, replica_id):
self._replica_id = replica_id
self._old_replica_id = None
def __enter__(self):
self._old_replica_id = get_update_rep... | class UpdateContext(object):
| """Context manager when you are in `update()` or `update_non_slot()`."""
__slots__ = ["_replica_id", "_old_replica_id"]
def __init__(self, replica_id):
self._replica_id = replica_id
self._old_replica_id = None
def __enter__(self):
self._old_replica_id = get_update_replica_id()
_update_replica... | _slot() call.
_update_replica_id = threading.local()
def get_update_replica_id():
"""Get the current device if in a `tf.distribute.Strategy.update()` call."""
try:
return _update_replica_id.current
except AttributeError:
return None
class UpdateContext(object):
| 64 | 64 | 145 | 5 | 58 | nyiritb/tensorflow | tensorflow/python/distribute/distribute_lib.py | Python | UpdateContext | UpdateContext | 250 | 265 | 250 | 250 | 10b8565cefc2f24d89f93b9c6543d39bc9f9c4c7 | bigcode/the-stack | train |
8690c6573fc6070f0c5b4d05 | train | class | @tf_export("distribute.InputContext")
class InputContext(object):
"""A class wrapping information needed by an input function.
This is a context class that is passed to the user's input function and
contains information about the compute replicas and input pipelines. The
number of compute replicas (in sync tra... | @tf_export("distribute.InputContext")
class InputContext(object):
| """A class wrapping information needed by an input function.
This is a context class that is passed to the user's input function and
contains information about the compute replicas and input pipelines. The
number of compute replicas (in sync training) helps compute the local batch
size from the desired globa... | , traceback)
except RuntimeError as e:
six.raise_from(
RuntimeError("Variable scope nesting error: move call to "
"tf.distribute.set_strategy() out of `with` scope."),
e)
_pop_per_thread_mode()
# TODO(yuefengz): add more replication modes.
@tf_export(... | 180 | 180 | 602 | 14 | 166 | nyiritb/tensorflow | tensorflow/python/distribute/distribute_lib.py | Python | InputContext | InputContext | 446 | 516 | 446 | 447 | 23ca2874e4267663b2baa4d0c4c78a5c49bed0e1 | bigcode/the-stack | train |
0cbbe54297d28810da3420b4 | train | function | def _require_strategy_scope_extended(extended):
"""Verify in a `distribution_strategy.scope()` in this thread."""
context = _get_per_thread_mode()
if context.strategy.extended is extended: return
# Report error.
strategy = extended._container_strategy() # pylint: disable=protected-access
_wrong_strategy_sc... | def _require_strategy_scope_extended(extended):
| """Verify in a `distribution_strategy.scope()` in this thread."""
context = _get_per_thread_mode()
if context.strategy.extended is extended: return
# Report error.
strategy = extended._container_strategy() # pylint: disable=protected-access
_wrong_strategy_scope(strategy, context)
| context.strategy, replica_ctx.strategy))
def _require_strategy_scope_strategy(strategy):
"""Verify in a `strategy.scope()` in this thread."""
context = _get_per_thread_mode()
if context.strategy is strategy: return
_wrong_strategy_scope(strategy, context)
def _require_strategy_scope_extended(extended):
| 64 | 64 | 74 | 9 | 55 | nyiritb/tensorflow | tensorflow/python/distribute/distribute_lib.py | Python | _require_strategy_scope_extended | _require_strategy_scope_extended | 349 | 355 | 349 | 349 | 98aa3bbb989d00d3c06208cad81b2711aaeb9ab7 | bigcode/the-stack | train |
f8e37bcf569be7aa4df4fa07 | train | class | @tf_export(v1=["distribute.StrategyExtended"]) # pylint: disable=missing-docstring
class StrategyExtendedV1(StrategyExtendedV2):
__doc__ = StrategyExtendedV2.__doc__
def experimental_make_numpy_dataset(self, numpy_input, session=None):
"""Makes a dataset for input provided via a numpy array.
This avoids... | @tf_export(v1=["distribute.StrategyExtended"]) # pylint: disable=missing-docstring
class StrategyExtendedV1(StrategyExtendedV2):
| __doc__ = StrategyExtendedV2.__doc__
def experimental_make_numpy_dataset(self, numpy_input, session=None):
"""Makes a dataset for input provided via a numpy array.
This avoids adding `numpy_input` as a large constant in the graph,
and copies the data to the machine or machines that will be processing
... | _type=None,
task_id=None):
"""Configures the strategy class."""
del session_config, cluster_spec, task_type, task_id
def _update_config_proto(self, config_proto):
return copy.deepcopy(config_proto)
def _in_multi_worker_mode(self):
"""Whether this strategy indicates working in mult... | 256 | 256 | 1,674 | 33 | 223 | nyiritb/tensorflow | tensorflow/python/distribute/distribute_lib.py | Python | StrategyExtendedV1 | StrategyExtendedV1 | 2,614 | 2,803 | 2,614 | 2,616 | c4506a35de52b4cfa5bd00b3b0423699fcaaf45f | bigcode/the-stack | train |
c22153d89f4ccd5f446b3437 | train | class | @tf_export("distribute.experimental.ValueContext", v1=[])
class ValueContext(object):
"""A class wrapping information needed by a distribute function.
This is a context class that is passed to the `value_fn` in
`strategy.experimental_distribute_values_from_function` and contains
information about the compute r... | @tf_export("distribute.experimental.ValueContext", v1=[])
class ValueContext(object):
| """A class wrapping information needed by a distribute function.
This is a context class that is passed to the `value_fn` in
`strategy.experimental_distribute_values_from_function` and contains
information about the compute replicas. The `num_replicas_in_sync` and
`replica_id` can be used to customize the va... | batch size.
Raises:
ValueError: if `global_batch_size` not divisible by
`num_replicas_in_sync`.
"""
if global_batch_size % self._num_replicas_in_sync != 0:
raise ValueError("The `global_batch_size` %r is not divisible by "
"`num_replicas_in_sync` %r " %
... | 166 | 166 | 556 | 19 | 147 | nyiritb/tensorflow | tensorflow/python/distribute/distribute_lib.py | Python | ValueContext | ValueContext | 519 | 582 | 519 | 520 | a4c03d7b7ef1b348eb23255443757aa387eb63dd | bigcode/the-stack | train |
b9f2590dd01565c2f0551f3f | train | class | @tf_export("distribute.Strategy", v1=[]) # pylint: disable=g-missing-docstring
class Strategy(StrategyBase):
__doc__ = StrategyBase.__doc__
def experimental_assign_to_logical_device(self, tensor, logical_device_id):
"""Adds annotation that `tensor` will be assigned to a logical device.
NOTE: This API is... | @tf_export("distribute.Strategy", v1=[]) # pylint: disable=g-missing-docstring
class Strategy(StrategyBase):
| __doc__ = StrategyBase.__doc__
def experimental_assign_to_logical_device(self, tensor, logical_device_id):
"""Adds annotation that `tensor` will be assigned to a logical device.
NOTE: This API is only supported in TPUStrategy for now.
This adds an annotation to `tensor` specifying that operations on
... | worker', 'index': 0}
})
# This implicitly uses TF_CONFIG for the cluster and current task info.
strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy()
...
if strategy.cluster_resolver.task_type == 'worker':
# Perform something that's only applicable on workers. Since we set thi... | 256 | 256 | 2,105 | 30 | 225 | nyiritb/tensorflow | tensorflow/python/distribute/distribute_lib.py | Python | Strategy | Strategy | 1,580 | 1,820 | 1,580 | 1,582 | 8a393f94134a13b2a6112c1abf044f688e64579a | bigcode/the-stack | train |
1b5d5214237be3b0b9420908 | train | class | @tf_export("distribute.RunOptions")
class RunOptions(
collections.namedtuple("RunOptions", [
"experimental_enable_dynamic_batch_size",
"experimental_bucketizing_dynamic_shape",
])):
"""Run options for `strategy.run`.
This can be used to hold some strategy specific configs.
Attributes:
... | @tf_export("distribute.RunOptions")
class RunOptions(
collections.namedtuple("RunOptions", [
"experimental_enable_dynamic_batch_size",
"experimental_bucketizing_dynamic_shape",
])):
| """Run options for `strategy.run`.
This can be used to hold some strategy specific configs.
Attributes:
experimental_enable_dynamic_batch_size: Boolean. Only applies to
TPUStrategy. Default to True. If True, TPUStrategy will enable dynamic
padder to support dynamic batch size for the inputs. Oth... | id {}, "
" total replicas in sync: ""{})")
.format(self.replica_id_in_sync_group, self.num_replicas_in_sync))
@tf_export("distribute.RunOptions")
class RunOptions(
collections.namedtuple("RunOptions", [
"experimental_enable_dynamic_batch_size",
"experimental_bucketizing_dyn... | 73 | 73 | 245 | 41 | 32 | nyiritb/tensorflow | tensorflow/python/distribute/distribute_lib.py | Python | RunOptions | RunOptions | 585 | 612 | 585 | 590 | 6efec6093096c7ec4a26d7895a94390a5aac97e7 | bigcode/the-stack | train |
89f5bd7f3eb47d97ebe7566e | train | class | @tf_export(v1=["distribute.Strategy"])
class StrategyV1(StrategyBase):
"""A list of devices with a state & compute distribution policy.
See [the guide](https://www.tensorflow.org/guide/distribute_strategy)
for overview and examples.
Note: Not all `tf.distribute.Strategy` implementations currently support
Te... | @tf_export(v1=["distribute.Strategy"])
class StrategyV1(StrategyBase):
| """A list of devices with a state & compute distribution policy.
See [the guide](https://www.tensorflow.org/guide/distribute_strategy)
for overview and examples.
Note: Not all `tf.distribute.Strategy` implementations currently support
TensorFlow's partitioned variables (where a single variable is split acro... | strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"])
>>> def value_fn(ctx):
... return ctx.num_replicas_in_sync
>>> distributed_values = (
... strategy.experimental_distribute_values_from_function(
... value_fn))
>>> local_result = strategy.experimental_local_results(dist... | 256 | 256 | 1,555 | 19 | 236 | nyiritb/tensorflow | tensorflow/python/distribute/distribute_lib.py | Python | StrategyV1 | StrategyV1 | 1,824 | 1,990 | 1,824 | 1,825 | cb9a2a66d55b461b85e719064b838529fae2af07 | bigcode/the-stack | train |
5637b9581e29ab0b65c31155 | train | class | class _DefaultDistributionExtended(StrategyExtendedV1):
"""Implementation of _DefaultDistributionStrategy."""
def __init__(self, container_strategy):
super(_DefaultDistributionExtended, self).__init__(container_strategy)
self._retrace_functions_for_each_device = False
def _scope(self, strategy):
"""... | class _DefaultDistributionExtended(StrategyExtendedV1):
| """Implementation of _DefaultDistributionStrategy."""
def __init__(self, container_strategy):
super(_DefaultDistributionExtended, self).__init__(container_strategy)
self._retrace_functions_for_each_device = False
def _scope(self, strategy):
"""Context manager setting a variable creator and `self` as... | _count"]
def __init__(self, strategy):
def creator(next_creator, **kwargs):
_require_strategy_scope_strategy(strategy)
return next_creator(**kwargs)
self._var_creator_scope = variable_scope.variable_creator_scope(creator)
self._strategy = strategy
self._nested_count = 0
def __enter__... | 256 | 256 | 1,206 | 11 | 245 | nyiritb/tensorflow | tensorflow/python/distribute/distribute_lib.py | Python | _DefaultDistributionExtended | _DefaultDistributionExtended | 3,072 | 3,233 | 3,072 | 3,072 | 82bccc604baf496200d5d314424b15ae5622691b | bigcode/the-stack | train |
28af036d3e8e94d2ccb0480b | train | function | def _from_proto_fn(v, import_scope=None):
if distribution_strategy_context.has_strategy():
raise NotImplementedError(
"Deserialization of variables is not yet supported when using a "
"tf.distribute.Strategy.")
else:
return _original_from_proto(v, import_scope=import_scope)
| def _from_proto_fn(v, import_scope=None):
| if distribution_strategy_context.has_strategy():
raise NotImplementedError(
"Deserialization of variables is not yet supported when using a "
"tf.distribute.Strategy.")
else:
return _original_from_proto(v, import_scope=import_scope)
| True
# ------------------------------------------------------------------------------
# We haven't yet implemented deserialization for DistributedVariables.
# So here we catch any attempts to deserialize variables
# when using distribution strategies.
# pylint: disable=protected-access
_original_from_proto = resourc... | 64 | 64 | 64 | 11 | 52 | nyiritb/tensorflow | tensorflow/python/distribute/distribute_lib.py | Python | _from_proto_fn | _from_proto_fn | 3,244 | 3,250 | 3,244 | 3,244 | ef5c9e3daaef51005d962999a61af8acb29f832a | bigcode/the-stack | train |
d4c9deaa25af581e5a60059a | train | class | class CartItem(models.Model):
product_name = models.CharField(max_length=200)
product_price = models.FloatField()
product_quantity = models.PositiveIntegerField()
| class CartItem(models.Model):
| product_name = models.CharField(max_length=200)
product_price = models.FloatField()
product_quantity = models.PositiveIntegerField()
| from django.db import models
class CartItem(models.Model):
| 12 | 64 | 35 | 6 | 5 | leonyu1010/creating-a-rest-api-with-django | shopping_cart/api_app/models.py | Python | CartItem | CartItem | 3 | 6 | 3 | 3 | 1fa8e69bf76f9db8b59b0a7d6597c069860460dc | bigcode/the-stack | train |
b019d11bfcd62fe66d43dd9f | train | function | def page_view(request, page=None):
return TemplateResponse(request, page + '.html', {})
| def page_view(request, page=None):
| return TemplateResponse(request, page + '.html', {})
| created:
obj.choice = vote
obj.save()
return http.JsonResponse({'status': 'recorded'})
def login_view(request):
n = request.GET.get('next', '/')
return TemplateResponse(request, 'login.html', {'next': n})
def page_view(request, page=None):
| 64 | 64 | 20 | 8 | 56 | pizzapanther/ppp | polls/views.py | Python | page_view | page_view | 90 | 91 | 90 | 90 | 6a4c2a35f6ffca46ecece7b8dec78c6777a3bb52 | bigcode/the-stack | train |
0e5b3bb8b2a57112cd42f9fa | train | function | @csrf_exempt
@staff_member_required
def start_poll(request, slug, pid):
pres = get_object_or_404(Presentation, slug=slug)
poll = get_object_or_404(Poll, id=pid, presentation__slug=slug)
pres.poll_set.exclude(id=pid).update(live=False)
poll.live = True
poll.save()
pusher_client = pusher.Pusher(**settings.P... | @csrf_exempt
@staff_member_required
def start_poll(request, slug, pid):
| pres = get_object_or_404(Presentation, slug=slug)
poll = get_object_or_404(Poll, id=pid, presentation__slug=slug)
pres.poll_set.exclude(id=pid).update(live=False)
poll.live = True
poll.save()
pusher_client = pusher.Pusher(**settings.PUSHER)
pusher_client.trigger(pres.slug, 'go-live', poll.json_data())
... | = {
'loaded': loaded,
'pres': pres,
'poll': poll,
'key': settings.PUSHER['key']
}
return TemplateResponse(request, 'embed.html', context)
@csrf_exempt
@staff_member_required
def start_poll(request, slug, pid):
| 64 | 64 | 137 | 19 | 45 | pizzapanther/ppp | polls/views.py | Python | start_poll | start_poll | 35 | 50 | 35 | 37 | a3c58f7e06c418b4552ff297a1e8df8e3b138a0f | bigcode/the-stack | train |
a6dccba939a0bf0a1ffd9da2 | train | function | @csrf_exempt
@login_required
def vote(request, slug):
pid = request.POST.get('poll')
vote = int(request.POST.get('vote'))
poll = get_object_or_404(Poll, id=pid, presentation__slug=slug)
obj, created = Vote.objects.get_or_create(
poll=poll,
user=request.user,
defaults={'choice': vote},
)
if not... | @csrf_exempt
@login_required
def vote(request, slug):
| pid = request.POST.get('poll')
vote = int(request.POST.get('vote'))
poll = get_object_or_404(Poll, id=pid, presentation__slug=slug)
obj, created = Vote.objects.get_or_create(
poll=poll,
user=request.user,
defaults={'choice': vote},
)
if not created:
obj.choice = vote
obj.save()
retu... | poll.save()
pusher_client = pusher.Pusher(**settings.PUSHER)
pusher_client.trigger(pres.slug, 'end-poll', {'poll': pid})
return http.JsonResponse({'status': 'ended'})
@csrf_exempt
@login_required
def vote(request, slug):
| 63 | 64 | 111 | 14 | 49 | pizzapanther/ppp | polls/views.py | Python | vote | vote | 66 | 83 | 66 | 68 | 92923a0ac47242bf73b63cfb0b95d61d1fb4e180 | bigcode/the-stack | train |
1a1c7861b5140d17fb7b99fe | train | function | @login_required
def presentation(request, slug):
pres = get_object_or_404(Presentation, slug=slug)
context = {'pres': pres, 'key': settings.PUSHER['key']}
return TemplateResponse(request, 'presentation.html', context)
| @login_required
def presentation(request, slug):
| pres = get_object_or_404(Presentation, slug=slug)
context = {'pres': pres, 'key': settings.PUSHER['key']}
return TemplateResponse(request, 'presentation.html', context)
| import staff_member_required
from django.shortcuts import get_object_or_404
from django.template.response import TemplateResponse
from django.views.decorators.csrf import csrf_exempt
import pusher
from polls.models import Presentation, Poll, Vote
from polls.tasks import push_stats
@login_required
def presentation(re... | 64 | 64 | 54 | 9 | 54 | pizzapanther/ppp | polls/views.py | Python | presentation | presentation | 14 | 18 | 14 | 15 | 2bd778f3a74c173f435299190d871004cb7f653c | bigcode/the-stack | train |
8e78f32240273f9e1cae3aa3 | train | function | def login_view(request):
n = request.GET.get('next', '/')
return TemplateResponse(request, 'login.html', {'next': n})
| def login_view(request):
| n = request.GET.get('next', '/')
return TemplateResponse(request, 'login.html', {'next': n})
| )
obj, created = Vote.objects.get_or_create(
poll=poll,
user=request.user,
defaults={'choice': vote},
)
if not created:
obj.choice = vote
obj.save()
return http.JsonResponse({'status': 'recorded'})
def login_view(request):
| 63 | 64 | 31 | 5 | 58 | pizzapanther/ppp | polls/views.py | Python | login_view | login_view | 86 | 88 | 86 | 86 | f6fc67e9554e48ac9086cba819598e027b3caf8e | bigcode/the-stack | train |
cce11c4c4b42ed9f79175490 | train | function | @csrf_exempt
@staff_member_required
def end_poll(request, slug, pid):
pres = get_object_or_404(Presentation, slug=slug)
poll = get_object_or_404(Poll, id=pid, presentation__slug=slug)
poll.live = False
poll.save()
pusher_client = pusher.Pusher(**settings.PUSHER)
pusher_client.trigger(pres.slug, 'end-poll',... | @csrf_exempt
@staff_member_required
def end_poll(request, slug, pid):
| pres = get_object_or_404(Presentation, slug=slug)
poll = get_object_or_404(Poll, id=pid, presentation__slug=slug)
poll.live = False
poll.save()
pusher_client = pusher.Pusher(**settings.PUSHER)
pusher_client.trigger(pres.slug, 'end-poll', {'poll': pid})
return http.JsonResponse({'status': 'ended'})
| )
pusher_client.trigger(pres.slug, 'go-live', poll.json_data())
push_stats.schedule((pres.slug, poll.id), delay=2)
return http.JsonResponse({'status': 'started'})
@csrf_exempt
@staff_member_required
def end_poll(request, slug, pid):
| 63 | 64 | 110 | 19 | 44 | pizzapanther/ppp | polls/views.py | Python | end_poll | end_poll | 52 | 63 | 52 | 54 | a58063b685468e9445ce5d850ebed35a256be8cc | bigcode/the-stack | train |
17d5c0080775330ba330cd1d | train | function | @staff_member_required
def embed(request, slug, pid):
pres = get_object_or_404(Presentation, slug=slug)
poll = get_object_or_404(Poll, id=pid, presentation__slug=slug)
loaded = request.GET.get('loaded')
context = {
'loaded': loaded,
'pres': pres,
'poll': poll,
'key': settings.PUSHER['key']
}
... | @staff_member_required
def embed(request, slug, pid):
| pres = get_object_or_404(Presentation, slug=slug)
poll = get_object_or_404(Poll, id=pid, presentation__slug=slug)
loaded = request.GET.get('loaded')
context = {
'loaded': loaded,
'pres': pres,
'poll': poll,
'key': settings.PUSHER['key']
}
return TemplateResponse(request, 'embed.html', contex... | def presentation(request, slug):
pres = get_object_or_404(Presentation, slug=slug)
context = {'pres': pres, 'key': settings.PUSHER['key']}
return TemplateResponse(request, 'presentation.html', context)
@staff_member_required
def embed(request, slug, pid):
| 64 | 64 | 105 | 13 | 51 | pizzapanther/ppp | polls/views.py | Python | embed | embed | 21 | 32 | 21 | 22 | fe0d5aaabd7e9c3e10742ddc776672904923906d | bigcode/the-stack | train |
90bf8d0d2db8548b44d82b32 | train | class | class TestAdditionalPropertiesClass(unittest.TestCase):
""" AdditionalPropertiesClass unit test stubs """
def setUp(self):
pass
def tearDown(self):
pass
def testAdditionalPropertiesClass(self):
"""
Test AdditionalPropertiesClass
"""
model = petstore_api... | class TestAdditionalPropertiesClass(unittest.TestCase):
| """ AdditionalPropertiesClass unit test stubs """
def setUp(self):
pass
def tearDown(self):
pass
def testAdditionalPropertiesClass(self):
"""
Test AdditionalPropertiesClass
"""
model = petstore_api.models.additional_properties_class.AdditionalProperties... | governing permissions and
limitations under the License.
"""
from __future__ import absolute_import
import os
import sys
import unittest
import petstore_api
from petstore_api.rest import ApiException
from petstore_api.models.additional_properties_class import AdditionalPropertiesClass
class TestAdditionalProper... | 64 | 64 | 70 | 9 | 54 | zhbcumt/swagger-codegen | samples/client/petstore/python/test/test_additional_properties_class.py | Python | TestAdditionalPropertiesClass | TestAdditionalPropertiesClass | 36 | 49 | 36 | 36 | bbfebefd21646abef683d3a1a5ba13d72544a034 | bigcode/the-stack | train |
836db6f3888b9ed85ed8ff09 | train | function | def get_command_line_options(executable_name, arguments):
parser = OptionParser(usage="%s options" % executable_name)
parser.add_option("-i", "--in", type="string", dest="input", help="Input DB File")
parser.add_option("-o", "--out", type="string", dest="output", help="Output Root File")
parser.add_opti... | def get_command_line_options(executable_name, arguments):
| parser = OptionParser(usage="%s options" % executable_name)
parser.add_option("-i", "--in", type="string", dest="input", help="Input DB File")
parser.add_option("-o", "--out", type="string", dest="output", help="Output Root File")
parser.add_option("-p", "--print", type="string", dest="print_format", he... | import print_function
from ROOT import gROOT, TFile
from LifeCycleAnalysis.LifeCyclePlots.LifeCyclePlotManager import LifeCyclePlotManager
from LifeCycleAnalysis.LifeCyclePlots.SqliteDAO import SqliteDAO
from LifeCycleAnalysis.LifeCyclePlots.SqliteDAO import sqlite
from LifeCycleAnalysis.LifeCyclePlots.WebView import ... | 99 | 99 | 330 | 11 | 87 | vkuznet/DBS | SystemTests/bin/LifeCyclePlots.py | Python | get_command_line_options | get_command_line_options | 12 | 35 | 12 | 12 | b7e17830f8d6256744a2d40ef8d43f4ff2b88172 | bigcode/the-stack | train |
40f3a2b1ff61df09678cbb33 | train | class | class GlibPackage (GnomeXzPackage):
def __init__ (self):
GnomeXzPackage.__init__ (self,
'glib',
version_major = '2.36',
version_minor = '3')
self.darwin = Package.profile.name == 'darwin'
if Package.profile.name == 'darwin':
#link to specific revisions for glib 2.30.x
self.sources.extend ([
... | class GlibPackage (GnomeXzPackage):
| def __init__ (self):
GnomeXzPackage.__init__ (self,
'glib',
version_major = '2.36',
version_minor = '3')
self.darwin = Package.profile.name == 'darwin'
if Package.profile.name == 'darwin':
#link to specific revisions for glib 2.30.x
self.sources.extend ([
# https://trac.macports.org/export/9... | class GlibPackage (GnomeXzPackage):
| 11 | 227 | 757 | 11 | 0 | bratsche/bockbuild | packages/glib.py | Python | GlibPackage | GlibPackage | 1 | 60 | 1 | 1 | dd0ff4b580a1b80f9e76093a0d6ffeaf09483748 | bigcode/the-stack | train |
85d47e5d51d6138ef8261f44 | train | function | def get_dist_vert_segm(rect_vert, rect_segm):
perm = [[x,y] for x in range(0, np.shape(rect_vert)[0]) for y in range(np.shape(rect_segm)[0])]
##############################
D = []
for pair in perm:
# take one point from rect_vert
ind_vert = pair[0]
# take two consequtive points f... | def get_dist_vert_segm(rect_vert, rect_segm):
| perm = [[x,y] for x in range(0, np.shape(rect_vert)[0]) for y in range(np.shape(rect_segm)[0])]
##############################
D = []
for pair in perm:
# take one point from rect_vert
ind_vert = pair[0]
# take two consequtive points from rect_segm
ind_s0 = pair[1]
... | = (p1.intersection(p2).area > 0.0)
return collision
def get_dist_vert_vert(rect0, rect1):
perm = [[x,y] for x in range(0, np.shape(rect0)[0]) for y in range(np.shape(rect1)[0])]
# Take among all 4 * 4 = 16 pairs of points (points from different rectangles)
D = []
for pair in perm:
v0 = re... | 151 | 151 | 506 | 13 | 137 | mselli/rss-extended | code/tools/dist_aux.py | Python | get_dist_vert_segm | get_dist_vert_segm | 36 | 76 | 36 | 36 | d552667c59f90b73c70880ad9ce47689922e62d5 | bigcode/the-stack | train |
ec0a8ce48717b3eb8db26ac0 | train | function | def evaluate_dist(vehicles):
# What should this return if there is only one vehicle?
V = [] # array of vertices
for vehicle in vehicles:
print('vehicle')
print(vehicle)
transform = vehicle.get_transform()
bounding_box = vehicle.bounding_box
#print(bounding_box)
... | def evaluate_dist(vehicles):
# What should this return if there is only one vehicle?
| V = [] # array of vertices
for vehicle in vehicles:
print('vehicle')
print(vehicle)
transform = vehicle.get_transform()
bounding_box = vehicle.bounding_box
#print(bounding_box)
#print(transform)
# 8 bounding box vertices relative to (0,0,0)
ext = ... | % (point_vert[0], point_vert[1]))
#print(math.degrees(angle0))
#print(math.degrees(angle1))
# perp length from vert to segment
perp = np.linalg.norm(np.cross(point_s1-point_s0, point_s0-point_vert))/np.linalg.norm(point_s0-point_s1)
D.append(perp)
try:
... | 120 | 120 | 402 | 19 | 100 | mselli/rss-extended | code/tools/dist_aux.py | Python | evaluate_dist | evaluate_dist | 79 | 128 | 79 | 81 | fc88dfb6709187c1129b423d2620a4b9c9b71faa | bigcode/the-stack | train |
2ade55870df1c9e4a892ae61 | train | function | def get_dist_vert_vert(rect0, rect1):
perm = [[x,y] for x in range(0, np.shape(rect0)[0]) for y in range(np.shape(rect1)[0])]
# Take among all 4 * 4 = 16 pairs of points (points from different rectangles)
D = []
for pair in perm:
v0 = rect0[pair[0]]
v1 = rect1[pair[1]]
D.append(g... | def get_dist_vert_vert(rect0, rect1):
| perm = [[x,y] for x in range(0, np.shape(rect0)[0]) for y in range(np.shape(rect1)[0])]
# Take among all 4 * 4 = 16 pairs of points (points from different rectangles)
D = []
for pair in perm:
v0 = rect0[pair[0]]
v1 = rect1[pair[1]]
D.append(get_distance(v0, v1))
d = min(D)
... | _collision(rect0, rect1):
p1 = Polygon(tuple(map(tuple, rect0)))
p2 = Polygon(tuple(map(tuple, rect1)))
collision = (p1.intersection(p2).area > 0.0)
return collision
def get_dist_vert_vert(rect0, rect1):
| 64 | 64 | 118 | 11 | 52 | mselli/rss-extended | code/tools/dist_aux.py | Python | get_dist_vert_vert | get_dist_vert_vert | 25 | 34 | 25 | 25 | 7e1edcfe65c99fdc4dfff8c012c22416359c8651 | bigcode/the-stack | train |
ba911eef91ca396843fe621f | train | function | def get_distance(v1, v2):
dist = math.sqrt( (v1[0] - v2[0])**2 + (v1[1] - v2[1])**2 )
return dist
| def get_distance(v1, v2):
| dist = math.sqrt( (v1[0] - v2[0])**2 + (v1[1] - v2[1])**2 )
return dist
| import carla
from shapely.geometry import Polygon
import numpy as np
import math
def get_distance(v1, v2):
| 28 | 64 | 49 | 9 | 18 | mselli/rss-extended | code/tools/dist_aux.py | Python | get_distance | get_distance | 6 | 8 | 6 | 6 | c6ed89a6c8f9e7f5afa5e889c2cc4332a82c36b8 | bigcode/the-stack | train |
7b825c4cb665554018ec6106 | train | function | def check_collision(rect0, rect1):
p1 = Polygon(tuple(map(tuple, rect0)))
p2 = Polygon(tuple(map(tuple, rect1)))
collision = (p1.intersection(p2).area > 0.0)
return collision
| def check_collision(rect0, rect1):
| p1 = Polygon(tuple(map(tuple, rect0)))
p2 = Polygon(tuple(map(tuple, rect1)))
collision = (p1.intersection(p2).area > 0.0)
return collision
| [1])**2 )
return dist
'''
def is_between(v1, v2, v3):
r = get_distance(v2,v1) + get_distance(v3,v1) == get_distance(v2,v3)
return r
'''
def check_collision(rect0, rect1):
| 63 | 64 | 55 | 9 | 54 | mselli/rss-extended | code/tools/dist_aux.py | Python | check_collision | check_collision | 18 | 22 | 18 | 18 | f8442746679c76df87e5a7e5151100ba27aaadfd | bigcode/the-stack | train |
462c4595cbae5446b1c11512 | train | function | def corrupt():
print(r+'[?]'+w+' Command not found, please type help')
| def corrupt():
| print(r+'[?]'+w+' Command not found, please type help')
| m'
b='\x1b[36;1m'
y='\x1b[33m'
def exit():
print(r+'[!]'+w+' The user forces it to stop')
print(r+'[!]'+w+' Exiting program')
sys.exit(1)
def corrupt():
| 63 | 64 | 21 | 3 | 60 | 5l1v3r1/saydog-framework | module/malware/21.py | Python | corrupt | corrupt | 15 | 16 | 15 | 15 | c0edfec3146884cca84bf40b1b4d86afa87281d5 | bigcode/the-stack | train |
42796e4bde5606b3a9ba4d7a | train | function | def thezoo():
while True:
try:
global name
global output
names = 'CryptoLocker_20Nov2013'
mg2 = input(w+'saydog('+r+'malware/'+names+w+') > ')
if mg2 == 'help':
... | def thezoo():
| while True:
try:
global name
global output
names = 'CryptoLocker_20Nov2013'
mg2 = input(w+'saydog('+r+'malware/'+names+w+') > ')
if mg2 == 'help':
... | import os,sys
import time
u='\033[4m'
w='\x1b[00m'
r='\x1b[91m'
b='\x1b[36;1m'
y='\x1b[33m'
def exit():
print(r+'[!]'+w+' The user forces it to stop')
print(r+'[!]'+w+' Exiting program')
sys.exit(1)
def corrupt():
print(r+'[?]'+w+' Command not found, please type help')
... | 126 | 168 | 560 | 5 | 120 | 5l1v3r1/saydog-framework | module/malware/21.py | Python | thezoo | thezoo | 20 | 72 | 20 | 20 | 9ea006dcdeaa937fe66932c340010180baa3ba7f | bigcode/the-stack | train |
391c211fe2f9eefa054d9921 | train | function | def exit():
print(r+'[!]'+w+' The user forces it to stop')
print(r+'[!]'+w+' Exiting program')
sys.exit(1)
| def exit():
| print(r+'[!]'+w+' The user forces it to stop')
print(r+'[!]'+w+' Exiting program')
sys.exit(1)
| import os,sys
import time
u='\033[4m'
w='\x1b[00m'
r='\x1b[91m'
b='\x1b[36;1m'
y='\x1b[33m'
def exit():
| 56 | 64 | 38 | 3 | 53 | 5l1v3r1/saydog-framework | module/malware/21.py | Python | exit | exit | 10 | 13 | 10 | 10 | 59748e618d7df41bfed07a7755b5f53abdafc369 | bigcode/the-stack | train |
c7019415449f2d14bf1455cf | train | class | class DBCommodity(Base):
@declared_attr
def __tablename__(cls):
return "dbcommodities"
commodity_id = Column(Integer, primary_key=True)
category = Column(String, nullable=False)
commodity = Column(String, nullable=False)
def __repr__(self):
output = f"<Commodity(id={self.commod... | class DBCommodity(Base):
@declared_attr
| def __tablename__(cls):
return "dbcommodities"
commodity_id = Column(Integer, primary_key=True)
category = Column(String, nullable=False)
commodity = Column(String, nullable=False)
def __repr__(self):
output = f"<Commodity(id={self.commodity_id}, category={self.category}, "
... | from hdx.database import Base
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import declared_attr
class DBCommodity(Base):
@declared_attr
| 34 | 64 | 95 | 11 | 22 | orest-d/hdxscraper-wfp-food-prices | database/dbcommodity.py | Python | DBCommodity | DBCommodity | 6 | 18 | 6 | 7 | afdd1a5911c97533bba400c9498cf8e499a38048 | bigcode/the-stack | train |
68bcea6e02b1c7b2bf5cf55d | train | function | def to_int(string_value):
"""
Convert a string starting with an int to an int and return this.
:param str string_value: The string to convert.
:returns: The int from the start of the string.
:rtype: int
:raises TypeError: if something other than a string is passed in.
:raises ValueError: if... | def to_int(string_value):
| """
Convert a string starting with an int to an int and return this.
:param str string_value: The string to convert.
:returns: The int from the start of the string.
:rtype: int
:raises TypeError: if something other than a string is passed in.
:raises ValueError: if an int cannot be found.
... | +)([eE][+-]?\d+)?'
try:
float_component = re.match(float_regexp, string_value).group(0)
except AttributeError:
raise ValueError('Cannot find float in {}'.format(string_value))
return float(float_component)
def to_int(string_value):
| 64 | 64 | 143 | 6 | 58 | PRIMAVERA-H2020/pre-proc | pre_proc/common.py | Python | to_int | to_int | 120 | 136 | 120 | 120 | 1260f56960a853c2991c0411aa190da451aaa9c5 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.