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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
65f168c36eb70015fa245caa | train | function | def nop(x):
return x
| def nop(x):
| return x
| = 0x05
tDiv = 0x06
tPower = 0x07
tConcat = 0x08
tLT, tLE, tEQ, tGE, tGT, tNE = range(0x09, 0x0F)
def nop(x):
| 64 | 64 | 8 | 4 | 60 | DissectMalware/xlrd2 | xlrd2/formula.py | Python | nop | nop | 1,203 | 1,204 | 1,203 | 1,203 | de2ac40653a09a1b72bec31a9f13f522191da35f | bigcode/the-stack | train |
271e97a7f8acb418e474a1d4 | train | function | def colname(colx):
"""Utility function: ``7`` => ``'H'``, ``27`` => ``'AB'``"""
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
if colx <= 25:
return alphabet[colx]
else:
xdiv26, xmod26 = divmod(colx, 26)
return alphabet[xdiv26 - 1] + alphabet[xmod26]
| def colname(colx):
| """Utility function: ``7`` => ``'H'``, ``27`` => ``'AB'``"""
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
if colx <= 25:
return alphabet[colx]
else:
xdiv26, xmod26 = divmod(colx, 26)
return alphabet[xdiv26 - 1] + alphabet[xmod26]
| el(colx, colxrel, bcolx, r1c1)
r = rownamerel(rowx, rowxrel, browx, r1c1)
if r1c1:
return r + c
return c + r
def colname(colx):
| 64 | 64 | 87 | 6 | 57 | DissectMalware/xlrd2 | xlrd2/formula.py | Python | colname | colname | 2,661 | 2,668 | 2,661 | 2,661 | 93145e5d9dfe8861a36e6b19ad8b1b6b2787b901 | bigcode/the-stack | train |
551f4439520f4826f7795e6b | train | function | def _opr_ne(x, y): return x != y
| def _opr_ne(x, y): | return x != y
| y
def _opr_le(x, y): return x <= y
def _opr_eq(x, y): return x == y
def _opr_ge(x, y): return x >= y
def _opr_gt(x, y): return x > y
def _opr_ne(x, y): | 64 | 64 | 13 | 9 | 54 | DissectMalware/xlrd2 | xlrd2/formula.py | Python | _opr_ne | _opr_ne | 1,213 | 1,213 | 1,213 | 1,213 | a0fe75f76ccde124d3bff5da392ea6b0cb27e0c0 | bigcode/the-stack | train |
a83e6187442ecf1b5674fa90 | train | class | class Operand(object):
"""
Used in evaluating formulas.
The following table describes the kinds and how their values
are represented.
.. raw:: html
<table border="1" cellpadding="7">
<tr>
<th>Kind symbol</th>
<th>Kind number</th>
<th>Value representation</th... | class Operand(object):
| """
Used in evaluating formulas.
The following table describes the kinds and how their values
are represented.
.. raw:: html
<table border="1" cellpadding="7">
<tr>
<th>Kind symbol</th>
<th>Kind number</th>
<th>Value representation</th>
</tr>
... | internal reference, deleted sheet(s)
nsheets = len(bk._all_sheets_map)
if not(0 <= ref_first_sheetx <= ref_last_sheetx < nsheets):
if blah:
print("/// get_externsheet_local_range_b57(%d, %d, %d) -> ???"
% (raw_extshtx, ref_first_sheetx, ref_last_sheetx), file=bk.logfile)
... | 229 | 229 | 764 | 4 | 224 | DissectMalware/xlrd2 | xlrd2/formula.py | Python | Operand | Operand | 1,037 | 1,126 | 1,037 | 1,037 | b8e972888f4aa74c510d51f8768d4d20f21e6987 | bigcode/the-stack | train |
97f056a7bfeaf2a410438468 | train | function | def rownamerel(rowx, rowxrel, browx=None, r1c1=0):
# if no base rowx is provided, we have to return r1c1
if browx is None:
r1c1 = True
if not rowxrel:
if r1c1:
return "R%d" % (rowx+1)
return "$%d" % (rowx+1)
if r1c1:
if rowx:
return "R[%d]" % rowx
... | def rownamerel(rowx, rowxrel, browx=None, r1c1=0):
# if no base rowx is provided, we have to return r1c1
| if browx is None:
r1c1 = True
if not rowxrel:
if r1c1:
return "R%d" % (rowx+1)
return "$%d" % (rowx+1)
if r1c1:
if rowx:
return "R[%d]" % rowx
return "R"
return "%d" % ((browx + rowx) % 65536 + 1)
| , 1, ...). These functions display the
# sheet component as empty, just like Excel etc.
def rownamerel(rowx, rowxrel, browx=None, r1c1=0):
# if no base rowx is provided, we have to return r1c1
| 64 | 64 | 147 | 42 | 22 | DissectMalware/xlrd2 | xlrd2/formula.py | Python | rownamerel | rownamerel | 2,611 | 2,623 | 2,611 | 2,612 | a0492f9c708ab8168c850c1dd34bc6a2c0614261 | bigcode/the-stack | train |
b5f7a84644b3172aff43bfd6 | train | function | def _opr_ge(x, y): return x >= y
| def _opr_ge(x, y): | return x >= y
| x
def _opr_pow(x, y): return x ** y
def _opr_lt(x, y): return x < y
def _opr_le(x, y): return x <= y
def _opr_eq(x, y): return x == y
def _opr_ge(x, y): | 64 | 64 | 13 | 9 | 54 | DissectMalware/xlrd2 | xlrd2/formula.py | Python | _opr_ge | _opr_ge | 1,211 | 1,211 | 1,211 | 1,211 | 37d5b531851897377701038f5481310c855da722 | bigcode/the-stack | train |
fb331615226844b3f5419a0a | train | function | def _opr_le(x, y): return x <= y
| def _opr_le(x, y): | return x <= y
| GE, tGT, tNE = range(0x09, 0x0F)
def nop(x):
return x
def _opr_pow(x, y): return x ** y
def _opr_lt(x, y): return x < y
def _opr_le(x, y): | 64 | 64 | 13 | 9 | 54 | DissectMalware/xlrd2 | xlrd2/formula.py | Python | _opr_le | _opr_le | 1,209 | 1,209 | 1,209 | 1,209 | 036215ae3eef99655e8873097ac57f9ad9f0a34b | bigcode/the-stack | train |
ad527744cd5d216d5e94cb76 | train | function | def cellname(rowx, colx):
"""Utility function: ``(5, 7)`` => ``'H6'``"""
return "%s%d" % (colname(colx), rowx+1)
| def cellname(rowx, colx):
| """Utility function: ``(5, 7)`` => ``'H6'``"""
return "%s%d" % (colname(colx), rowx+1)
| )
return "$" + colname(colx)
if r1c1:
if colx:
return "C[%d]" % colx
return "C"
return colname((bcolx + colx) % 256)
def cellname(rowx, colx):
| 64 | 64 | 48 | 9 | 55 | DissectMalware/xlrd2 | xlrd2/formula.py | Python | cellname | cellname | 2,639 | 2,641 | 2,639 | 2,639 | b1454f313ce23d7596fa7c02f71b7fc043371370 | bigcode/the-stack | train |
e1782307efb3c5d0cdc3d388 | train | function | def evaluate_name_formula(bk, nobj, namex, blah=0, level=0):
if level > STACK_ALARM_LEVEL:
blah = 1
data = nobj.raw_formula
fmlalen = nobj.basic_formula_len
bv = bk.biff_version
reldelta = 1 # All defined name formulas use "Method B" [OOo docs]
if blah:
print("::: evaluate_name_f... | def evaluate_name_formula(bk, nobj, namex, blah=0, level=0):
| if level > STACK_ALARM_LEVEL:
blah = 1
data = nobj.raw_formula
fmlalen = nobj.basic_formula_len
bv = bk.biff_version
reldelta = 1 # All defined name formulas use "Method B" [OOo docs]
if blah:
print("::: evaluate_name_formula %r %r %d %d %r level=%d"
% (namex, nobj.na... | , '<'),
tLE: (_cmp_argdict, oBOOL, _opr_le, 10, '<='),
tEQ: (_cmp_argdict, oBOOL, _opr_eq, 10, '='),
tGE: (_cmp_argdict, oBOOL, _opr_ge, 10, '>='),
tGT: (_cmp_argdict, oBOOL, _opr_gt, 10, '>'),
tNE: (_cmp_argdict, oBOOL, _opr_ne, 10, '<>'),
}
unop_rules = {
0x13: (lambd... | 256 | 256 | 7,082 | 21 | 234 | DissectMalware/xlrd2 | xlrd2/formula.py | Python | evaluate_name_formula | evaluate_name_formula | 1,255 | 1,892 | 1,255 | 1,255 | 8ab957e442487eaf3a52b79513581ab0c3f5be2d | bigcode/the-stack | train |
e371a91af80d9041fae0ba58 | train | function | def get_cell_addr(data, pos, bv, reldelta, browx=None, bcolx=None):
if bv >= 80:
rowval, colval = unpack("<HH", data[pos:pos+4])
# print " rv=%04xh cv=%04xh" % (rowval, colval)
return adjust_cell_addr_biff8(rowval, colval, reldelta, browx, bcolx)
else:
rowval, colval = unpack(... | def get_cell_addr(data, pos, bv, reldelta, browx=None, bcolx=None):
| if bv >= 80:
rowval, colval = unpack("<HH", data[pos:pos+4])
# print " rv=%04xh cv=%04xh" % (rowval, colval)
return adjust_cell_addr_biff8(rowval, colval, reldelta, browx, bcolx)
else:
rowval, colval = unpack("<HB", data[pos:pos+3])
# print " rv=%04xh cv=%04xh" % (r... | else:
if row_rel:
rowx -= browx
if col_rel:
colx -= bcolx
return rowx, colx, row_rel, col_rel
def get_cell_addr(data, pos, bv, reldelta, browx=None, bcolx=None):
| 64 | 64 | 166 | 23 | 40 | DissectMalware/xlrd2 | xlrd2/formula.py | Python | get_cell_addr | get_cell_addr | 946 | 955 | 946 | 946 | c82ab73883f625b2ee6e05a1c5c9f564a7142fc2 | bigcode/the-stack | train |
81fb424a8819e0bcbe034bbf | train | function | def get_cell_range_addr(data, pos, bv, reldelta, browx=None, bcolx=None):
if bv >= 80:
row1val, row2val, col1val, col2val = unpack("<HHHH", data[pos:pos+8])
# print " rv=%04xh cv=%04xh" % (row1val, col1val)
# print " rv=%04xh cv=%04xh" % (row2val, col2val)
res1 = adjust_cell_ad... | def get_cell_range_addr(data, pos, bv, reldelta, browx=None, bcolx=None):
| if bv >= 80:
row1val, row2val, col1val, col2val = unpack("<HHHH", data[pos:pos+8])
# print " rv=%04xh cv=%04xh" % (row1val, col1val)
# print " rv=%04xh cv=%04xh" % (row2val, col2val)
res1 = adjust_cell_addr_biff8(row1val, col1val, reldelta, browx, bcolx)
res2 = adjust_c... | x)
else:
rowval, colval = unpack("<HB", data[pos:pos+3])
# print " rv=%04xh cv=%04xh" % (rowval, colval)
return adjust_cell_addr_biff_le7(
rowval, colval, reldelta, browx, bcolx)
def get_cell_range_addr(data, pos, bv, reldelta, browx=None, bcolx=None):
| 97 | 97 | 326 | 24 | 73 | DissectMalware/xlrd2 | xlrd2/formula.py | Python | get_cell_range_addr | get_cell_range_addr | 957 | 973 | 957 | 957 | fb7968c0cac3b124b08778ff7798b2ea0bec3e05 | bigcode/the-stack | train |
2b3ec8e47703813fb3392342 | train | function | def rangename3drel(book, ref3d, browx=None, bcolx=None, r1c1=0):
"""
Utility function:
``Ref3D(coords=(0, 1, -32, -22, -13, 13), relflags=(0, 0, 1, 1, 1, 1))``
In R1C1 mode => ``'Sheet1!R[-32]C[-13]:R[-23]C[12]'``
In A1 mode => depends on base cell ``(browx, bcolx)``
"""
coords = ref3d.coo... | def rangename3drel(book, ref3d, browx=None, bcolx=None, r1c1=0):
| """
Utility function:
``Ref3D(coords=(0, 1, -32, -22, -13, 13), relflags=(0, 0, 1, 1, 1, 1))``
In R1C1 mode => ``'Sheet1!R[-32]C[-13]:R[-23]C[12]'``
In A1 mode => depends on base cell ``(browx, bcolx)``
"""
coords = ref3d.coords
relflags = ref3d.relflags
shdesc = sheetrangerel(book... | coords = ref3d.coords
return "%s!%s" % (
sheetrange(book, *coords[:2]),
rangename2d(*coords[2:6]))
def rangename3drel(book, ref3d, browx=None, bcolx=None, r1c1=0):
| 69 | 69 | 232 | 28 | 41 | DissectMalware/xlrd2 | xlrd2/formula.py | Python | rangename3drel | rangename3drel | 2,708 | 2,723 | 2,708 | 2,708 | bd448abb6382d054b9858076d327efd74a1cb413 | bigcode/the-stack | train |
9923a348890794a4aefca2fb | train | function | def get_externsheet_local_range(bk, refx, blah=0):
try:
info = bk._externsheet_info[refx]
except IndexError:
print("!!! get_externsheet_local_range: refx=%d, not in range(%d)"
% (refx, len(bk._externsheet_info)), file=bk.logfile)
return (-101, -101)
ref_recordx, ref_first... | def get_externsheet_local_range(bk, refx, blah=0):
| try:
info = bk._externsheet_info[refx]
except IndexError:
print("!!! get_externsheet_local_range: refx=%d, not in range(%d)"
% (refx, len(bk._externsheet_info)), file=bk.logfile)
return (-101, -101)
ref_recordx, ref_first_sheetx, ref_last_sheetx = info
if ref_recordx ... | 1, res2
else:
row1val, row2val, col1val, col2val = unpack("<HHBB", data[pos:pos+6])
# print " rv=%04xh cv=%04xh" % (row1val, col1val)
# print " rv=%04xh cv=%04xh" % (row2val, col2val)
res1 = adjust_cell_addr_biff_le7(
row1val, col1val, reldelta, browx, bcolx... | 174 | 174 | 580 | 17 | 156 | DissectMalware/xlrd2 | xlrd2/formula.py | Python | get_externsheet_local_range | get_externsheet_local_range | 975 | 1,010 | 975 | 975 | fe3370b42005ad7e8ca85f9443a9666c1a05cc52 | bigcode/the-stack | train |
963edeaed3325b4bfadc23ad | train | function | def do_box_funcs(box_funcs, boxa, boxb):
return tuple(
func(numa, numb)
for func, numa, numb in zip(box_funcs, boxa.coords, boxb.coords)
)
| def do_box_funcs(box_funcs, boxa, boxb):
| return tuple(
func(numa, numb)
for func, numa, numb in zip(box_funcs, boxa.coords, boxb.coords)
)
| x1C, 0x1D, 0x2F])
tRangeFuncs = (min, max, min, max, min, max)
tIsectFuncs = (max, min, max, min, max, min)
def do_box_funcs(box_funcs, boxa, boxb):
| 64 | 64 | 46 | 13 | 51 | DissectMalware/xlrd2 | xlrd2/formula.py | Python | do_box_funcs | do_box_funcs | 905 | 909 | 905 | 905 | 58f73e68fcf59d37866303764bfbab952aa9c40a | bigcode/the-stack | train |
327380ab7d9816906f8d7fef | train | class | class FormulaError(Exception):
pass
| class FormulaError(Exception):
| pass
| _sheets_map[ref_last_sheetx]
if not(0 <= xlrd_sheetx1 <= xlrd_sheetx2):
return (-3, -3) # internal reference, but to a macro sheet
return xlrd_sheetx1, xlrd_sheetx2
class FormulaError(Exception):
| 64 | 64 | 8 | 5 | 58 | DissectMalware/xlrd2 | xlrd2/formula.py | Python | FormulaError | FormulaError | 1,033 | 1,034 | 1,033 | 1,033 | 8c3d0646f73cfae9c255653279ec344704ec8510 | bigcode/the-stack | train |
f93c157cf42a44aec32ad351 | train | function | def adjust_cell_addr_biff8(rowval, colval, reldelta, browx=None, bcolx=None):
row_rel = (colval >> 15) & 1
col_rel = (colval >> 14) & 1
rowx = rowval
colx = colval & 0xff
if reldelta:
if row_rel and rowx >= 32768:
rowx -= 65536
if col_rel and colx >= 128:
colx... | def adjust_cell_addr_biff8(rowval, colval, reldelta, browx=None, bcolx=None):
| row_rel = (colval >> 15) & 1
col_rel = (colval >> 14) & 1
rowx = rowval
colx = colval & 0xff
if reldelta:
if row_rel and rowx >= 32768:
rowx -= 65536
if col_rel and colx >= 128:
colx -= 256
else:
if row_rel and browx:
rowx -= browx
... | a, boxb):
return tuple(
func(numa, numb)
for func, numa, numb in zip(box_funcs, boxa.coords, boxb.coords)
)
def adjust_cell_addr_biff8(rowval, colval, reldelta, browx=None, bcolx=None):
| 64 | 64 | 167 | 26 | 38 | DissectMalware/xlrd2 | xlrd2/formula.py | Python | adjust_cell_addr_biff8 | adjust_cell_addr_biff8 | 911 | 926 | 911 | 911 | f51996b0f46936c839df083b92f9b74ef970412a | bigcode/the-stack | train |
8ee10eef052902c9c990fb1c | train | function | def _opr_gt(x, y): return x > y
| def _opr_gt(x, y): | return x > y
| y
def _opr_lt(x, y): return x < y
def _opr_le(x, y): return x <= y
def _opr_eq(x, y): return x == y
def _opr_ge(x, y): return x >= y
def _opr_gt(x, y): | 64 | 64 | 14 | 9 | 54 | DissectMalware/xlrd2 | xlrd2/formula.py | Python | _opr_gt | _opr_gt | 1,212 | 1,212 | 1,212 | 1,212 | d0d1c14c519033c3558e4c5bd133185105b80d1f | bigcode/the-stack | train |
416019f8b6461e67256074a5 | train | class | class Ref3D(tuple):
"""
Represents an absolute or relative 3-dimensional reference to a box
of one or more cells.
The ``coords`` attribute is a tuple of the form::
(shtxlo, shtxhi, rowxlo, rowxhi, colxlo, colxhi)
where ``0 <= thingxlo <= thingx < thingxhi``.
.. note::
It is quite... | class Ref3D(tuple):
| """
Represents an absolute or relative 3-dimensional reference to a box
of one or more cells.
The ``coords`` attribute is a tuple of the form::
(shtxlo, shtxhi, rowxlo, rowxhi, colxlo, colxhi)
where ``0 <= thingxlo <= thingx < thingxhi``.
.. note::
It is quite possible to have ``... | text of the original formula. Function names will be
#: in English irrespective of the original language, which doesn't seem
#: to be recorded anywhere. The separator is ",", not ";" or whatever else
#: might be more appropriate for the end-user's locale; patches welcome.
text = '?'
def __init__(s... | 212 | 212 | 707 | 6 | 206 | DissectMalware/xlrd2 | xlrd2/formula.py | Python | Ref3D | Ref3D | 1,129 | 1,192 | 1,129 | 1,129 | 7a8c23fca465706cf58dc08306cac2b41876c5d7 | bigcode/the-stack | train |
e312355eabd39e3b0c46e861 | train | function | def rangename2d(rlo, rhi, clo, chi, r1c1=0):
""" ``(5, 20, 7, 10)`` => ``'$H$6:$J$20'`` """
if r1c1:
return
if rhi == rlo+1 and chi == clo+1:
return cellnameabs(rlo, clo, r1c1)
return "%s:%s" % (cellnameabs(rlo, clo, r1c1), cellnameabs(rhi-1, chi-1, r1c1))
| def rangename2d(rlo, rhi, clo, chi, r1c1=0):
| """ ``(5, 20, 7, 10)`` => ``'$H$6:$J$20'`` """
if r1c1:
return
if rhi == rlo+1 and chi == clo+1:
return cellnameabs(rlo, clo, r1c1)
return "%s:%s" % (cellnameabs(rlo, clo, r1c1), cellnameabs(rhi-1, chi-1, r1c1))
| return alphabet[colx]
else:
xdiv26, xmod26 = divmod(colx, 26)
return alphabet[xdiv26 - 1] + alphabet[xmod26]
def rangename2d(rlo, rhi, clo, chi, r1c1=0):
| 64 | 64 | 131 | 22 | 42 | DissectMalware/xlrd2 | xlrd2/formula.py | Python | rangename2d | rangename2d | 2,670 | 2,676 | 2,670 | 2,670 | 4baa0a43fdd1a2a45c9087843c74697e902e8caa | bigcode/the-stack | train |
3b3328ff345c4804fe5b2db2 | train | function | def colnamerel(colx, colxrel, bcolx=None, r1c1=0):
# if no base colx is provided, we have to return r1c1
if bcolx is None:
r1c1 = True
if not colxrel:
if r1c1:
return "C%d" % (colx + 1)
return "$" + colname(colx)
if r1c1:
if colx:
return "C[%d]" % ... | def colnamerel(colx, colxrel, bcolx=None, r1c1=0):
# if no base colx is provided, we have to return r1c1
| if bcolx is None:
r1c1 = True
if not colxrel:
if r1c1:
return "C%d" % (colx + 1)
return "$" + colname(colx)
if r1c1:
if colx:
return "C[%d]" % colx
return "C"
return colname((bcolx + colx) % 256)
| return "%d" % ((browx + rowx) % 65536 + 1)
def colnamerel(colx, colxrel, bcolx=None, r1c1=0):
# if no base colx is provided, we have to return r1c1
| 64 | 64 | 141 | 43 | 21 | DissectMalware/xlrd2 | xlrd2/formula.py | Python | colnamerel | colnamerel | 2,625 | 2,637 | 2,625 | 2,626 | 7e0bd83e0e18ab9e2eab149688853ee556ea8bc2 | bigcode/the-stack | train |
ac74f3e71ed1f44549e38043 | train | function | def _opr_pow(x, y): return x ** y
| def _opr_pow(x, y): | return x ** y
|
tPower = 0x07
tConcat = 0x08
tLT, tLE, tEQ, tGE, tGT, tNE = range(0x09, 0x0F)
def nop(x):
return x
def _opr_pow(x, y): | 64 | 64 | 13 | 9 | 54 | DissectMalware/xlrd2 | xlrd2/formula.py | Python | _opr_pow | _opr_pow | 1,206 | 1,206 | 1,206 | 1,206 | 53aee421781042a9ff042908dc73b17660bb14e6 | bigcode/the-stack | train |
db35889622d3fe63fac395a7 | train | function | def dump_formula(bk, data, fmlalen, bv, reldelta, blah=0, isname=0):
if blah:
print("dump_formula", fmlalen, bv, len(data), file=bk.logfile)
hex_char_dump(data, 0, fmlalen, fout=bk.logfile)
assert bv >= 80 #### this function needs updating ####
sztab = szdict[bv]
pos = 0
stack = []
... | def dump_formula(bk, data, fmlalen, bv, reldelta, blah=0, isname=0):
| if blah:
print("dump_formula", fmlalen, bv, len(data), file=bk.logfile)
hex_char_dump(data, 0, fmlalen, fout=bk.logfile)
assert bv >= 80 #### this function needs updating ####
sztab = szdict[bv]
pos = 0
stack = []
any_rel = 0
any_err = 0
spush = stack.append
while 0 <... | res = Operand(okind, ovalue, LEAF_RANK, otext)
spush(res)
elif opcode in error_opcodes:
any_err = 1
spush(error_opnd)
else:
if blah:
print("FORMULA: /// Not handled yet: t" + oname, file=bk.logfile)
any_err = 1
if sz <=... | 256 | 256 | 2,179 | 27 | 229 | DissectMalware/xlrd2 | xlrd2/formula.py | Python | dump_formula | dump_formula | 2,447 | 2,601 | 2,447 | 2,447 | f8d280cc852f11892e96ae566057228115011ca5 | bigcode/the-stack | train |
27c5e029ad39b9248ed37c20 | train | function | def _opr_eq(x, y): return x == y
| def _opr_eq(x, y): | return x == y
| , 0x0F)
def nop(x):
return x
def _opr_pow(x, y): return x ** y
def _opr_lt(x, y): return x < y
def _opr_le(x, y): return x <= y
def _opr_eq(x, y): | 64 | 64 | 13 | 9 | 54 | DissectMalware/xlrd2 | xlrd2/formula.py | Python | _opr_eq | _opr_eq | 1,210 | 1,210 | 1,210 | 1,210 | 84a610b2012a06989efe88488542a2cb44273c44 | bigcode/the-stack | train |
cc24fb5007ae6113c553ad50 | train | function | def cellnamerel(rowx, colx, rowxrel, colxrel, browx=None, bcolx=None, r1c1=0):
if not rowxrel and not colxrel:
return cellnameabs(rowx, colx, r1c1)
if (rowxrel and browx is None) or (colxrel and bcolx is None):
# must flip the whole cell into R1C1 mode
r1c1 = True
c = colnamerel(colx... | def cellnamerel(rowx, colx, rowxrel, colxrel, browx=None, bcolx=None, r1c1=0):
| if not rowxrel and not colxrel:
return cellnameabs(rowx, colx, r1c1)
if (rowxrel and browx is None) or (colxrel and bcolx is None):
# must flip the whole cell into R1C1 mode
r1c1 = True
c = colnamerel(colx, colxrel, bcolx, r1c1)
r = rownamerel(rowx, rowxrel, browx, r1c1)
if r... | +1, colx+1)
return "$%s$%d" % (colname(colx), rowx+1)
def cellnamerel(rowx, colx, rowxrel, colxrel, browx=None, bcolx=None, r1c1=0):
| 64 | 64 | 173 | 35 | 29 | DissectMalware/xlrd2 | xlrd2/formula.py | Python | cellnamerel | cellnamerel | 2,649 | 2,659 | 2,649 | 2,649 | ea2cfb9ab1178fd45c508ecdb5d232c51fc1f4cc | bigcode/the-stack | train |
035d78745e19dd40dc3e4807 | train | function | def rangename2drel(rlo_rhi_clo_chi, rlorel_rhirel_clorel_chirel, browx=None, bcolx=None, r1c1=0):
rlo, rhi, clo, chi = rlo_rhi_clo_chi
rlorel, rhirel, clorel, chirel = rlorel_rhirel_clorel_chirel
if (rlorel or rhirel) and browx is None:
r1c1 = True
if (clorel or chirel) and bcolx is None:
... | def rangename2drel(rlo_rhi_clo_chi, rlorel_rhirel_clorel_chirel, browx=None, bcolx=None, r1c1=0):
| rlo, rhi, clo, chi = rlo_rhi_clo_chi
rlorel, rhirel, clorel, chirel = rlorel_rhirel_clorel_chirel
if (rlorel or rhirel) and browx is None:
r1c1 = True
if (clorel or chirel) and bcolx is None:
r1c1 = True
start_cell = cellnamerel(rlo, clo, rlorel, clorel, browx, bcolx, r1c1)
end_c... | , clo, r1c1)
return "%s:%s" % (cellnameabs(rlo, clo, r1c1), cellnameabs(rhi-1, chi-1, r1c1))
def rangename2drel(rlo_rhi_clo_chi, rlorel_rhirel_clorel_chirel, browx=None, bcolx=None, r1c1=0):
| 89 | 89 | 299 | 42 | 47 | DissectMalware/xlrd2 | xlrd2/formula.py | Python | rangename2drel | rangename2drel | 2,678 | 2,693 | 2,678 | 2,678 | 630ab9096eadca93d366644539beab0345a49b26 | bigcode/the-stack | train |
abf7695b3a96a9f85ea80a11 | train | function | def cellnameabs(rowx, colx, r1c1=0):
"""Utility function: ``(5, 7)`` => ``'$H$6'``"""
if r1c1:
return "R%dC%d" % (rowx+1, colx+1)
return "$%s$%d" % (colname(colx), rowx+1)
| def cellnameabs(rowx, colx, r1c1=0):
| """Utility function: ``(5, 7)`` => ``'$H$6'``"""
if r1c1:
return "R%dC%d" % (rowx+1, colx+1)
return "$%s$%d" % (colname(colx), rowx+1)
| cellname(rowx, colx):
"""Utility function: ``(5, 7)`` => ``'H6'``"""
return "%s%d" % (colname(colx), rowx+1)
def cellnameabs(rowx, colx, r1c1=0):
| 64 | 64 | 87 | 17 | 47 | DissectMalware/xlrd2 | xlrd2/formula.py | Python | cellnameabs | cellnameabs | 2,643 | 2,647 | 2,643 | 2,643 | 55ef0dc4f2a809b6c43092ea1820c6ae99e9b1ff | bigcode/the-stack | train |
8436caac45a3fcff6b1d5aad | train | class | class JyveExporter(HTMLExporter):
""" Export a single notebook as a snapshot of a working JupyterLab
environment
"""
port = T.Integer(9999, help="port for temporary server")
token = T.Unicode(
binascii.b2a_hex(os.urandom(15)).decode("utf-8"), help="temporary token"
)
extra_urls ... | class JyveExporter(HTMLExporter):
| """ Export a single notebook as a snapshot of a working JupyterLab
environment
"""
port = T.Integer(9999, help="port for temporary server")
token = T.Unicode(
binascii.b2a_hex(os.urandom(15)).decode("utf-8"), help="temporary token"
)
extra_urls = T.List(
[
"f... | import subprocess
import time
import os
import shutil
import binascii
import json
import re
import notebook
from shutil import copytree, rmtree, copy2
from pathlib import Path
from tornado.httpclient import HTTPClient
import nbformat
from ipython_genutils.tempdir import TemporaryDirectory
import traitlets as T
fro... | 103 | 256 | 2,865 | 8 | 94 | deathbeds/jyve | jyve/exporter.py | Python | JyveExporter | JyveExporter | 26 | 379 | 26 | 26 | 61071c85e77e0d35be92ea8ab43513b3ec33a648 | bigcode/the-stack | train |
bd9c42e28c4f0be527bd1976 | train | class | class DataReader:
'''
'''
def __init__(self,res):
'''
'''
self.res=res
self.columns=None
self.col_index=None
self.cur_row=None
def build(self):
'''
'''
ret=True
res=self.res
cols=[]
cidx={}
index=0
for col in res.description:
cname=col[0].upper()
cols.append(cname)
cidx[cname... | class DataReader:
| '''
'''
def __init__(self,res):
'''
'''
self.res=res
self.columns=None
self.col_index=None
self.cur_row=None
def build(self):
'''
'''
ret=True
res=self.res
cols=[]
cidx={}
index=0
for col in res.description:
cname=col[0].upper()
cols.append(cname)
cidx[cname]=index
index+=... | #!/usr/bin/python
#coding=UTF-8
import pymysql as dbapi
import pandas as pd
import traceback
import warnings
warnings.filterwarnings('ignore')
__all__=['DBHandler','DataReader']
class DataReader:
| 49 | 104 | 347 | 4 | 45 | crb479/mcdevitt-trauma-ml | ScienceDirect/package/db_handler_mysql.py | Python | DataReader | DataReader | 14 | 100 | 14 | 14 | 5ac77f31fde06b7e69754f95839bead73eac87fd | bigcode/the-stack | train |
6f2d4bb6647a6a20f838a34b | train | class | class DBHandler:
class ConnParams:
def __init__(self,pas):
self.host=pas.get('host','localhost')
self.user=pas.get('user')
self.passwd=pas.get('passwd')
self.db=pas.get('db')
self.autocommit=False
self.error=None
def valid(self):
'''
'''
ret=True
if self.user is None:
self.erro... | class DBHandler:
| class ConnParams:
def __init__(self,pas):
self.host=pas.get('host','localhost')
self.user=pas.get('user')
self.passwd=pas.get('passwd')
self.db=pas.get('db')
self.autocommit=False
self.error=None
def valid(self):
'''
'''
ret=True
if self.user is None:
self.error=f'no user.'
... | .append(cname)
cidx[cname]=index
index+=1
self.columns=cols
self.col_index=cidx
return ret
def __getitem__(self,index):
'''
'''
ret=None
if isinstance(index,int):
ret=self.get_with_index(index)
else:
ret=self.get_with_name(index)
return ret
def get_with_index(self,index):
'''
''... | 256 | 256 | 1,934 | 4 | 251 | crb479/mcdevitt-trauma-ml | ScienceDirect/package/db_handler_mysql.py | Python | DBHandler | DBHandler | 104 | 516 | 104 | 105 | 4a4798f8a5e74efffefe3ec4d7b1b6dcc066c5f7 | bigcode/the-stack | train |
e93a3847d69f29f06dee6e1e | train | class | class GitCmdObjectDB(LooseObjectDB):
"""A database representing the default git object store, which includes loose
objects, pack files and an alternates file
It will create objects only in the loose object database.
:note: for now, we use the git command to do all the lookup, just until he
hav... | class GitCmdObjectDB(LooseObjectDB):
| """A database representing the default git object store, which includes loose
objects, pack files and an alternates file
It will create objects only in the loose object database.
:note: for now, we use the git command to do all the lookup, just until he
have packs and the other implementations
... | git command"""
from git.util import bin_to_hex, hex_to_bin
from gitdb.base import (
OInfo,
OStream
)
from gitdb.db import GitDB # @UnusedImport
from gitdb.db import LooseObjectDB
from .exc import (
GitCommandError,
BadObject
)
__all__ = ('GitCmdObjectDB', 'GitDB')
# class GitCmdObjectDB(CompoundDB... | 105 | 106 | 355 | 10 | 95 | Harmon758/GitPython | git/db.py | Python | GitCmdObjectDB | GitCmdObjectDB | 21 | 57 | 21 | 22 | ccd9094327b1137544e4b80bc93473eeea701630 | bigcode/the-stack | train |
13d42ac65b08b2208200c7ab | train | function | def embedding_attention_seq2seq(encoder_inputs, decoder_inputs, cell,
num_encoder_symbols, num_decoder_symbols,
embedding_size,
num_heads=1, output_projection=None,
feed_previous=False, dtype=... | def embedding_attention_seq2seq(encoder_inputs, decoder_inputs, cell,
num_encoder_symbols, num_decoder_symbols,
embedding_size,
num_heads=1, output_projection=None,
feed_previous=False, dtype=... | """Embedding sequence-to-sequence model with attention.
This model first embeds encoder_inputs by a newly created embedding (of shape
[num_encoder_symbols x input_size]). Then it runs an RNN to encode
embedded encoder_inputs into a state vector. It keeps the outputs of this
RNN at every step to use for atten... | wrong shape.
"""
if output_size is None:
output_size = cell.output_size
if output_projection is not None:
proj_biases = ops.convert_to_tensor(output_projection[1], dtype=dtype)
proj_biases.get_shape().assert_is_compatible_with([num_symbols])
with variable_scope.variable_scope(scope or "embedding_a... | 256 | 256 | 1,000 | 58 | 198 | smrutiranjans/tensorflow | tensorflow/python/ops/seq2seq.py | Python | embedding_attention_seq2seq | embedding_attention_seq2seq | 650 | 741 | 650 | 655 | 4ed7531a99f094888b7191670be3c6dc7c0f123e | bigcode/the-stack | train |
ef06c98b538c079d387145b9 | train | function | def rnn_decoder(decoder_inputs, initial_state, cell, loop_function=None,
scope=None):
"""RNN decoder for the sequence-to-sequence model.
Args:
decoder_inputs: A list of 2D Tensors [batch_size x input_size].
initial_state: 2D Tensor with shape [batch_size x cell.state_size].
cell: rnn_ce... | def rnn_decoder(decoder_inputs, initial_state, cell, loop_function=None,
scope=None):
| """RNN decoder for the sequence-to-sequence model.
Args:
decoder_inputs: A list of 2D Tensors [batch_size x input_size].
initial_state: 2D Tensor with shape [batch_size x cell.state_size].
cell: rnn_cell.RNNCell defining the cell function and size.
loop_function: If not None, this function will be ... | through the embeddings.
Returns:
A loop function.
"""
def loop_function(prev, _):
if output_projection is not None:
prev = nn_ops.xw_plus_b(
prev, output_projection[0], output_projection[1])
prev_symbol = math_ops.argmax(prev, 1)
# Note that gradients will not propagate thro... | 148 | 148 | 495 | 21 | 126 | smrutiranjans/tensorflow | tensorflow/python/ops/seq2seq.py | Python | rnn_decoder | rnn_decoder | 104 | 145 | 104 | 105 | 11a788800c19c272893bbb7cc2ae7eb8da026afd | bigcode/the-stack | train |
77ca4f1054f3dcabcea0d269 | train | function | def tied_rnn_seq2seq(encoder_inputs, decoder_inputs, cell,
loop_function=None, dtype=dtypes.float32, scope=None):
"""RNN sequence-to-sequence model with tied encoder and decoder parameters.
This model first runs an RNN to encode encoder_inputs into a state vector, and
then runs decoder, init... | def tied_rnn_seq2seq(encoder_inputs, decoder_inputs, cell,
loop_function=None, dtype=dtypes.float32, scope=None):
| """RNN sequence-to-sequence model with tied encoder and decoder parameters.
This model first runs an RNN to encode encoder_inputs into a state vector, and
then runs decoder, initialized with the last encoder state, on decoder_inputs.
Encoder and decoder use the same RNN cell and share parameters.
Args:
... | D Tensors with
shape [batch_size x output_size] containing the generated outputs.
state: The state of each decoder cell in the final time-step.
It is a 2D Tensor of shape [batch_size x cell.state_size].
"""
with variable_scope.variable_scope(scope or "basic_rnn_seq2seq"):
_, enc_state = rn... | 132 | 132 | 443 | 30 | 102 | smrutiranjans/tensorflow | tensorflow/python/ops/seq2seq.py | Python | tied_rnn_seq2seq | tied_rnn_seq2seq | 175 | 207 | 175 | 176 | 5fb361fa510a15531e109f315657d920dee5679e | bigcode/the-stack | train |
055b0b40a819b8a9be27be51 | train | function | def embedding_rnn_decoder(decoder_inputs, initial_state, cell, num_symbols,
embedding_size, output_projection=None,
feed_previous=False,
update_embedding_for_previous=True, scope=None):
"""RNN decoder with embedding and a pure-decoding opti... | def embedding_rnn_decoder(decoder_inputs, initial_state, cell, num_symbols,
embedding_size, output_projection=None,
feed_previous=False,
update_embedding_for_previous=True, scope=None):
| """RNN decoder with embedding and a pure-decoding option.
Args:
decoder_inputs: A list of 1D batch-sized int32 Tensors (decoder inputs).
initial_state: 2D Tensor [batch_size x cell.state_size].
cell: rnn_cell.RNNCell defining the cell function.
num_symbols: Integer, how many symbols come into the e... | the same length as decoder_inputs of 2D Tensors with
shape [batch_size x output_size] containing the generated outputs.
state: The state of each decoder cell in each time-step. This is a list
with length len(decoder_inputs) -- one item for each time-step.
It is a 2D Tensor of shape [batch... | 212 | 212 | 709 | 40 | 172 | smrutiranjans/tensorflow | tensorflow/python/ops/seq2seq.py | Python | embedding_rnn_decoder | embedding_rnn_decoder | 210 | 269 | 210 | 213 | 38bdb247ae0b1fdec5ff71b7b824235773be92b5 | bigcode/the-stack | train |
9c4fca0ff35fe6fe47ee5912 | train | function | def embedding_rnn_seq2seq(encoder_inputs, decoder_inputs, cell,
num_encoder_symbols, num_decoder_symbols,
embedding_size, output_projection=None,
feed_previous=False, dtype=dtypes.float32,
scope=None):
"""Embedding... | def embedding_rnn_seq2seq(encoder_inputs, decoder_inputs, cell,
num_encoder_symbols, num_decoder_symbols,
embedding_size, output_projection=None,
feed_previous=False, dtype=dtypes.float32,
scope=None):
| """Embedding RNN sequence-to-sequence model.
This model first embeds encoder_inputs by a newly created embedding (of shape
[num_encoder_symbols x input_size]). Then it runs an RNN to encode
embedded encoder_inputs into a state vector. Next, it embeds decoder_inputs
by another newly created embedding (of shap... | shape.
"""
if output_projection is not None:
proj_weights = ops.convert_to_tensor(output_projection[0],
dtype=dtypes.float32)
proj_weights.get_shape().assert_is_compatible_with([None, num_symbols])
proj_biases = ops.convert_to_tensor(
output_projection[1... | 249 | 249 | 832 | 48 | 201 | smrutiranjans/tensorflow | tensorflow/python/ops/seq2seq.py | Python | embedding_rnn_seq2seq | embedding_rnn_seq2seq | 272 | 347 | 272 | 276 | ee808309dbe27f27346e3cbbef5a925541b3723f | bigcode/the-stack | train |
eeca0c06c1bb8ba3b62bf7de | train | function | def embedding_tied_rnn_seq2seq(encoder_inputs, decoder_inputs, cell,
num_symbols, embedding_size,
output_projection=None, feed_previous=False,
dtype=dtypes.float32, scope=None):
"""Embedding RNN sequence-to-sequence model wit... | def embedding_tied_rnn_seq2seq(encoder_inputs, decoder_inputs, cell,
num_symbols, embedding_size,
output_projection=None, feed_previous=False,
dtype=dtypes.float32, scope=None):
| """Embedding RNN sequence-to-sequence model with tied (shared) parameters.
This model first embeds encoder_inputs by a newly created embedding (of shape
[num_symbols x input_size]). Then it runs an RNN to encode embedded
encoder_inputs into a state vector. Next, it embeds decoder_inputs using
the same embedd... | output_projection is None:
cell = rnn_cell.OutputProjectionWrapper(cell, num_decoder_symbols)
if isinstance(feed_previous, bool):
return embedding_rnn_decoder(
decoder_inputs, encoder_state, cell, num_decoder_symbols,
embedding_size, output_projection=output_projection,
f... | 256 | 256 | 916 | 44 | 212 | smrutiranjans/tensorflow | tensorflow/python/ops/seq2seq.py | Python | embedding_tied_rnn_seq2seq | embedding_tied_rnn_seq2seq | 350 | 431 | 350 | 353 | 0a59a4f2615dfe9b3f50a00c7950f6bd555d8151 | bigcode/the-stack | train |
76405a086f3750a15061f234 | train | function | def embedding_attention_decoder(decoder_inputs, initial_state, attention_states,
cell, num_symbols, embedding_size, num_heads=1,
output_size=None, output_projection=None,
feed_previous=False,
... | def embedding_attention_decoder(decoder_inputs, initial_state, attention_states,
cell, num_symbols, embedding_size, num_heads=1,
output_size=None, output_projection=None,
feed_previous=False,
... | """RNN decoder with embedding and attention and a pure-decoding option.
Args:
decoder_inputs: A list of 1D batch-sized int32 Tensors (decoder inputs).
initial_state: 2D Tensor [batch_size x cell.state_size].
attention_states: 3D Tensor [batch_size x attn_length x attn_size].
cell: rnn_cell.RNNCell ... | _size = inp.get_shape().with_rank(2)[1]
if input_size.value is None:
raise ValueError("Could not infer input size from input: %s" % inp.name)
x = rnn_cell.linear([inp] + attns, input_size, True)
# Run the RNN.
cell_output, state = cell(x, state)
# Run the attention mechanism.
... | 250 | 250 | 835 | 65 | 184 | smrutiranjans/tensorflow | tensorflow/python/ops/seq2seq.py | Python | embedding_attention_decoder | embedding_attention_decoder | 578 | 647 | 578 | 584 | a3696ad89f030fc1d8a98f593c64e57f197b32d5 | bigcode/the-stack | train |
eb2a58f4c6396fb7777fe3bd | train | function | def basic_rnn_seq2seq(
encoder_inputs, decoder_inputs, cell, dtype=dtypes.float32, scope=None):
"""Basic RNN sequence-to-sequence model.
This model first runs an RNN to encode encoder_inputs into a state vector,
then runs decoder, initialized with the last encoder state, on decoder_inputs.
Encoder and deco... | def basic_rnn_seq2seq(
encoder_inputs, decoder_inputs, cell, dtype=dtypes.float32, scope=None):
| """Basic RNN sequence-to-sequence model.
This model first runs an RNN to encode encoder_inputs into a state vector,
then runs decoder, initialized with the last encoder state, on decoder_inputs.
Encoder and decoder use the same RNN cell type, but don't share parameters.
Args:
encoder_inputs: A list of 2... | .variable_scope("loop_function", reuse=True):
inp = loop_function(prev, i)
if i > 0:
variable_scope.get_variable_scope().reuse_variables()
output, state = cell(inp, state)
outputs.append(output)
if loop_function is not None:
prev = output
return outputs, state
def bas... | 95 | 95 | 319 | 26 | 68 | smrutiranjans/tensorflow | tensorflow/python/ops/seq2seq.py | Python | basic_rnn_seq2seq | basic_rnn_seq2seq | 148 | 172 | 148 | 149 | 0765553925a878f4468bb3e56caf0c400ee24c32 | bigcode/the-stack | train |
edda66ea073232c8c716b728 | train | function | def attention_decoder(decoder_inputs, initial_state, attention_states, cell,
output_size=None, num_heads=1, loop_function=None,
dtype=dtypes.float32, scope=None,
initial_state_attention=False):
"""RNN decoder with attention for the sequence-to-sequence... | def attention_decoder(decoder_inputs, initial_state, attention_states, cell,
output_size=None, num_heads=1, loop_function=None,
dtype=dtypes.float32, scope=None,
initial_state_attention=False):
| """RNN decoder with attention for the sequence-to-sequence model.
In this context "attention" means that, during decoding, the RNN can look up
information in the additional tensor attention_states, and it does this by
focusing on a few entries from the tensor. This model has proven to yield
especially good r... | = _extract_argmax_and_embed(
embedding, output_projection, True) if feed_previous else None
return tied_rnn_seq2seq(emb_encoder_inputs, emb_decoder_inputs, cell,
loop_function=loop_function, dtype=dtype)
# If feed_previous is a Tensor, we construct 2 graphs and use co... | 256 | 256 | 1,689 | 45 | 211 | smrutiranjans/tensorflow | tensorflow/python/ops/seq2seq.py | Python | attention_decoder | attention_decoder | 434 | 575 | 434 | 437 | d03e1879bb2162e3572ce1639ce363c2f14ea68d | bigcode/the-stack | train |
c97f518e4cbfc1032730563f | train | function | def one2many_rnn_seq2seq(encoder_inputs, decoder_inputs_dict, cell,
num_encoder_symbols, num_decoder_symbols_dict,
embedding_size, feed_previous=False,
dtype=dtypes.float32, scope=None):
"""One-to-many RNN sequence-to-sequence model (multi-tas... | def one2many_rnn_seq2seq(encoder_inputs, decoder_inputs_dict, cell,
num_encoder_symbols, num_decoder_symbols_dict,
embedding_size, feed_previous=False,
dtype=dtypes.float32, scope=None):
| """One-to-many RNN sequence-to-sequence model (multi-task).
This is a multi-task sequence-to-sequence model with one encoder and multiple
decoders. Reference to multi-task sequence-to-sequence learning can be found
here: http://arxiv.org/abs/1511.06114
Args:
encoder_inputs: A list of 1D int32 Tensors of... | _symbols, embedding_size, num_heads=num_heads,
output_size=output_size, output_projection=output_projection,
feed_previous=feed_previous,
initial_state_attention=initial_state_attention)
# If feed_previous is a Tensor, we construct 2 graphs and use cond.
def decoder(feed_previous_... | 256 | 256 | 911 | 47 | 209 | smrutiranjans/tensorflow | tensorflow/python/ops/seq2seq.py | Python | one2many_rnn_seq2seq | one2many_rnn_seq2seq | 744 | 829 | 744 | 747 | c0e5c96599f36d1552d729c65ac8e8bc637e3d46 | bigcode/the-stack | train |
1cd1952154e86feeafa0d81f | train | function | def model_with_buckets(encoder_inputs, decoder_inputs, targets, weights,
buckets, seq2seq, softmax_loss_function=None,
per_example_loss=False, name=None):
"""Create a sequence-to-sequence model with support for bucketing.
The seq2seq argument is a function that defines... | def model_with_buckets(encoder_inputs, decoder_inputs, targets, weights,
buckets, seq2seq, softmax_loss_function=None,
per_example_loss=False, name=None):
| """Create a sequence-to-sequence model with support for bucketing.
The seq2seq argument is a function that defines a sequence-to-sequence model,
e.g., seq2seq = lambda x, y: basic_rnn_seq2seq(x, y, rnn_cell.GRUCell(24))
Args:
encoder_inputs: A list of Tensors to feed the encoder; first seq2seq input.
... | cost by the batch size.
softmax_loss_function: Function (inputs-batch, labels-batch) -> loss-batch
to be used instead of the standard softmax (the default if this is None).
name: Optional name for this operation, defaults to "sequence_loss".
Returns:
A scalar float Tensor: The average log-perplexi... | 247 | 247 | 825 | 38 | 208 | smrutiranjans/tensorflow | tensorflow/python/ops/seq2seq.py | Python | model_with_buckets | model_with_buckets | 912 | 976 | 912 | 914 | f52ddca54d6b20a295724cc61c6d2041a28dfebe | bigcode/the-stack | train |
ba2e745b4b2bc7bbc830e9fc | train | function | def _extract_argmax_and_embed(embedding, output_projection=None,
update_embedding=True):
"""Get a loop_function that extracts the previous symbol and embeds it.
Args:
embedding: embedding tensor for symbols.
output_projection: None or a pair (W, B). If provided, each fed previ... | def _extract_argmax_and_embed(embedding, output_projection=None,
update_embedding=True):
| """Get a loop_function that extracts the previous symbol and embeds it.
Args:
embedding: embedding tensor for symbols.
output_projection: None or a pair (W, B). If provided, each fed previous
output will first be multiplied by W and added B.
update_embedding: Boolean; if False, the gradients will... | .ops import embedding_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import nn_ops
from tensorflow.python.ops import rnn
from tensorflow.python.ops import rnn_cell
from tensorflow.python.ops import variable_scope
def _extract_argmax_and_embed(embedding, output_projection=None,
... | 65 | 65 | 219 | 19 | 45 | smrutiranjans/tensorflow | tensorflow/python/ops/seq2seq.py | Python | _extract_argmax_and_embed | _extract_argmax_and_embed | 76 | 101 | 76 | 77 | 64ef3456e51f118d5a28df5111672c65a83fffda | bigcode/the-stack | train |
d4c26cda9ba9a41ae778c2e5 | train | function | def sequence_loss_by_example(logits, targets, weights,
average_across_timesteps=True,
softmax_loss_function=None, name=None):
"""Weighted cross-entropy loss for a sequence of logits (per example).
Args:
logits: List of 2D Tensors of shape [batch_size x ... | def sequence_loss_by_example(logits, targets, weights,
average_across_timesteps=True,
softmax_loss_function=None, name=None):
| """Weighted cross-entropy loss for a sequence of logits (per example).
Args:
logits: List of 2D Tensors of shape [batch_size x num_decoder_symbols].
targets: List of 1D batch-sized int32 Tensors of the same length as logits.
weights: List of 1D batch-sized float-Tensors of the same length as logits.
... | = embedding_rnn_decoder(
decoder_inputs, encoder_state, decoder_cell,
num_decoder_symbols, embedding_size,
feed_previous=feed_previous)
# pylint: enable=cell-var-from-loop
return outputs + [state]
outputs_and_state = control_flow_o... | 156 | 156 | 520 | 30 | 125 | smrutiranjans/tensorflow | tensorflow/python/ops/seq2seq.py | Python | sequence_loss_by_example | sequence_loss_by_example | 832 | 875 | 832 | 834 | 6d38d003961617a5580a1829dafc80bafafcebc3 | bigcode/the-stack | train |
1bc3ce05dfeca7b4241bbee2 | train | function | def sequence_loss(logits, targets, weights,
average_across_timesteps=True, average_across_batch=True,
softmax_loss_function=None, name=None):
"""Weighted cross-entropy loss for a sequence of logits, batch-collapsed.
Args:
logits: List of 2D Tensors of shape [batch_size x num... | def sequence_loss(logits, targets, weights,
average_across_timesteps=True, average_across_batch=True,
softmax_loss_function=None, name=None):
| """Weighted cross-entropy loss for a sequence of logits, batch-collapsed.
Args:
logits: List of 2D Tensors of shape [batch_size x num_decoder_symbols].
targets: List of 1D batch-sized int32 Tensors of the same length as logits.
weights: List of 1D batch-sized float-Tensors of the same length as logits.... | * weight)
log_perps = math_ops.add_n(log_perp_list)
if average_across_timesteps:
total_size = math_ops.add_n(weights)
total_size += 1e-12 # Just to avoid division by 0 for all-0 weights.
log_perps /= total_size
return log_perps
def sequence_loss(logits, targets, weights,
... | 107 | 107 | 359 | 34 | 72 | smrutiranjans/tensorflow | tensorflow/python/ops/seq2seq.py | Python | sequence_loss | sequence_loss | 878 | 909 | 878 | 880 | 1aee555bf7a0f0101ffb6833a816823cc17cd4d1 | bigcode/the-stack | train |
d68b3fde142bdde41d2a8e6a | train | function | @app.route('/')
def parase_request():
page = request.args.get('timestamp')
craw = newcraw.newcraw()
if str(len(str(page))) != 0:
sateSQL = []
SQL1 = NASASQL.NASASQL(1234)
SQL1.connect_SQL()
SQL1.insert_SQL("1601711620","hi","12.081128","12.081128","12.081128")
... | @app.route('/')
def parase_request():
| page = request.args.get('timestamp')
craw = newcraw.newcraw()
if str(len(str(page))) != 0:
sateSQL = []
SQL1 = NASASQL.NASASQL(1234)
SQL1.connect_SQL()
SQL1.insert_SQL("1601711620","hi","12.081128","12.081128","12.081128")
SQL1.insert_SQL("1601711621","hi",... | from flask import Flask, request
from module import NASASQL
import newcraw
app = Flask(__name__)
@app.route('/')
def parase_request():
| 33 | 64 | 212 | 8 | 25 | William-Mou/satellite-tracker-backend | db.py | Python | parase_request | parase_request | 8 | 28 | 8 | 9 | 6d121f4d0a4d93ccadece38ca13a6ee2732ba54d | bigcode/the-stack | train |
aa4a76f3d9965c0e273d335e | train | function | def get_app(
functions_client: functions.FunctionsManagementClient,
app_name: str, compartment: identity_models.Compartment) -> fn_models.Application:
"""
Identifies app object by its name
:param functions_client: OCI Functions client
:type functions_client: oci.functions.FunctionsManage... | def get_app(
functions_client: functions.FunctionsManagementClient,
app_name: str, compartment: identity_models.Compartment) -> fn_models.Application:
| """
Identifies app object by its name
:param functions_client: OCI Functions client
:type functions_client: oci.functions.FunctionsManagementClient
:param app_name: OCI Functions app name
:type app_name: str
:param compartment: OCI tenancy compartment
:type compartment: oci.identity.mode... | for c in result.data:
if compartment_name == c.name:
print(type(c))
return c
raise Exception("compartment not found")
def get_app(
functions_client: functions.FunctionsManagementClient,
app_name: str, compartment: identity_models.Compartment) -> fn_models.Applicatio... | 64 | 64 | 183 | 32 | 32 | denismakogon/fn-python-sdk-invoke | invoke_function.py | Python | get_app | get_app | 36 | 59 | 36 | 38 | dc406fab2eddd323a2971a2492a461a88d8d3392 | bigcode/the-stack | train |
8ca12bddf64cc755cef24045 | train | function | def get_compartment(oci_cfg, compartment_name: str) -> identity_models.Compartment:
"""
Identifies compartment ID by its name within the particular tenancy
:param oci_cfg: OCI auth config
:param compartment_name: OCI tenancy compartment name
:return: OCI tenancy compartment
"""
identity_clie... | def get_compartment(oci_cfg, compartment_name: str) -> identity_models.Compartment:
| """
Identifies compartment ID by its name within the particular tenancy
:param oci_cfg: OCI auth config
:param compartment_name: OCI tenancy compartment name
:return: OCI tenancy compartment
"""
identity_client = identity.IdentityClient(oci_cfg)
result = pagination.list_call_get_all_resu... |
from oci import config
from oci import functions
from oci import identity
from oci import pagination
from oci.identity import models as identity_models
from oci.functions import models as fn_models
def get_compartment(oci_cfg, compartment_name: str) -> identity_models.Compartment:
| 64 | 64 | 151 | 19 | 44 | denismakogon/fn-python-sdk-invoke | invoke_function.py | Python | get_compartment | get_compartment | 14 | 33 | 14 | 14 | 84541286aef686766e5bf7e2fa6739ef43a7830d | bigcode/the-stack | train |
b3c0e347ff9c2018c3396070 | train | function | def get_function(functions_client: functions.FunctionsManagementClient,
app: fn_models.Application,
function_name: str) -> fn_models.Function:
"""
Identifies function object by its name
:param functions_client: OCI Functions client
:type functions_client: oci.functions.... | def get_function(functions_client: functions.FunctionsManagementClient,
app: fn_models.Application,
function_name: str) -> fn_models.Function:
| """
Identifies function object by its name
:param functions_client: OCI Functions client
:type functions_client: oci.functions.FunctionsManagementClient
:param app: OCI Functions app
:type app: oci.functions.models.Application
:param function_name: OCI Functions function name
:type funct... | for app in result.data:
if app_name == app.display_name:
print(type(app))
return app
raise Exception("app not found")
def get_function(functions_client: functions.FunctionsManagementClient,
app: fn_models.Application,
function_name: str) -> fn_m... | 64 | 64 | 194 | 31 | 33 | denismakogon/fn-python-sdk-invoke | invoke_function.py | Python | get_function | get_function | 62 | 87 | 62 | 64 | 0edde4d47960e67b4629f8070941f5f824e1783a | bigcode/the-stack | train |
94cde128f1277cd4688cdc25 | train | class | class EmailForm(forms.ModelForm):
class Meta:
model = EmailAddress
fields = ["address"] | class EmailForm(forms.ModelForm):
| class Meta:
model = EmailAddress
fields = ["address"] | from django import forms
from .models import EmailAddress
class EmailForm(forms.ModelForm):
| 19 | 64 | 23 | 7 | 11 | kermox/schronisko-krakow | mails/forms.py | Python | EmailForm | EmailForm | 6 | 9 | 6 | 6 | 0a7920584576714aed4d3faefde72b748e4c9203 | bigcode/the-stack | train |
e61ed5317fbf312d441d3b28 | train | class | class TextAnalyticsClient(TextAnalyticsClientOperationsMixin):
"""The Text Analytics API is a suite of text analytics web services built with best-in-class Microsoft machine learning algorithms. The API can be used to analyze unstructured text for tasks such as sentiment analysis, key phrase extraction and language... | class TextAnalyticsClient(TextAnalyticsClientOperationsMixin):
| """The Text Analytics API is a suite of text analytics web services built with best-in-class Microsoft machine learning algorithms. The API can be used to analyze unstructured text for tasks such as sentiment analysis, key phrase extraction and language detection. No training data is needed to use this API; just br... | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------... | 121 | 121 | 406 | 10 | 110 | iscai-msft/azure-sdk-for-python | sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/aio/_text_analytics_client_async.py | Python | TextAnalyticsClient | TextAnalyticsClient | 19 | 52 | 19 | 19 | 86d5ee1291bd1afae71ce87201ba284d4c9d6d86 | bigcode/the-stack | train |
b4d984292fd595c03f98b276 | train | class | class InlineQrCodeTest(SimpleTestCase):
"""
Test the inline QR Code Tag
"""
def test_context(self):
"""
Test the context
"""
context = do_inline_otp_qr_code('test_user', b32encode(b'ThisIsJustATestSecretForASimpleUnitTestHere'))
self.assertIsInstance(context, dic... | class InlineQrCodeTest(SimpleTestCase):
| """
Test the inline QR Code Tag
"""
def test_context(self):
"""
Test the context
"""
context = do_inline_otp_qr_code('test_user', b32encode(b'ThisIsJustATestSecretForASimpleUnitTestHere'))
self.assertIsInstance(context, dict)
self.assertIn('qr_img_data', ... | """
Tests for the otp template tags
"""
from base64 import b32encode
from django.test import SimpleTestCase
from hub_app.templatetags.hub_app_otp import do_inline_otp_qr_code
class InlineQrCodeTest(SimpleTestCase):
| 55 | 64 | 122 | 9 | 45 | passiopeia/passiopeia-hub | hub_app/tests/test_templatetags_otp.py | Python | InlineQrCodeTest | InlineQrCodeTest | 11 | 24 | 11 | 11 | 971b01415aff43ff229f7315e69fae496da45bdd | bigcode/the-stack | train |
cf6e5c149d18802da20ad14a | train | function | def random_unitary_basis(kappa):
Ax1 = random_2d_rotation_in_3d('x', kappa)
Ay1 = random_2d_rotation_in_3d('y', kappa)
Az1 = random_2d_rotation_in_3d('z', kappa)
Ax2 = random_2d_rotation_in_3d('x', kappa)
Ay1 = random_2d_rotation_in_3d('y', kappa)
Az1 = random_2d_rotation_in_3d('z', kappa)
A... | def random_unitary_basis(kappa):
| Ax1 = random_2d_rotation_in_3d('x', kappa)
Ay1 = random_2d_rotation_in_3d('y', kappa)
Az1 = random_2d_rotation_in_3d('z', kappa)
Ax2 = random_2d_rotation_in_3d('x', kappa)
Ay1 = random_2d_rotation_in_3d('y', kappa)
Az1 = random_2d_rotation_in_3d('z', kappa)
A = np.dot(np.dot(Ax1,Ay1),Az1)
... | """Collection of tools for probability distributions"""
import numpy as np
def random_unitary_basis(kappa):
| 21 | 64 | 163 | 8 | 12 | McmcNeuron/Generator | McNeuron/prob_util.py | Python | random_unitary_basis | random_unitary_basis | 4 | 13 | 4 | 4 | 357ca463be184f83c0d19185feab3a08e9549d9f | bigcode/the-stack | train |
973505c24f5ea0a5c43e5564 | train | function | def random_2d_rotation_in_3d(axis, kappa):
theta = np.random.vonmises(0, kappa, 1)
A = np.eye(3)
if axis is 'z':
A[0,0] = np.cos(theta)
A[1,0] = np.sin(theta)
A[0,1] = - np.sin(theta)
A[1,1] = np.cos(theta)
return A
if axis is 'y':
A[0,0] = np.cos(theta)
... | def random_2d_rotation_in_3d(axis, kappa):
| theta = np.random.vonmises(0, kappa, 1)
A = np.eye(3)
if axis is 'z':
A[0,0] = np.cos(theta)
A[1,0] = np.sin(theta)
A[0,1] = - np.sin(theta)
A[1,1] = np.cos(theta)
return A
if axis is 'y':
A[0,0] = np.cos(theta)
A[2,0] = np.sin(theta)
A[0,2... | _in_3d('z', kappa)
A = np.dot(np.dot(Ax1,Ay1),Az1)
B = np.dot(np.dot(Az1,Ay1),Ax1)
return np.dot(A,B)
def random_2d_rotation_in_3d(axis, kappa):
| 66 | 66 | 221 | 15 | 51 | McmcNeuron/Generator | McNeuron/prob_util.py | Python | random_2d_rotation_in_3d | random_2d_rotation_in_3d | 15 | 35 | 15 | 15 | b48cf09f1cbba035d5e6aa997c9da757a0c5b703 | bigcode/the-stack | train |
afed98b9b532d609ef2c0919 | train | function | def load_game():
a = input('Пожалуйста, введите ID сохранения, которую вы хотите загрузить: ')
| def load_game():
| a = input('Пожалуйста, введите ID сохранения, которую вы хотите загрузить: ')
| passw={}'.format(games_count, user, passw))
ACTIVATED_GAME = games_count
with open('saves.json', mode='w') as f:
dict = {}
dict['count'] = games_count + 1
json.dump(dict, f)
def load_game():
| 64 | 64 | 26 | 4 | 60 | ZerZru/hacktheworld | 1.0.1/__init__.py | Python | load_game | load_game | 58 | 59 | 58 | 58 | 5cf34d163be9f1d750e66c6dc8e6a0e55ed5bf17 | bigcode/the-stack | train |
2826e60720ba4c943bf218fe | train | function | def ghelp():
print(helping_info[0], helping_info[1], helping_info[2])
| def ghelp():
| print(helping_info[0], helping_info[1], helping_info[2])
| aves.json', mode='w') as f:
dict = {}
dict['count'] = games_count + 1
json.dump(dict, f)
def load_game():
a = input('Пожалуйста, введите ID сохранения, которую вы хотите загрузить: ')
def ghelp():
| 63 | 64 | 22 | 4 | 59 | ZerZru/hacktheworld | 1.0.1/__init__.py | Python | ghelp | ghelp | 61 | 62 | 61 | 61 | dd0d57896469c4fd55205c1edb0b6b8b79b3d79a | bigcode/the-stack | train |
b717022e9495333c212d33fa | train | function | def exit():
quit() | def exit():
| quit() | json.dump(dict, f)
def load_game():
a = input('Пожалуйста, введите ID сохранения, которую вы хотите загрузить: ')
def ghelp():
print(helping_info[0], helping_info[1], helping_info[2])
#def save_game():
def exit():
| 63 | 64 | 6 | 3 | 60 | ZerZru/hacktheworld | 1.0.1/__init__.py | Python | exit | exit | 67 | 68 | 67 | 67 | 99f993e4e25532b5b8f4027972176064bc8906ff | bigcode/the-stack | train |
e9de8d23256f89da963a7d60 | train | function | def new_game():
user = input('Пожалуйста, введите своё имя: ')
passw = input('Придумайте пароль для игры: ')
with open('saves.json', mode='r') as f:
data = json.load(f)
games_count = data['count']
with open('saved_games.ini', mode='a') as f:
f.write('\n\n[game_{}]\nuse... | def new_game():
| user = input('Пожалуйста, введите своё имя: ')
passw = input('Придумайте пароль для игры: ')
with open('saves.json', mode='r') as f:
data = json.load(f)
games_count = data['count']
with open('saved_games.ini', mode='a') as f:
f.write('\n\n[game_{}]\nuser={}\npassw={}'.f... | о функции, игре или авторстве программы,'
+ 'введите название функции, game_info или authors\n'
]
#defining functions
def menu(): #function menu,
print(start_menu[0], start_menu[1], start_menu[2], start_menu[3])
def new_game():
| 64 | 64 | 157 | 4 | 60 | ZerZru/hacktheworld | 1.0.1/__init__.py | Python | new_game | new_game | 41 | 56 | 41 | 41 | 5aa99ca8ed70b5089933c9634325ec9917b015e1 | bigcode/the-stack | train |
26bd279dfceb6d95c733fbe6 | train | function | def menu(): #function menu,
print(start_menu[0], start_menu[1], start_menu[2], start_menu[3])
| def menu(): #function menu,
| print(start_menu[0], start_menu[1], start_menu[2], start_menu[3])
| World: гайды\n',
'Здесь вы можете получить любую интересующую вас информацию\n',
'Чтобы получить информацию о функции, игре или авторстве программы,'
+ 'введите название функции, game_info или authors\n'
]
#defining functions
def menu(): #function menu,
| 64 | 64 | 30 | 8 | 55 | ZerZru/hacktheworld | 1.0.1/__init__.py | Python | menu | menu | 38 | 39 | 38 | 38 | 6c9d84656d596176ac601ef556d0e51369fe6cef | bigcode/the-stack | train |
79078ee5794a8439f9825b91 | train | class | class Scaler:
def __init__(self, parameter_limits):
'''
Scaler object to convert a point in parameter space to a dimensionless
coordinate with all points between 0 and 1
Parameters
----------
parameter_limits : array_like, shape (n_variables, 2)
The limit... | class Scaler:
| def __init__(self, parameter_limits):
'''
Scaler object to convert a point in parameter space to a dimensionless
coordinate with all points between 0 and 1
Parameters
----------
parameter_limits : array_like, shape (n_variables, 2)
The limits on each para... | '''
_scaler
Scaler object to convert points with dimensions into dimensionless space with
variables in the range [0,1)
'''
import numpy as np
class Scaler:
| 36 | 217 | 724 | 4 | 31 | joshjchayes/RetrievalAccuracy | retrievalaccuracy/_scaler.py | Python | Scaler | Scaler | 10 | 97 | 10 | 10 | 11abc70be0c1863429d566ff93dc3d67d43b0edc | bigcode/the-stack | train |
220ba861600349b22f154055 | train | class | @register_optimizer('adashift')
class FairseqAdaShift(FairseqOptimizer):
def __init__(self, args, params):
super().__init__(args, params)
self._optimizer = adashift.AdaShift(params, **self.optimizer_config)
@staticmethod
def add_args(parser):
"""Add optimizer-specific arguments to t... | @register_optimizer('adashift')
class FairseqAdaShift(FairseqOptimizer):
| def __init__(self, args, params):
super().__init__(args, params)
self._optimizer = adashift.AdaShift(params, **self.optimizer_config)
@staticmethod
def add_args(parser):
"""Add optimizer-specific arguments to the parser."""
# fmt: off
parser.add_argument('--adashift-... | import torch.optim
from . import FairseqOptimizer, register_optimizer
import math
import sys
sys.path.append('..')
sys.path.append('..')
sys.path.append('..')
from optims import adashift
@register_optimizer('adashift')
class FairseqAdaShift(FairseqOptimizer):
| 64 | 103 | 344 | 18 | 45 | Vicky-Wil/NLE_CLR_NMT | fairseq_master/fairseq/optim/adashift.py | Python | FairseqAdaShift | FairseqAdaShift | 15 | 51 | 15 | 16 | 083aeecd80c5095842b7c017acb38eb0ed33c66d | bigcode/the-stack | train |
8a608a95472c224a32087bc5 | train | class | class IntegerOption(Option):
"""An option allowing a range of integers."""
def __init__(self, minimum=1, maximum=None, prefix='', **kwargs):
"""Initializer."""
super(IntegerOption, self).__init__(**kwargs)
if not ((minimum is None or isinstance(minimum, int))
an... | class IntegerOption(Option):
| """An option allowing a range of integers."""
def __init__(self, minimum=1, maximum=None, prefix='', **kwargs):
"""Initializer."""
super(IntegerOption, self).__init__(**kwargs)
if not ((minimum is None or isinstance(minimum, int))
and (maximum is None or isinstance... | super(ContextOption, self).__init__(option, shortcut, stop=False)
self.text = text
self.context = context
self.delta = delta
self.start = start
self.end = end
def result(self, value):
"""Add the delta to the context and output it."""
self.con... | 171 | 172 | 574 | 6 | 165 | Sanechoic/JoyStory | venv/lib/python3.7/site-packages/pywikibot/bot_choice.py | Python | IntegerOption | IntegerOption | 228 | 302 | 228 | 229 | 60baed27495dde699151a7bc2bc06c2d2a75c42a | bigcode/the-stack | train |
44a6c3e688601941f740a489 | train | class | class MultipleChoiceList(ListOption):
"""An option to select multiple items from a list."""
def test(self, value):
"""Return whether the values are int and in the specified range."""
try:
values = [self.parse(val) for val in value.split(',')]
except ValueError:
... | class MultipleChoiceList(ListOption):
| """An option to select multiple items from a list."""
def test(self, value):
"""Return whether the values are int and in the specified range."""
try:
values = [self.parse(val) for val in value.split(',')]
except ValueError:
return False
for val ... | (str(self.maximum))
for i, item in enumerate(self._list, self.minimum):
pywikibot.output('{:>{width}} - {}'.format(i, item, width=width))
if self.post is not None:
pywikibot.output(self.post)
class MultipleChoiceList(ListOption):
| 64 | 64 | 182 | 7 | 57 | Sanechoic/JoyStory | venv/lib/python3.7/site-packages/pywikibot/bot_choice.py | Python | MultipleChoiceList | MultipleChoiceList | 369 | 394 | 369 | 370 | 3bcd048be351fb5daed0d7728416d06e976ba9b9 | bigcode/the-stack | train |
68ac52bb24f3914a9739bee4 | train | class | class ShowingMultipleChoiceList(ShowingListOption, MultipleChoiceList):
"""An option to show a list and select multiple items."""
pass
| class ShowingMultipleChoiceList(ShowingListOption, MultipleChoiceList):
| """An option to show a list and select multiple items."""
pass
| the prefix and selected values as a list."""
values = (self.parse(val) for val in value.split(','))
result = [self._list[val - 1] for val in values]
return (self.prefix, result)
class ShowingMultipleChoiceList(ShowingListOption, MultipleChoiceList):
| 64 | 64 | 31 | 14 | 50 | Sanechoic/JoyStory | venv/lib/python3.7/site-packages/pywikibot/bot_choice.py | Python | ShowingMultipleChoiceList | ShowingMultipleChoiceList | 397 | 401 | 397 | 398 | 218be5db5d62597f2ee175adb1c88e93f391ba28 | bigcode/the-stack | train |
016f4ec79650cbc99af3764b | train | class | class ContextOption(OutputOption, StandardOption):
"""An option to show more and more context."""
def __init__(
self, option, shortcut, text, context, delta=100, start=0, end=0
):
"""Initializer."""
super(ContextOption, self).__init__(option, shortcut, stop=False)
... | class ContextOption(OutputOption, StandardOption):
| """An option to show more and more context."""
def __init__(
self, option, shortcut, text, context, delta=100, start=0, end=0
):
"""Initializer."""
super(ContextOption, self).__init__(option, shortcut, stop=False)
self.text = text
self.context = context
... | handled = option.handled(value)
if handled is not None:
return handled
else:
return super(NestedOption, self).handled(value)
def output(self):
"""Output the suboptions."""
pywikibot.output(self._output)
class ContextOption(OutputOp... | 66 | 66 | 223 | 9 | 57 | Sanechoic/JoyStory | venv/lib/python3.7/site-packages/pywikibot/bot_choice.py | Python | ContextOption | ContextOption | 197 | 225 | 197 | 198 | bb7da1176b5336a7629cee1d400777ab8353a9db | bigcode/the-stack | train |
da8030a906545cffc11de416 | train | class | class OutputOption(Option):
"""An option that never stops and can output on each question."""
before_question = False
@property
def stop(self):
"""Never stop asking."""
return False
def result(self, value):
"""Just output the value."""
self.output()
... | class OutputOption(Option):
| """An option that never stops and can output on each question."""
before_question = False
@property
def stop(self):
"""Never stop asking."""
return False
def result(self, value):
"""Just output the value."""
self.output()
def output(self):
... |
raise NotImplementedError()
def result(self, value):
"""Return the actual value which is associated by the given one."""
raise NotImplementedError()
def test(self, value):
"""Return True whether this option applies."""
raise NotImplementedError()
class OutputO... | 64 | 64 | 91 | 6 | 58 | Sanechoic/JoyStory | venv/lib/python3.7/site-packages/pywikibot/bot_choice.py | Python | OutputOption | OutputOption | 89 | 106 | 89 | 90 | c435b40fc70e15f001342b456139b4fb241702ec | bigcode/the-stack | train |
7ec590482f3223d46cd6c75f | train | class | class HighlightContextOption(ContextOption):
"""Show the original region highlighted."""
def output_range(self, start, end):
"""Show normal context with a red center region."""
pywikibot.output(self.text[start:self.start] + '\03{lightred}'
+ self.text[self.start... | class HighlightContextOption(ContextOption):
| """Show the original region highlighted."""
def output_range(self, start, end):
"""Show normal context with a red center region."""
pywikibot.output(self.text[start:self.start] + '\03{lightred}'
+ self.text[self.start:self.end] + '\03{default}'
... | ))
result = [self._list[val - 1] for val in values]
return (self.prefix, result)
class ShowingMultipleChoiceList(ShowingListOption, MultipleChoiceList):
"""An option to show a list and select multiple items."""
pass
class HighlightContextOption(ContextOption):
| 64 | 64 | 82 | 7 | 56 | Sanechoic/JoyStory | venv/lib/python3.7/site-packages/pywikibot/bot_choice.py | Python | HighlightContextOption | HighlightContextOption | 404 | 412 | 404 | 405 | 5013223f883474999f3bb184e2dc3f2c48b8fcf7 | bigcode/the-stack | train |
0e49a7d0808f4bd6151948d6 | train | class | class ListOption(IntegerOption):
"""An option to select something from a list."""
def __init__(self, sequence, prefix='', **kwargs):
"""Initializer."""
self._list = sequence
try:
super(ListOption, self).__init__(1, self.maximum, prefix, **kwargs)
except Val... | class ListOption(IntegerOption):
| """An option to select something from a list."""
def __init__(self, sequence, prefix='', **kwargs):
"""Initializer."""
self._list = sequence
try:
super(ListOption, self).__init__(1, self.maximum, prefix, **kwargs)
except ValueError:
raise ValueErr... | startswith(self.prefix.lower()):
return int(value[len(self.prefix):])
else:
raise ValueError('Value does not start with prefix')
def result(self, value):
"""Return the value converted into int."""
return (self.prefix, self.parse(value))
class ListOption(Intege... | 63 | 64 | 201 | 6 | 57 | Sanechoic/JoyStory | venv/lib/python3.7/site-packages/pywikibot/bot_choice.py | Python | ListOption | ListOption | 305 | 332 | 305 | 306 | f8ada9f8b556207673c515eaaa8e68e294defd76 | bigcode/the-stack | train |
56e964cd9e89d264b4b20320 | train | class | class ShowingListOption(ListOption, OutputOption):
"""An option to show a list and select an item."""
before_question = True
def __init__(self, sequence, prefix='', pre=None, post=None, **kwargs):
"""Initializer.
@param pre: Additional comment printed before the list.
@... | class ShowingListOption(ListOption, OutputOption):
| """An option to show a list and select an item."""
before_question = True
def __init__(self, sequence, prefix='', pre=None, post=None, **kwargs):
"""Initializer.
@param pre: Additional comment printed before the list.
@type pre: str
@param post: Additional comment... | @property
def maximum(self):
"""Return the maximum value."""
return len(self._list)
def result(self, value):
"""Return a tuple with the prefix and selected value."""
return (self.prefix, self._list[self.parse(value) - 1])
class ShowingListOption(ListOption, OutputOpti... | 71 | 72 | 241 | 10 | 61 | Sanechoic/JoyStory | venv/lib/python3.7/site-packages/pywikibot/bot_choice.py | Python | ShowingListOption | ShowingListOption | 335 | 366 | 335 | 336 | 2854038a1618169836a1158e8fc048e98ed89cfd | bigcode/the-stack | train |
289b7fd01461cbab0a08ea8b | train | class | class Option(object):
"""
A basic option for input_choice.
The following methods need to be implemented:
* format(default=None)
* result(value)
* test(value)
The methods C{test} and C{handled} are in such a relationship that when
C{handled} returns itself that C{test} must ... | class Option(object):
| """
A basic option for input_choice.
The following methods need to be implemented:
* format(default=None)
* result(value)
* test(value)
The methods C{test} and C{handled} are in such a relationship that when
C{handled} returns itself that C{test} must return True for that valu... | # -*- coding: utf-8 -*-
"""Choices for input_choice."""
#
# (C) Pywikibot team, 2015-2019
#
# Distributed under the terms of the MIT license.
#
from __future__ import absolute_import, division, unicode_literals
import re
from textwrap import fill
import pywikibot
class Option(object):
| 78 | 145 | 486 | 4 | 73 | Sanechoic/JoyStory | venv/lib/python3.7/site-packages/pywikibot/bot_choice.py | Python | Option | Option | 16 | 86 | 16 | 17 | 8b1204666028cb2eb8070ed158368fca1efc5265 | bigcode/the-stack | train |
6e238496e419a765954dbee6 | train | class | class QuitKeyboardInterrupt(ChoiceException, KeyboardInterrupt):
"""The user has cancelled processing at a prompt."""
def __init__(self):
"""Constructor using the 'quit' ('q') in input_choice."""
super(QuitKeyboardInterrupt, self).__init__('quit', 'q')
| class QuitKeyboardInterrupt(ChoiceException, KeyboardInterrupt):
| """The user has cancelled processing at a prompt."""
def __init__(self):
"""Constructor using the 'quit' ('q') in input_choice."""
super(QuitKeyboardInterrupt, self).__init__('quit', 'q')
| '
+ self.text[self.end:end])
class ChoiceException(StandardOption, Exception):
"""A choice for input_choice which result in this exception."""
def result(self, value):
"""Return itself to raise the exception."""
return self
class QuitKeyboardInterrupt(Choic... | 64 | 64 | 62 | 11 | 52 | Sanechoic/JoyStory | venv/lib/python3.7/site-packages/pywikibot/bot_choice.py | Python | QuitKeyboardInterrupt | QuitKeyboardInterrupt | 424 | 430 | 424 | 425 | 97383465c35467555e76e6229f6e10ebd2dc091a | bigcode/the-stack | train |
768bd44a2f5d823fcd3df369 | train | class | class StandardOption(Option):
"""An option with a description and shortcut and returning the shortcut."""
def __init__(self, option, shortcut, **kwargs):
"""
Initializer.
@param option: option string
@type option: str
@param shortcut: Shortcut of the option
... | class StandardOption(Option):
| """An option with a description and shortcut and returning the shortcut."""
def __init__(self, option, shortcut, **kwargs):
"""
Initializer.
@param option: option string
@type option: str
@param shortcut: Shortcut of the option
@type shortcut: str
... | output on each question."""
before_question = False
@property
def stop(self):
"""Never stop asking."""
return False
def result(self, value):
"""Just output the value."""
self.output()
def output(self):
"""Output a string when selected and po... | 82 | 82 | 274 | 6 | 76 | Sanechoic/JoyStory | venv/lib/python3.7/site-packages/pywikibot/bot_choice.py | Python | StandardOption | StandardOption | 109 | 146 | 109 | 110 | 5580ef438c4b21b755fe1dffa07af398ea8ef111 | bigcode/the-stack | train |
36aef398ddc1a7d9fd9f58db | train | class | class OutputProxyOption(OutputOption, StandardOption):
"""An option which calls output of the given output class."""
def __init__(self, option, shortcut, output, **kwargs):
"""Create a new option for the given sequence."""
super(OutputProxyOption, self).__init__(option, shortcut, **kwarg... | class OutputProxyOption(OutputOption, StandardOption):
| """An option which calls output of the given output class."""
def __init__(self, option, shortcut, output, **kwargs):
"""Create a new option for the given sequence."""
super(OutputProxyOption, self).__init__(option, shortcut, **kwargs)
self._outputter = output
def output(sel... | Return the lowercased shortcut."""
return self.shortcut
def test(self, value):
"""Return True whether this option applies."""
return (self.shortcut.lower() == value.lower()
or self.option.lower() == value.lower())
class OutputProxyOption(OutputOption, StandardOption):
... | 63 | 64 | 96 | 10 | 53 | Sanechoic/JoyStory | venv/lib/python3.7/site-packages/pywikibot/bot_choice.py | Python | OutputProxyOption | OutputProxyOption | 149 | 160 | 149 | 150 | 05b33b9834cd6aa9eab65f0d1f086bb8dddad0aa | bigcode/the-stack | train |
1888ce677e802fa179e135d0 | train | class | class ChoiceException(StandardOption, Exception):
"""A choice for input_choice which result in this exception."""
def result(self, value):
"""Return itself to raise the exception."""
return self
| class ChoiceException(StandardOption, Exception):
| """A choice for input_choice which result in this exception."""
def result(self, value):
"""Return itself to raise the exception."""
return self
| """Show normal context with a red center region."""
pywikibot.output(self.text[start:self.start] + '\03{lightred}'
+ self.text[self.start:self.end] + '\03{default}'
+ self.text[self.end:end])
class ChoiceException(StandardOption, Exception):
| 63 | 64 | 43 | 8 | 55 | Sanechoic/JoyStory | venv/lib/python3.7/site-packages/pywikibot/bot_choice.py | Python | ChoiceException | ChoiceException | 415 | 421 | 415 | 416 | b3f52afa82dd445836f48548526b9bc730b92ae8 | bigcode/the-stack | train |
8de9c4ca3161c6f750ca13f6 | train | class | class NestedOption(OutputOption, StandardOption):
"""
An option containing other options.
It will return True in test if this option applies but False if a sub
option applies while handle returns the sub option.
"""
def __init__(self, option, shortcut, description, options):
... | class NestedOption(OutputOption, StandardOption):
| """
An option containing other options.
It will return True in test if this option applies but False if a sub
option applies while handle returns the sub option.
"""
def __init__(self, option, shortcut, description, options):
"""Initializer."""
super(NestedOption, self... | **kwargs):
"""Create a new option for the given sequence."""
super(OutputProxyOption, self).__init__(option, shortcut, **kwargs)
self._outputter = output
def output(self):
"""Output the contents."""
self._outputter.output()
class NestedOption(OutputOption, StandardOp... | 68 | 68 | 229 | 9 | 59 | Sanechoic/JoyStory | venv/lib/python3.7/site-packages/pywikibot/bot_choice.py | Python | NestedOption | NestedOption | 163 | 194 | 163 | 164 | 49c7445c485ae5ca464e5c2099c7ee12b55e087c | bigcode/the-stack | train |
eb29a5d9bb00c6d1f9ff4c55 | train | class | class Model(MetricTemplate224):
BACKBONE = 'rres18'
is_advtrain = False
do_svd = False
| class Model(MetricTemplate224):
| BACKBONE = 'rres18'
is_advtrain = False
do_svd = False
| writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
'''
from .template_rank import MetricTemplate224
class Model(Me... | 64 | 64 | 31 | 7 | 56 | yhZhai/robrank | robrank/models/rres18.py | Python | Model | Model | 19 | 22 | 19 | 19 | c971e70d9f7226f51b61e1dcb39ef6541ede1e00 | bigcode/the-stack | train |
441904753f60f7c74485ab4d | train | class | class TestEndToEnd(AbstractEndToEndTest):
__test__ = True
def setUp(self):
""" Create the dataset
"""
rng = np.random.RandomState(0)
vocab_size = 25
nDoc = 10
for d in range(nDoc):
NU_d = rng.choice(vocab_size)
NU_d = np.maximum(1, NU_d)
... | class TestEndToEnd(AbstractEndToEndTest):
| __test__ = True
def setUp(self):
""" Create the dataset
"""
rng = np.random.RandomState(0)
vocab_size = 25
nDoc = 10
for d in range(nDoc):
NU_d = rng.choice(vocab_size)
NU_d = np.maximum(1, NU_d)
word_id_d = rng.choice(vocab_si... | import numpy as np
import unittest
from collections import OrderedDict
import bnpy
from AbstractEndToEndTest import AbstractEndToEndTest
class TestEndToEnd(AbstractEndToEndTest):
| 42 | 183 | 611 | 11 | 30 | jun2tong/bnp-anomaly | tests/endtoend/TestRandomWordsData.py | Python | TestEndToEnd | TestEndToEnd | 9 | 79 | 9 | 9 | 3595161c5689d889039d0b7d623fd18d9eec7ca1 | bigcode/the-stack | train |
83c0f88fa498ac3da01d4633 | train | class | class TestLog(object):
def test_default(self):
log_config = default_config(level="DEBUG")
assert log_config["root"]["level"] == "DEBUG"
def test_configure_logging(self, tmpdir, params, monkeypatch):
raw_config = {
"handlers": {
"file": {
"... | class TestLog(object):
| def test_default(self):
log_config = default_config(level="DEBUG")
assert log_config["root"]["level"] == "DEBUG"
def test_configure_logging(self, tmpdir, params, monkeypatch):
raw_config = {
"handlers": {
"file": {
"class": "logging.handle... | params():
return {
"bg_host": "bg_host",
"bg_port": 1234,
"system_name": "system_name",
"ca_cert": "ca_cert",
"client_cert": "client_cert",
"ssl_enabled": False,
}
class TestLog(object):
| 64 | 64 | 214 | 5 | 59 | scott-taubman/brewtils | test/log_test.py | Python | TestLog | TestLog | 36 | 66 | 36 | 36 | afc0bc98ce22121af5cdd1b1261ba87e3a24ff24 | bigcode/the-stack | train |
4882ed1f602225a5ec0e5854 | train | function | @pytest.fixture
def params():
return {
"bg_host": "bg_host",
"bg_port": 1234,
"system_name": "system_name",
"ca_cert": "ca_cert",
"client_cert": "client_cert",
"ssl_enabled": False,
}
| @pytest.fixture
def params():
| return {
"bg_host": "bg_host",
"bg_port": 1234,
"system_name": "system_name",
"ca_cert": "ca_cert",
"client_cert": "client_cert",
"ssl_enabled": False,
}
| DEFAULT_FORMATTERS,
DEFAULT_HANDLERS,
configure_logging,
convert_logging_config,
default_config,
find_log_file,
get_logging_config,
get_python_logging_config,
read_log_file,
setup_logger,
)
from brewtils.models import LoggingConfig
@pytest.fixture
def params():
| 64 | 64 | 63 | 6 | 57 | scott-taubman/brewtils | test/log_test.py | Python | params | params | 24 | 33 | 24 | 25 | 3be4742e0c3113c16960e8d498ce06a0287f8eed | bigcode/the-stack | train |
ffddb3bb0399c266d63f07e2 | train | class | class TestDeprecated(object):
def test_get_logging_config(self, params, monkeypatch):
monkeypatch.setattr("brewtils.get_easy_client", Mock())
convert_mock = Mock(return_value="config")
monkeypatch.setattr("brewtils.log.convert_logging_config", convert_mock)
with warnings.catch_warn... | class TestDeprecated(object):
| def test_get_logging_config(self, params, monkeypatch):
monkeypatch.setattr("brewtils.get_easy_client", Mock())
convert_mock = Mock(return_value="config")
monkeypatch.setattr("brewtils.log.convert_logging_config", convert_mock)
with warnings.catch_warnings(record=True) as w:
... | return ["Line {0}\n".format(i) for i in range(10)]
@pytest.fixture
def log_file(self, tmpdir, lines):
log_file = os.path.join(str(tmpdir), "test.log")
with open(log_file, "w") as f:
f.writelines(lines)
return log_file
def test_read_all(self, log_file, lines):
... | 207 | 207 | 692 | 5 | 202 | scott-taubman/brewtils | test/log_test.py | Python | TestDeprecated | TestDeprecated | 117 | 205 | 117 | 117 | c044e232f7c9d671dfb4cc393678388ce5f8eecd | bigcode/the-stack | train |
b463e349758793d669a68b05 | train | class | class TestReadLogFile(object):
@pytest.fixture
def lines(self):
return ["Line {0}\n".format(i) for i in range(10)]
@pytest.fixture
def log_file(self, tmpdir, lines):
log_file = os.path.join(str(tmpdir), "test.log")
with open(log_file, "w") as f:
f.writelines(lines)
... | class TestReadLogFile(object):
@pytest.fixture
| def lines(self):
return ["Line {0}\n".format(i) for i in range(10)]
@pytest.fixture
def log_file(self, tmpdir, lines):
log_file = os.path.join(str(tmpdir), "test.log")
with open(log_file, "w") as f:
f.writelines(lines)
return log_file
def test_read_all(sel... | doesn't have a baseFilename attribute
handler_mock = MagicMock(spec="")
root_mock = Mock(handlers=[handler_mock])
monkeypatch.setattr(logging, "getLogger", Mock(return_value=root_mock))
assert find_log_file() is None
class TestReadLogFile(object):
@pytest.fixture
| 65 | 65 | 219 | 12 | 52 | scott-taubman/brewtils | test/log_test.py | Python | TestReadLogFile | TestReadLogFile | 87 | 114 | 87 | 88 | 5a32b8bb4918adb1e62e0f4bb60cae63c535661c | bigcode/the-stack | train |
c2ac68aa1f8cf62858428ce9 | train | class | class TestFindLogFile(object):
def test_success(self, monkeypatch):
handler_mock = Mock(baseFilename="foo.log")
root_mock = Mock(handlers=[handler_mock])
monkeypatch.setattr(logging, "getLogger", Mock(return_value=root_mock))
assert find_log_file() == "foo.log"
def test_failure... | class TestFindLogFile(object):
| def test_success(self, monkeypatch):
handler_mock = Mock(baseFilename="foo.log")
root_mock = Mock(handlers=[handler_mock])
monkeypatch.setattr(logging, "getLogger", Mock(return_value=root_mock))
assert find_log_file() == "foo.log"
def test_failure(self, monkeypatch):
# ... | ",
)
assert os.path.exists(os.path.join(str(tmpdir), "log"))
assert config_mock.called is True
mangled_config = config_mock.call_args[0][0]
assert "foo" in mangled_config["handlers"]["file"]["filename"]
class TestFindLogFile(object):
| 63 | 64 | 134 | 7 | 56 | scott-taubman/brewtils | test/log_test.py | Python | TestFindLogFile | TestFindLogFile | 69 | 84 | 69 | 69 | f2effa0d74770845dc3488dffd1dd70a2c5aff6e | bigcode/the-stack | train |
e55203a5b224b6c9d5d31efc | train | class | @DATASETS.register()
class FrameRecDataset(BaseDataset):
"""Rawframe dataset for action recognition.
The dataset loads raw frames from frame files, and apply specified transform operatation them.
The indecx file is a text file with multiple lines, and each line indicates the directory of frames of a video, ... | @DATASETS.register()
class FrameRecDataset(BaseDataset):
| """Rawframe dataset for action recognition.
The dataset loads raw frames from frame files, and apply specified transform operatation them.
The indecx file is a text file with multiple lines, and each line indicates the directory of frames of a video, toatl frames of the video, and its label, which split wit... | """
# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# 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
#
# Unless required by app... | 199 | 209 | 697 | 12 | 187 | txyugood/PaddleTableTennis | applications/VideoQualityAssessment/paddlevideo/loader/dataset/frame_rec.py | Python | FrameRecDataset | FrameRecDataset | 28 | 110 | 28 | 29 | 7759a5088ea634ad9a3b599aa1b74e39bc42d3ec | bigcode/the-stack | train |
7f92db7d553f3e0f8be0377d | train | class | class BPBitBang(BPBase):
"""Represents a BitBang interface for the Bus Pirate"""
def __init__(self, conn: BPConnection):
"""Class constructor"""
super(BPBitBang, self).__init__(conn)
# Property Definitions
self.__log = Logger.getlogger()
"""Class Logger"""
... | class BPBitBang(BPBase):
| """Represents a BitBang interface for the Bus Pirate"""
def __init__(self, conn: BPConnection):
"""Class constructor"""
super(BPBitBang, self).__init__(conn)
# Property Definitions
self.__log = Logger.getlogger()
"""Class Logger"""
self.RequiredMode = [... | #!/usr/bin/python3
from enum import Enum
from .BPBase import BPBase
from BusPiratePy.util.Logger import Logger
from BusPiratePy.BPConnection import BPConnection, BPMode
class BPBitBang(BPBase):
| 52 | 64 | 129 | 8 | 43 | ASoftTech/Py.BusPiratePy3 | Source/BusPiratePy/interface/BPBitBang.py | Python | BPBitBang | BPBitBang | 8 | 24 | 8 | 9 | 045bfc028cd088a8ae02d99da2a5fc6876689ed0 | bigcode/the-stack | train |
200fd5665a2bdd3b05ede2e1 | train | function | def postprocess_translations(reduce_diff_hacks=False):
print('Checking and postprocessing...')
if reduce_diff_hacks:
global _orig_escape_cdata
_orig_escape_cdata = ET._escape_cdata
ET._escape_cdata = escape_cdata
for (filename,filepath) in all_ts_files():
os.rename(filepath... | def postprocess_translations(reduce_diff_hacks=False):
| print('Checking and postprocessing...')
if reduce_diff_hacks:
global _orig_escape_cdata
_orig_escape_cdata = ET._escape_cdata
ET._escape_cdata = escape_cdata
for (filename,filepath) in all_ts_files():
os.rename(filepath, filepath+'.orig')
have_errors = False
for (f... | ) or filename == SOURCE_LANG+suffix:
continue
if suffix: # remove provided suffix
filename = filename[0:-len(suffix)]
filepath = os.path.join(LOCALE_DIR, filename)
yield(filename, filepath)
FIX_RE = re.compile(b'[\x00-\x09\x0b\x0c\x0e-\x1f]')
def remove_invalid_character... | 194 | 194 | 647 | 12 | 181 | lycion/TripOne | contrib/devtools/update-translations.py | Python | postprocess_translations | postprocess_translations | 118 | 194 | 118 | 118 | 15bee6a32bf7dbeb48912f0b8d5ec9553a40f7bb | bigcode/the-stack | train |
2100c2df7ba913ccd4161bb6 | train | function | def all_ts_files(suffix=''):
for filename in os.listdir(LOCALE_DIR):
# process only language files, and do not process source language
if not filename.endswith('.ts'+suffix) or filename == SOURCE_LANG+suffix:
continue
if suffix: # remove provided suffix
filename = fil... | def all_ts_files(suffix=''):
| for filename in os.listdir(LOCALE_DIR):
# process only language files, and do not process source language
if not filename.endswith('.ts'+suffix) or filename == SOURCE_LANG+suffix:
continue
if suffix: # remove provided suffix
filename = filename[0:-len(suffix)]
... | Allow numerus translations to omit %n specifier (usually when it only has one possible value)
return True
errors.append("Mismatch between '%s' and '%s'" % (sanitize_string(source), sanitize_string(translation)))
return False
return True
def all_ts_files(suffix=''):
| 64 | 64 | 93 | 8 | 55 | lycion/TripOne | contrib/devtools/update-translations.py | Python | all_ts_files | all_ts_files | 94 | 102 | 94 | 94 | f25ec7bd152fdbcac881f6aff16d3b5858a2e0ee | bigcode/the-stack | train |
76ff28874c7d87b7ddbe88be | train | function | def find_format_specifiers(s):
'''Find all format specifiers in a string.'''
pos = 0
specifiers = []
while True:
percent = s.find('%', pos)
if percent < 0:
break
specifiers.append(s[percent+1])
pos = percent+2
return specifiers
| def find_format_specifiers(s):
| '''Find all format specifiers in a string.'''
pos = 0
specifiers = []
while True:
percent = s.find('%', pos)
if percent < 0:
break
specifiers.append(s[percent+1])
pos = percent+2
return specifiers
| this script at the root of the repository', file=sys.stderr)
exit(1)
def fetch_all_translations():
if subprocess.call([TX, 'pull', '-f', '-a']):
print('Error while fetching translations', file=sys.stderr)
exit(1)
def find_format_specifiers(s):
| 64 | 64 | 75 | 7 | 57 | lycion/TripOne | contrib/devtools/update-translations.py | Python | find_format_specifiers | find_format_specifiers | 46 | 56 | 46 | 46 | 00f979633ace57cdda001b9da45ea3a8bd778038 | bigcode/the-stack | train |
a594fd5aaba046438b4c4c21 | train | function | def remove_invalid_characters(s):
'''Remove invalid characters from translation string'''
return FIX_RE.sub(b'', s)
| def remove_invalid_characters(s):
| '''Remove invalid characters from translation string'''
return FIX_RE.sub(b'', s)
| filename = filename[0:-len(suffix)]
filepath = os.path.join(LOCALE_DIR, filename)
yield(filename, filepath)
FIX_RE = re.compile(b'[\x00-\x09\x0b\x0c\x0e-\x1f]')
def remove_invalid_characters(s):
| 64 | 64 | 25 | 7 | 58 | lycion/TripOne | contrib/devtools/update-translations.py | Python | remove_invalid_characters | remove_invalid_characters | 105 | 107 | 105 | 105 | f01df57c7e739d19b8f8316a2a6f3ece5e1fe7c1 | bigcode/the-stack | train |
5249fe97ce1dc53198537f78 | train | function | def split_format_specifiers(specifiers):
'''Split format specifiers between numeric (Qt) and others (strprintf)'''
numeric = []
other = []
for s in specifiers:
if s in {'1','2','3','4','5','6','7','8','9'}:
numeric.append(s)
else:
other.append(s)
# numeric (Q... | def split_format_specifiers(specifiers):
| '''Split format specifiers between numeric (Qt) and others (strprintf)'''
numeric = []
other = []
for s in specifiers:
if s in {'1','2','3','4','5','6','7','8','9'}:
numeric.append(s)
else:
other.append(s)
# numeric (Qt) can be present in any order, others (s... | pos = 0
specifiers = []
while True:
percent = s.find('%', pos)
if percent < 0:
break
specifiers.append(s[percent+1])
pos = percent+2
return specifiers
def split_format_specifiers(specifiers):
| 64 | 64 | 110 | 8 | 55 | lycion/TripOne | contrib/devtools/update-translations.py | Python | split_format_specifiers | split_format_specifiers | 58 | 69 | 58 | 58 | a623f04fb6a09cc9a2984ccd82df5aa2ff458231 | bigcode/the-stack | train |
2cfea0f35d2dd5636bf99439 | train | function | def fetch_all_translations():
if subprocess.call([TX, 'pull', '-f', '-a']):
print('Error while fetching translations', file=sys.stderr)
exit(1)
| def fetch_all_translations():
| if subprocess.call([TX, 'pull', '-f', '-a']):
print('Error while fetching translations', file=sys.stderr)
exit(1)
| be considered at all
MIN_NUM_MESSAGES = 10
def check_at_repository_root():
if not os.path.exists('.git'):
print('No .git directory found')
print('Execute this script at the root of the repository', file=sys.stderr)
exit(1)
def fetch_all_translations():
| 64 | 64 | 39 | 6 | 58 | lycion/TripOne | contrib/devtools/update-translations.py | Python | fetch_all_translations | fetch_all_translations | 41 | 44 | 41 | 41 | 5a79d6e3fb86627130a006212ed7d7e829148656 | bigcode/the-stack | train |
192dcadbf1dce63d595fd463 | train | function | def check_format_specifiers(source, translation, errors, numerus):
source_f = split_format_specifiers(find_format_specifiers(source))
# assert that no source messages contain both Qt and strprintf format specifiers
# if this fails, go change the source as this is hacky and confusing!
assert(not(source_f... | def check_format_specifiers(source, translation, errors, numerus):
| source_f = split_format_specifiers(find_format_specifiers(source))
# assert that no source messages contain both Qt and strprintf format specifiers
# if this fails, go change the source as this is hacky and confusing!
assert(not(source_f[0] and source_f[1]))
try:
translation_f = split_format... | )
# numeric (Qt) can be present in any order, others (strprintf) must be in specified order
return set(numeric),other
def sanitize_string(s):
'''Sanitize string for printing'''
return s.replace('\n',' ')
def check_format_specifiers(source, translation, errors, numerus):
| 68 | 69 | 230 | 14 | 54 | lycion/TripOne | contrib/devtools/update-translations.py | Python | check_format_specifiers | check_format_specifiers | 75 | 92 | 75 | 75 | 0279122a5f1f1c3ac141693e4d6ef894869e697f | bigcode/the-stack | train |
1c677c7b716dd978e6038f89 | train | function | def sanitize_string(s):
'''Sanitize string for printing'''
return s.replace('\n',' ')
| def sanitize_string(s):
| '''Sanitize string for printing'''
return s.replace('\n',' ')
| ','4','5','6','7','8','9'}:
numeric.append(s)
else:
other.append(s)
# numeric (Qt) can be present in any order, others (strprintf) must be in specified order
return set(numeric),other
def sanitize_string(s):
| 64 | 64 | 21 | 5 | 58 | lycion/TripOne | contrib/devtools/update-translations.py | Python | sanitize_string | sanitize_string | 71 | 73 | 71 | 71 | 3bf41e4a161e3999fd7cc587b8f72f523ec406e8 | bigcode/the-stack | train |
4883a5f3d6096a55ac43f25b | train | function | def check_at_repository_root():
if not os.path.exists('.git'):
print('No .git directory found')
print('Execute this script at the root of the repository', file=sys.stderr)
exit(1)
| def check_at_repository_root():
| if not os.path.exists('.git'):
print('No .git directory found')
print('Execute this script at the root of the repository', file=sys.stderr)
exit(1)
| TX = 'tx'
# Name of source language file
SOURCE_LANG = 'tripone_en.ts'
# Directory with locale files
LOCALE_DIR = 'src/qt/locale'
# Minimum number of messages for translation to be considered at all
MIN_NUM_MESSAGES = 10
def check_at_repository_root():
| 64 | 64 | 46 | 6 | 57 | lycion/TripOne | contrib/devtools/update-translations.py | Python | check_at_repository_root | check_at_repository_root | 35 | 39 | 35 | 35 | e22a674c83912abbe7de2097a642d2c88879b0a3 | bigcode/the-stack | train |
2ede69a6a3166243b8f558dc | train | function | def escape_cdata(text):
text = _orig_escape_cdata(text)
text = text.replace("'", ''')
text = text.replace('"', '"')
return text
| def escape_cdata(text):
| text = _orig_escape_cdata(text)
text = text.replace("'", ''')
text = text.replace('"', '"')
return text
| acters(s):
'''Remove invalid characters from translation string'''
return FIX_RE.sub(b'', s)
# Override cdata escape function to make our output match Qt's (optional, just for cleaner diffs for
# comparison, disable by default)
_orig_escape_cdata = None
def escape_cdata(text):
| 64 | 64 | 42 | 6 | 57 | lycion/TripOne | contrib/devtools/update-translations.py | Python | escape_cdata | escape_cdata | 112 | 116 | 112 | 112 | a0ad083ad5161501d817976805d7156747d0fc02 | bigcode/the-stack | train |
30a15db69fad435f44e14198 | train | class | @jsii.data_type(jsii_type="@aws-cdk/core.CfnRuleProps", jsii_struct_bases=[], name_mapping={'assertions': 'assertions', 'rule_condition': 'ruleCondition'})
class CfnRuleProps():
def __init__(self, *, assertions: typing.Optional[typing.List["CfnRuleAssertion"]]=None, rule_condition: typing.Optional["ICfnConditionExp... | @jsii.data_type(jsii_type="@aws-cdk/core.CfnRuleProps", jsii_struct_bases=[], name_mapping={'assertions': 'assertions', 'rule_condition': 'ruleCondition'})
class CfnRuleProps():
| def __init__(self, *, assertions: typing.Optional[typing.List["CfnRuleAssertion"]]=None, rule_condition: typing.Optional["ICfnConditionExpression"]=None):
"""A rule can include a RuleCondition property and must include an Assertions property. For each rule, you can define only one rule condition; you can de... | self._values.get('assert_')
@property
def assert_description(self) -> str:
"""The assertion description."""
return self._values.get('assert_description')
def __eq__(self, rhs) -> bool:
return isinstance(rhs, self.__class__) and rhs._values == self._values
def __ne__(self, rhs... | 175 | 175 | 586 | 47 | 128 | chriscoombs/amazon-sagemaker-cdk-examples | dask-fargate/.env/lib/python3.6/site-packages/aws_cdk/core/__init__.py | Python | CfnRuleProps | CfnRuleProps | 1,479 | 1,533 | 1,479 | 1,480 | e325ec7b451903adffbe540fdfe3448b41fd7faf | bigcode/the-stack | train |
35f98c556938e60295438ecc | train | class | @jsii.interface(jsii_type="@aws-cdk/core.ICfnResourceOptions")
class ICfnResourceOptions(jsii.compat.Protocol):
@staticmethod
def __jsii_proxy_class__():
return _ICfnResourceOptionsProxy
@property
@jsii.member(jsii_name="condition")
def condition(self) -> typing.Optional["CfnCondition"]:
... | @jsii.interface(jsii_type="@aws-cdk/core.ICfnResourceOptions")
class ICfnResourceOptions(jsii.compat.Protocol):
@staticmethod
| def __jsii_proxy_class__():
return _ICfnResourceOptionsProxy
@property
@jsii.member(jsii_name="condition")
def condition(self) -> typing.Optional["CfnCondition"]:
"""A condition to associate with this resource.
This means that only if the condition evaluates to 'true' when the ... | value.
:param context: -
"""
return jsii.invoke(self, "produce", [context])
@jsii.interface(jsii_type="@aws-cdk/core.IAspect")
class IAspect(jsii.compat.Protocol):
"""Represents an Aspect."""
@staticmethod
def __jsii_proxy_class__():
return _IAspectProxy
@jsii.member... | 227 | 227 | 759 | 30 | 197 | chriscoombs/amazon-sagemaker-cdk-examples | dask-fargate/.env/lib/python3.6/site-packages/aws_cdk/core/__init__.py | Python | ICfnResourceOptions | ICfnResourceOptions | 3,092 | 3,174 | 3,092 | 3,094 | 23e3cefaedb5c463663eec8550473d3110f23781 | bigcode/the-stack | train |
54a4f2117e16ad21370f7d1c | train | class | @jsii.enum(jsii_type="@aws-cdk/core.ConstructOrder")
class ConstructOrder(enum.Enum):
"""In what order to return constructs."""
PREORDER = "PREORDER"
"""Depth-first, pre-order."""
POSTORDER = "POSTORDER"
"""Depth-first, post-order (leaf nodes first)."""
| @jsii.enum(jsii_type="@aws-cdk/core.ConstructOrder")
class ConstructOrder(enum.Enum):
| """In what order to return constructs."""
PREORDER = "PREORDER"
"""Depth-first, pre-order."""
POSTORDER = "POSTORDER"
"""Depth-first, post-order (leaf nodes first)."""
| jsii.get(self, "defaultChild")
@default_child.setter
def default_child(self, value: typing.Optional["IConstruct"]):
return jsii.set(self, "defaultChild", value)
@jsii.enum(jsii_type="@aws-cdk/core.ConstructOrder")
class ConstructOrder(enum.Enum):
| 64 | 64 | 67 | 21 | 43 | chriscoombs/amazon-sagemaker-cdk-examples | dask-fargate/.env/lib/python3.6/site-packages/aws_cdk/core/__init__.py | Python | ConstructOrder | ConstructOrder | 1,910 | 1,916 | 1,910 | 1,911 | c3a6c3d3cf9a8c13a75f0c4c7f470c4431996afe | bigcode/the-stack | train |
4edc02c07a7b1f2af1d536b2 | train | class | class _IConstructProxy(jsii.proxy_for(IDependable)):
"""Represents a construct."""
__jsii_type__ = "@aws-cdk/core.IConstruct"
@property
@jsii.member(jsii_name="node")
def node(self) -> "ConstructNode":
"""The construct node in the tree."""
return jsii.get(self, "node")
| class _IConstructProxy(jsii.proxy_for(IDependable)):
| """Represents a construct."""
__jsii_type__ = "@aws-cdk/core.IConstruct"
@property
@jsii.member(jsii_name="node")
def node(self) -> "ConstructNode":
"""The construct node in the tree."""
return jsii.get(self, "node")
|
def __jsii_proxy_class__():
return _IConstructProxy
@property
@jsii.member(jsii_name="node")
def node(self) -> "ConstructNode":
"""The construct node in the tree."""
...
class _IConstructProxy(jsii.proxy_for(IDependable)):
| 64 | 64 | 77 | 13 | 51 | chriscoombs/amazon-sagemaker-cdk-examples | dask-fargate/.env/lib/python3.6/site-packages/aws_cdk/core/__init__.py | Python | _IConstructProxy | _IConstructProxy | 3,333 | 3,340 | 3,333 | 3,333 | 4fc878e6eb95f3b9bc03b28a3c5a7275cc8c425b | bigcode/the-stack | train |
4d02fb7fda95dfced793712e | train | class | @jsii.data_type(jsii_type="@aws-cdk/core.AppProps", jsii_struct_bases=[], name_mapping={'auto_synth': 'autoSynth', 'context': 'context', 'outdir': 'outdir', 'runtime_info': 'runtimeInfo', 'stack_traces': 'stackTraces', 'tree_metadata': 'treeMetadata'})
class AppProps():
def __init__(self, *, auto_synth: typing.Opti... | @jsii.data_type(jsii_type="@aws-cdk/core.AppProps", jsii_struct_bases=[], name_mapping={'auto_synth': 'autoSynth', 'context': 'context', 'outdir': 'outdir', 'runtime_info': 'runtimeInfo', 'stack_traces': 'stackTraces', 'tree_metadata': 'treeMetadata'})
class AppProps():
| def __init__(self, *, auto_synth: typing.Optional[bool]=None, context: typing.Optional[typing.Mapping[str,str]]=None, outdir: typing.Optional[str]=None, runtime_info: typing.Optional[bool]=None, stack_traces: typing.Optional[bool]=None, tree_metadata: typing.Optional[bool]=None):
"""Initialization props for... | the synthesized template.
This can be achieved using the `CfnInclude` class.
```python
# Example automatically generated. See https://github.com/aws/jsii/issues/826
CfnInclude(self, "ID",
template={
"Resources": {
"Bucket": {
"Type": "AWS::S3::Bucket",
"Properti... | 256 | 256 | 1,168 | 76 | 180 | chriscoombs/amazon-sagemaker-cdk-examples | dask-fargate/.env/lib/python3.6/site-packages/aws_cdk/core/__init__.py | Python | AppProps | AppProps | 414 | 510 | 414 | 415 | a9b52e419bf9fa07cf4bd82ec161af0a26e136a6 | bigcode/the-stack | train |
39bfb9efff3e81cdb8d6451c | train | class | @jsii.enum(jsii_type="@aws-cdk/core.CfnDynamicReferenceService")
class CfnDynamicReferenceService(enum.Enum):
"""The service to retrieve the dynamic reference from."""
SSM = "SSM"
"""Plaintext value stored in AWS Systems Manager Parameter Store."""
SSM_SECURE = "SSM_SECURE"
"""Secure string stored i... | @jsii.enum(jsii_type="@aws-cdk/core.CfnDynamicReferenceService")
class CfnDynamicReferenceService(enum.Enum):
| """The service to retrieve the dynamic reference from."""
SSM = "SSM"
"""Plaintext value stored in AWS Systems Manager Parameter Store."""
SSM_SECURE = "SSM_SECURE"
"""Secure string stored in AWS Systems Manager Parameter Store."""
SECRETS_MANAGER = "SECRETS_MANAGER"
"""Secret stored in AWS ... | __(self) -> str:
return 'CfnDynamicReferenceProps(%s)' % ', '.join(k + '=' + repr(v) for k, v in self._values.items())
@jsii.enum(jsii_type="@aws-cdk/core.CfnDynamicReferenceService")
class CfnDynamicReferenceService(enum.Enum):
| 64 | 64 | 103 | 26 | 38 | chriscoombs/amazon-sagemaker-cdk-examples | dask-fargate/.env/lib/python3.6/site-packages/aws_cdk/core/__init__.py | Python | CfnDynamicReferenceService | CfnDynamicReferenceService | 1,072 | 1,080 | 1,072 | 1,073 | 5dac9672962b2ddda0eaf1c1e5a1d1d2aed7c9b7 | bigcode/the-stack | train |
562aae16c63bff2eb2d46d0a | train | class | @jsii.interface(jsii_type="@aws-cdk/core.IListProducer")
class IListProducer(jsii.compat.Protocol):
"""Interface for lazy list producers."""
@staticmethod
def __jsii_proxy_class__():
return _IListProducerProxy
@jsii.member(jsii_name="produce")
def produce(self, context: "IResolveContext") -... | @jsii.interface(jsii_type="@aws-cdk/core.IListProducer")
class IListProducer(jsii.compat.Protocol):
| """Interface for lazy list producers."""
@staticmethod
def __jsii_proxy_class__():
return _IListProducerProxy
@jsii.member(jsii_name="produce")
def produce(self, context: "IResolveContext") -> typing.Optional[typing.List[str]]:
"""Produce the list value.
:param context: -
... | Inspector") -> None:
"""Examines construct.
:param inspector: - tree inspector to collect and process attributes.
"""
return jsii.invoke(self, "inspect", [inspector])
@jsii.interface(jsii_type="@aws-cdk/core.IListProducer")
class IListProducer(jsii.compat.Protocol):
| 64 | 64 | 98 | 23 | 41 | chriscoombs/amazon-sagemaker-cdk-examples | dask-fargate/.env/lib/python3.6/site-packages/aws_cdk/core/__init__.py | Python | IListProducer | IListProducer | 4,025 | 4,038 | 4,025 | 4,026 | 70670eb389d0e36e385a5638b3392c588d2cc34d | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.