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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
597946370df61a7fc97ff2f8 | train | class | class testmode(object): # pylint: disable=too-few-public-methods
"""Decorator to check testmode & route to command decorator"""
def __init__(self, *aliases):
self.aliases = aliases
def __call__(self, func):
"""Testmode call method"""
if not state.testmode:
return None... | class testmode(object): # pylint: disable=too-few-public-methods
| """Decorator to check testmode & route to command decorator"""
def __init__(self, *aliases):
self.aliases = aliases
def __call__(self, func):
"""Testmode call method"""
if not state.testmode:
return None
return command(self.aliases[0]).__call__(func)
| = alias.split(':')
if apivariant != prefix:
continue
except ValueError:
pass
result._handlers[alias] = func
except AttributeError:
pass
return result
class testmode(ob... | 64 | 64 | 89 | 18 | 45 | vishalbelsare/PyBitmessage | src/api.py | Python | testmode | testmode | 307 | 318 | 307 | 307 | 8e5bd9f72c70a5a27d9b25b779ba7b13d203aea7 | bigcode/the-stack | train |
4589a522e0fb3368568fb76a | train | class | class BMXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
"""The main API handler"""
# pylint: disable=protected-access
def do_POST(self):
"""
Handles the HTTP POST request.
Attempts to interpret all HTTP POST requests as XML-RPC calls,
which are forwarded to the server's _... | class BMXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
| """The main API handler"""
# pylint: disable=protected-access
def do_POST(self):
"""
Handles the HTTP POST request.
Attempts to interpret all HTTP POST requests as XML-RPC calls,
which are forwarded to the server's _dispatch method for handling.
.. note:: this meth... | self, func):
if BMConfigParser().safeGet(
'bitmessagesettings', 'apivariant') == 'legacy':
def wrapper(*args):
"""
A wrapper for legacy apivariant which dumps the result
into string of json
"""
result = ... | 226 | 226 | 755 | 12 | 213 | vishalbelsare/PyBitmessage | src/api.py | Python | BMXMLRPCRequestHandler | BMXMLRPCRequestHandler | 354 | 457 | 354 | 354 | 28c7ea073a42595402dea738c949c491af005556 | bigcode/the-stack | train |
6d692ddbf3dd4137e6a8ffad | train | function | def get_matlab_matrices(function_name):
"""Loads the matrices generated by MATLAB for unit tests
Parameters
----------
function_name: str
Function name, e.g. NMFD
Returns
-------
matrix_dict: dict
MATLAB matrix in dict format
"""
base_dir = os.path.join(PATH_TO_MATR... | def get_matlab_matrices(function_name):
| """Loads the matrices generated by MATLAB for unit tests
Parameters
----------
function_name: str
Function name, e.g. NMFD
Returns
-------
matrix_dict: dict
MATLAB matrix in dict format
"""
base_dir = os.path.join(PATH_TO_MATRICES, function_name)
filename_list =... | =1)
else:
arr_python = res_python
np.testing.assert_almost_equal(arr_python, mat_matlab, decimal=decimal_precision, err_msg='', verbose=True)
print('Test successfully passed. Precision: {} significant digits'.format(decimal_precision))
def get_matlab_matrices(function_name):
| 64 | 64 | 149 | 9 | 55 | avinashpujala/av_segmentation | nmfTools/utils.py | Python | get_matlab_matrices | get_matlab_matrices | 172 | 196 | 172 | 172 | 86ee6e7d4cccc9fa473abbb67d29d607fea74bc6 | bigcode/the-stack | train |
2c28fc941c8addeaf709e002 | train | function | def conv2(x, y, mode='same'):
"""Emulate the function conv2 from Mathworks.
Usage:
z = conv2(x,y,mode='same')
"""
# We must provide an offset for each non-singleton dimension to reproduce the results of Matlab's conv2.
# A simple implementation supporting the 'same' option, only, could be mad... | def conv2(x, y, mode='same'):
| """Emulate the function conv2 from Mathworks.
Usage:
z = conv2(x,y,mode='same')
"""
# We must provide an offset for each non-singleton dimension to reproduce the results of Matlab's conv2.
# A simple implementation supporting the 'same' option, only, could be made like below
# source: htt... | 16 to float32
Parameters
----------
audio: array-like
Numpy array in int16 type
Returns
-------
res: array-like
Numpy array in float32 type
"""
res = np.array(audio, dtype=np.float32) / MAX_WAV_VALUE
res[res > 1] = 1
res[res < -1] = -1
return res
def conv2... | 104 | 104 | 349 | 11 | 92 | avinashpujala/av_segmentation | nmfTools/utils.py | Python | conv2 | conv2 | 102 | 144 | 102 | 102 | 1ab6cee77e56fa95a30f048257fe8936a9bb530a | bigcode/the-stack | train |
78a40098047afa79ea64963d | train | function | def pcmInt16ToFloat32Numpy(audio):
"""Converts the data type of the input from int16 to float32
Parameters
----------
audio: array-like
Numpy array in int16 type
Returns
-------
res: array-like
Numpy array in float32 type
"""
res = np.array(audio, dtype=np.float32)... | def pcmInt16ToFloat32Numpy(audio):
| """Converts the data type of the input from int16 to float32
Parameters
----------
audio: array-like
Numpy array in int16 type
Returns
-------
res: array-like
Numpy array in float32 type
"""
res = np.array(audio, dtype=np.float32) / MAX_WAV_VALUE
res[res > 1] =... | field: str
Name of the MATLAB matrix, which is the key of the dictionary
Returns
-------
mat[field]: array-like
MATLAB matrix in python
"""
mat = scipy.io.loadmat(filepath)
return mat[field]
def pcmInt16ToFloat32Numpy(audio):
| 64 | 64 | 116 | 11 | 53 | avinashpujala/av_segmentation | nmfTools/utils.py | Python | pcmInt16ToFloat32Numpy | pcmInt16ToFloat32Numpy | 81 | 99 | 81 | 81 | 2b2416114cb4bb5da5465806df9e1f12bcf1224b | bigcode/the-stack | train |
d2a3a4a5964fdc7334202b64 | train | function | def load_matlab_dict(filepath, field):
"""Loads .mat file from the directory
Parameters
----------
filepath: str
Path to the .mat file
field: str
Name of the MATLAB matrix, which is the key of the dictionary
Returns
-------
mat[field]: array-like
MATLAB matrix ... | def load_matlab_dict(filepath, field):
| """Loads .mat file from the directory
Parameters
----------
filepath: str
Path to the .mat file
field: str
Name of the MATLAB matrix, which is the key of the dictionary
Returns
-------
mat[field]: array-like
MATLAB matrix in python
"""
mat = scipy.io.lo... | array-like
Audio input in numpy format
Returns
-------
audio: array-like
Monochannel audio
"""
audio = np.mean(audio, axis=1) if len(audio.shape) == 2 else audio
return audio
def load_matlab_dict(filepath, field):
| 64 | 64 | 91 | 9 | 54 | avinashpujala/av_segmentation | nmfTools/utils.py | Python | load_matlab_dict | load_matlab_dict | 61 | 78 | 61 | 61 | 7e32d32e5c30746f3479472a6d599cb3a7b05e13 | bigcode/the-stack | train |
d674236f315e46bb8df71962 | train | function | def run_unit_test(res_python, mat_matlab, decimal_precision=5):
"""Runs the unit test for one of the functions in unit_tests folder
Parameters
----------
res_python: array-like
Python result
mat_matlab: array-like
MATLAB matrix
decimal_precision: int
Desired precision,... | def run_unit_test(res_python, mat_matlab, decimal_precision=5):
| """Runs the unit test for one of the functions in unit_tests folder
Parameters
----------
res_python: array-like
Python result
mat_matlab: array-like
MATLAB matrix
decimal_precision: int
Desired precision, default is 5.
"""
# If res_python is a list, convert it... | .shape[i] > 1):
origin = origin + (-1,)
else:
origin = origin + (0,)
z = convolve(x, y, mode='constant', origin=origin)
return z
def run_unit_test(res_python, mat_matlab, decimal_precision=5):
| 64 | 64 | 166 | 16 | 47 | avinashpujala/av_segmentation | nmfTools/utils.py | Python | run_unit_test | run_unit_test | 147 | 169 | 147 | 147 | 75b502835b2d71d7db7bcff5d7fa7099eea959e6 | bigcode/the-stack | train |
9d39356d4fda53da097092d8 | train | function | def make_monaural(audio):
"""Converts multichannel audio to mono-channel output
Parameters
----------
audio: array-like
Audio input in numpy format
Returns
-------
audio: array-like
Monochannel audio
"""
audio = np.mean(audio, axis=1) if len(audio.shape) == 2 else ... | def make_monaural(audio):
| """Converts multichannel audio to mono-channel output
Parameters
----------
audio: array-like
Audio input in numpy format
Returns
-------
audio: array-like
Monochannel audio
"""
audio = np.mean(audio, axis=1) if len(audio.shape) == 2 else audio
return audio
| /.
"""
import numpy as np
from scipy.ndimage.filters import convolve
import scipy.io
import os
EPS = 2.0 ** -52
MAX_WAV_VALUE = 2.0 ** 15
PATH_TO_MATRICES = 'matrices/'
def make_monaural(audio):
| 63 | 64 | 82 | 7 | 56 | avinashpujala/av_segmentation | nmfTools/utils.py | Python | make_monaural | make_monaural | 42 | 58 | 42 | 42 | b19be8a9d2457b7ac54a48399d0bb4f19d3765a1 | bigcode/the-stack | train |
6d5193c4febe773434671c6f | train | function | def run_matlab_script(function_name, path_to_matlab_bin):
"""Runs the corresponding MATLAB script for unit testing
Parameters
----------
function_name: str
Function name, e.g. NMFD
path_to_matlab_bin: str
Path to the binary file of MATLAB
"""
os.system('cat test_{}.m | {} -... | def run_matlab_script(function_name, path_to_matlab_bin):
| """Runs the corresponding MATLAB script for unit testing
Parameters
----------
function_name: str
Function name, e.g. NMFD
path_to_matlab_bin: str
Path to the binary file of MATLAB
"""
os.system('cat test_{}.m | {} - nodesktop - nosplash'.format(function_name, path_to_matla... | :
filepath = os.path.join(base_dir, filename)
matrix_id = filename.split('.')[0]
matlab_matrix = load_matlab_dict(filepath, matrix_id)
matrix_dict[matrix_id] = matlab_matrix
return matrix_dict
def run_matlab_script(function_name, path_to_matlab_bin):
| 64 | 64 | 94 | 14 | 49 | avinashpujala/av_segmentation | nmfTools/utils.py | Python | run_matlab_script | run_matlab_script | 199 | 210 | 199 | 199 | 3577351956c07794c100d594ddf590f6883c08f6 | bigcode/the-stack | train |
8ca53b43c7367ad27548a324 | train | function | def afineZoom(img, a=1., b=0., c=0., d=1., tx=0., ty=0.):
H, W, C = img.shape
aH = int(a * H)
dW = int(d * W)
y = np.arange(aH).repeat(dW).reshape(dW, -1)
x = np.tile(np.arange(dW), (aH, 1))
| def afineZoom(img, a=1., b=0., c=0., d=1., tx=0., ty=0.):
| H, W, C = img.shape
aH = int(a * H)
dW = int(d * W)
y = np.arange(aH).repeat(dW).reshape(dW, -1)
x = np.tile(np.arange(dW), (aH, 1))
| @File : q29.py
# @Description : 仿射变换之放大缩小
import cv2 as cv
import numpy as np
def afineZoom(img, a=1., b=0., c=0., d=1., tx=0., ty=0.):
| 64 | 64 | 95 | 31 | 32 | wuwuwuyuanhang/python | opencv/q29.py | Python | afineZoom | afineZoom | 9 | 17 | 9 | 10 | 19d3417e9d2b3fdc93b8a9db81bdab5fa3d89353 | bigcode/the-stack | train |
b503d5f2dddbd3a363b54ffc | train | class | class KMeans:
"""
This class implements KMeans.
Args:
k(int): Amount of classes.
random_seed(int): Optional. Random seed for initialization.
Attributes:
KMeans.k(int): Amount of classes.
KMeans.random_seed: Optional. Random seed for initialization.
KM... | class KMeans:
| """
This class implements KMeans.
Args:
k(int): Amount of classes.
random_seed(int): Optional. Random seed for initialization.
Attributes:
KMeans.k(int): Amount of classes.
KMeans.random_seed: Optional. Random seed for initialization.
KMeans.means: Cen... | import numpy as np
class KMeans:
| 9 | 256 | 948 | 4 | 4 | hejj16/Machine-Learning-Algorithms | KMeans.py | Python | KMeans | KMeans | 4 | 130 | 4 | 4 | ea1b0b325461479cb891e89689029dbb20e2584d | bigcode/the-stack | train |
3910948036fe2dbb4af8e18f | train | class | class TestPlugins(AllenNlpTestCase):
def setup_method(self):
super().setup_method()
self.plugins_root = self.FIXTURES_ROOT / "plugins"
def test_no_plugins(self):
available_plugins = set(discover_plugins())
assert available_plugins == set()
def test_file_plugin(self):
... | class TestPlugins(AllenNlpTestCase):
| def setup_method(self):
super().setup_method()
self.plugins_root = self.FIXTURES_ROOT / "plugins"
def test_no_plugins(self):
available_plugins = set(discover_plugins())
assert available_plugins == set()
def test_file_plugin(self):
available_plugins = set(discover_pl... | from allennlp.commands import Subcommand
from allennlp.common.plugins import (
discover_plugins,
import_plugins,
)
from allennlp.common.testing import AllenNlpTestCase
from allennlp.common.util import pushd
class TestPlugins(AllenNlpTestCase):
| 59 | 64 | 132 | 10 | 48 | MSLars/allennlp | tests/common/plugins_test.py | Python | TestPlugins | TestPlugins | 10 | 29 | 10 | 10 | 880aa003396f676a24538709876112d826be29f9 | bigcode/the-stack | train |
d5d3bf2ee6d43ab92ef94b5b | train | class | class Solution:
def getRow(self, rowIndex: int) -> List[int]:
ret = [0] * (rowIndex + 1)
for i in range(rowIndex + 1):
# math.comb is only available since Python 3.8
ret[i] = math.comb(rowIndex, i)
return ret
| class Solution:
| def getRow(self, rowIndex: int) -> List[int]:
ret = [0] * (rowIndex + 1)
for i in range(rowIndex + 1):
# math.comb is only available since Python 3.8
ret[i] = math.comb(rowIndex, i)
return ret
| : [1]
# Example 3:
# Input: rowIndex = 1
# Output: [1,1]
# Constraints:
# 0 <= rowIndex <= 33
# Follow up: Could you optimize your algorithm to use only O(rowIndex) extra
# space?
class Solution:
| 64 | 64 | 75 | 3 | 61 | aafulei/leetcode | python/0119-pascals-triangle-ii.py | Python | Solution | Solution | 29 | 35 | 29 | 29 | 474a467d7f3b505ea479cef7f6eb84e8b2c414f9 | bigcode/the-stack | train |
f572aed9b862ee15f3a28f9f | train | class | class Solution:
def getRow(self, rowIndex: int) -> List[int]:
ret = [1] * (rowIndex + 1)
for i in range(1, rowIndex // 2 + 1):
ret[i] = ret[i-1] * (rowIndex - i + 1) // i
for i in range(rowIndex // 2 + 1, rowIndex + 1):
ret[i] = ret[rowIndex - i]
return ret
| class Solution:
| def getRow(self, rowIndex: int) -> List[int]:
ret = [1] * (rowIndex + 1)
for i in range(1, rowIndex // 2 + 1):
ret[i] = ret[i-1] * (rowIndex - i + 1) // i
for i in range(rowIndex // 2 + 1, rowIndex + 1):
ret[i] = ret[rowIndex - i]
return ret
| -> List[int]:
ret = [0] * (rowIndex + 1)
for i in range(rowIndex + 1):
# math.comb is only available since Python 3.8
ret[i] = math.comb(rowIndex, i)
return ret
class Solution:
| 64 | 64 | 107 | 3 | 60 | aafulei/leetcode | python/0119-pascals-triangle-ii.py | Python | Solution | Solution | 38 | 45 | 38 | 38 | 3fb3f13413b5992b1474236de475619b51b799dd | bigcode/the-stack | train |
c2d840015b908104cc0e79bd | train | function | @compiles(_ExecDropConstraint, "mssql")
def _exec_drop_col_constraint(element, compiler, **kw):
tname, colname, type_ = element.tname, element.colname, element.type_
# from http://www.mssqltips.com/sqlservertip/1425/\
# working-with-default-constraints-in-sql-server/
# TODO: needs table formatting, etc.... | @compiles(_ExecDropConstraint, "mssql")
def _exec_drop_col_constraint(element, compiler, **kw):
| tname, colname, type_ = element.tname, element.colname, element.type_
# from http://www.mssqltips.com/sqlservertip/1425/\
# working-with-default-constraints-in-sql-server/
# TODO: needs table formatting, etc.
return """declare @const_name varchar(256)
select @const_name = [name] from %(type)s
where ... | ExecDropFKConstraint(Executable, ClauseElement):
def __init__(self, tname, colname):
self.tname = tname
self.colname = colname
@compiles(_ExecDropConstraint, "mssql")
def _exec_drop_col_constraint(element, compiler, **kw):
| 64 | 64 | 205 | 25 | 38 | kenmutuma001/Blog | virtual/lib/python3.6/site-packages/alembic/ddl/mssql.py | Python | _exec_drop_col_constraint | _exec_drop_col_constraint | 166 | 181 | 166 | 167 | d8fa9f442a3726bf213ff0e7d281dca17ec5dc44 | bigcode/the-stack | train |
28ffa2fe8d1a513ea7bda617 | train | function | @compiles(_ExecDropFKConstraint, "mssql")
def _exec_drop_col_fk_constraint(element, compiler, **kw):
tname, colname = element.tname, element.colname
return """declare @const_name varchar(256)
select @const_name = [name] from
sys.foreign_keys fk join sys.foreign_key_columns fkc
on fk.object_id=fkc.const... | @compiles(_ExecDropFKConstraint, "mssql")
def _exec_drop_col_fk_constraint(element, compiler, **kw):
| tname, colname = element.tname, element.colname
return """declare @const_name varchar(256)
select @const_name = [name] from
sys.foreign_keys fk join sys.foreign_key_columns fkc
on fk.object_id=fkc.constraint_object_id
where fkc.parent_object_id = object_id('%(tname)s')
and col_name(fkc.parent_object_id... | _,
"tname": tname,
"colname": colname,
"tname_quoted": format_table_name(compiler, tname, None),
}
@compiles(_ExecDropFKConstraint, "mssql")
def _exec_drop_col_fk_constraint(element, compiler, **kw):
| 64 | 64 | 183 | 27 | 37 | kenmutuma001/Blog | virtual/lib/python3.6/site-packages/alembic/ddl/mssql.py | Python | _exec_drop_col_fk_constraint | _exec_drop_col_fk_constraint | 184 | 198 | 184 | 185 | ee676f3e8adafe93f0e8d15e8eeaa183b682d808 | bigcode/the-stack | train |
a95b7eb8fc6a963048252764 | train | function | def mssql_add_column(compiler, column, **kw):
return "ADD %s" % compiler.get_column_specification(column, **kw)
| def mssql_add_column(compiler, column, **kw):
| return "ADD %s" % compiler.get_column_specification(column, **kw)
| ssql")
def visit_add_column(element, compiler, **kw):
return "%s %s" % (
alter_table(compiler, element.table_name, element.schema),
mssql_add_column(compiler, element.column, **kw),
)
def mssql_add_column(compiler, column, **kw):
| 64 | 64 | 31 | 13 | 51 | kenmutuma001/Blog | virtual/lib/python3.6/site-packages/alembic/ddl/mssql.py | Python | mssql_add_column | mssql_add_column | 209 | 210 | 209 | 209 | 37fdd45d1aa0f297953b5097e083bd8b8f47d7a7 | bigcode/the-stack | train |
df4c8a3df648ec59567ecd1d | train | function | @compiles(RenameTable, "mssql")
def visit_rename_table(element, compiler, **kw):
return "EXEC sp_rename '%s', %s" % (
format_table_name(compiler, element.table_name, element.schema),
format_table_name(compiler, element.new_table_name, None),
)
| @compiles(RenameTable, "mssql")
def visit_rename_table(element, compiler, **kw):
| return "EXEC sp_rename '%s', %s" % (
format_table_name(compiler, element.table_name, element.schema),
format_table_name(compiler, element.new_table_name, None),
)
| s %s" % (
alter_table(compiler, element.table_name, element.schema),
alter_column(compiler, element.column_name),
format_type(compiler, element.type_),
)
@compiles(RenameTable, "mssql")
def visit_rename_table(element, compiler, **kw):
| 64 | 64 | 68 | 23 | 41 | kenmutuma001/Blog | virtual/lib/python3.6/site-packages/alembic/ddl/mssql.py | Python | visit_rename_table | visit_rename_table | 252 | 257 | 252 | 253 | 8760d616429bc9c436ece4ed824ab81c07409d41 | bigcode/the-stack | train |
b3cf04c08c11b78d08a3765c | train | function | @compiles(ColumnType, "mssql")
def visit_column_type(element, compiler, **kw):
return "%s %s %s" % (
alter_table(compiler, element.table_name, element.schema),
alter_column(compiler, element.column_name),
format_type(compiler, element.type_),
)
| @compiles(ColumnType, "mssql")
def visit_column_type(element, compiler, **kw):
| return "%s %s %s" % (
alter_table(compiler, element.table_name, element.schema),
alter_column(compiler, element.column_name),
format_type(compiler, element.type_),
)
| 'COLUMN'" % (
format_table_name(compiler, element.table_name, element.schema),
format_column_name(compiler, element.column_name),
format_column_name(compiler, element.newname),
)
@compiles(ColumnType, "mssql")
def visit_column_type(element, compiler, **kw):
| 64 | 64 | 67 | 21 | 43 | kenmutuma001/Blog | virtual/lib/python3.6/site-packages/alembic/ddl/mssql.py | Python | visit_column_type | visit_column_type | 243 | 249 | 243 | 244 | 56ee9e4f80008aa90e5b7a85d62309b34e90d222 | bigcode/the-stack | train |
0ea07f799fd3e70142e16771 | train | class | class _ExecDropConstraint(Executable, ClauseElement):
def __init__(self, tname, colname, type_):
self.tname = tname
self.colname = colname
self.type_ = type_
| class _ExecDropConstraint(Executable, ClauseElement):
| def __init__(self, tname, colname, type_):
self.tname = tname
self.colname = colname
self.type_ = type_
| ks = kw.pop("mssql_drop_foreign_key", False)
if drop_fks:
self._exec(_ExecDropFKConstraint(table_name, column))
super(MSSQLImpl, self).drop_column(table_name, column, **kw)
class _ExecDropConstraint(Executable, ClauseElement):
| 64 | 64 | 50 | 11 | 53 | kenmutuma001/Blog | virtual/lib/python3.6/site-packages/alembic/ddl/mssql.py | Python | _ExecDropConstraint | _ExecDropConstraint | 153 | 157 | 153 | 153 | 2997308a39a95aa59c1f9ae2e3ddf0f12b8c6e1f | bigcode/the-stack | train |
9a422586ced01002ffd7ce81 | train | function | @compiles(ColumnNullable, "mssql")
def visit_column_nullable(element, compiler, **kw):
return "%s %s %s %s" % (
alter_table(compiler, element.table_name, element.schema),
alter_column(compiler, element.column_name),
format_type(compiler, element.existing_type),
"NULL" if element.null... | @compiles(ColumnNullable, "mssql")
def visit_column_nullable(element, compiler, **kw):
| return "%s %s %s %s" % (
alter_table(compiler, element.table_name, element.schema),
alter_column(compiler, element.column_name),
format_type(compiler, element.existing_type),
"NULL" if element.nullable else "NOT NULL",
)
| _column(compiler, element.column, **kw),
)
def mssql_add_column(compiler, column, **kw):
return "ADD %s" % compiler.get_column_specification(column, **kw)
@compiles(ColumnNullable, "mssql")
def visit_column_nullable(element, compiler, **kw):
| 64 | 64 | 83 | 21 | 43 | kenmutuma001/Blog | virtual/lib/python3.6/site-packages/alembic/ddl/mssql.py | Python | visit_column_nullable | visit_column_nullable | 213 | 220 | 213 | 214 | 0c0f54c12d90bdf732a9a60e2a6d722db3c494dc | bigcode/the-stack | train |
343976f40300bd7ebcd4e240 | train | function | @compiles(ColumnDefault, "mssql")
def visit_column_default(element, compiler, **kw):
# TODO: there can also be a named constraint
# with ADD CONSTRAINT here
return "%s ADD DEFAULT %s FOR %s" % (
alter_table(compiler, element.table_name, element.schema),
format_server_default(compiler, elemen... | @compiles(ColumnDefault, "mssql")
def visit_column_default(element, compiler, **kw):
# TODO: there can also be a named constraint
# with ADD CONSTRAINT here
| return "%s ADD DEFAULT %s FOR %s" % (
alter_table(compiler, element.table_name, element.schema),
format_server_default(compiler, element.default),
format_column_name(compiler, element.column_name),
)
| (compiler, element.existing_type),
"NULL" if element.nullable else "NOT NULL",
)
@compiles(ColumnDefault, "mssql")
def visit_column_default(element, compiler, **kw):
# TODO: there can also be a named constraint
# with ADD CONSTRAINT here
| 64 | 64 | 91 | 41 | 23 | kenmutuma001/Blog | virtual/lib/python3.6/site-packages/alembic/ddl/mssql.py | Python | visit_column_default | visit_column_default | 223 | 231 | 223 | 226 | 05bfedd64ccbb1832cd06f623192a734064ef801 | bigcode/the-stack | train |
3ce280b6209da428124660c9 | train | function | @compiles(AddColumn, "mssql")
def visit_add_column(element, compiler, **kw):
return "%s %s" % (
alter_table(compiler, element.table_name, element.schema),
mssql_add_column(compiler, element.column, **kw),
)
| @compiles(AddColumn, "mssql")
def visit_add_column(element, compiler, **kw):
| return "%s %s" % (
alter_table(compiler, element.table_name, element.schema),
mssql_add_column(compiler, element.column, **kw),
)
| @const_name)""" % {
"tname": tname,
"colname": colname,
"tname_quoted": format_table_name(compiler, tname, None),
}
@compiles(AddColumn, "mssql")
def visit_add_column(element, compiler, **kw):
| 64 | 64 | 59 | 21 | 43 | kenmutuma001/Blog | virtual/lib/python3.6/site-packages/alembic/ddl/mssql.py | Python | visit_add_column | visit_add_column | 201 | 206 | 201 | 202 | 6ab50cef496f497585251917a0977674ef8c45ae | bigcode/the-stack | train |
6335d1580a7c8717ddfa14b0 | train | class | class MSSQLImpl(DefaultImpl):
__dialect__ = "mssql"
transactional_ddl = True
batch_separator = "GO"
def __init__(self, *arg, **kw):
super(MSSQLImpl, self).__init__(*arg, **kw)
self.batch_separator = self.context_opts.get(
"mssql_batch_separator", self.batch_separator
... | class MSSQLImpl(DefaultImpl):
| __dialect__ = "mssql"
transactional_ddl = True
batch_separator = "GO"
def __init__(self, *arg, **kw):
super(MSSQLImpl, self).__init__(*arg, **kw)
self.batch_separator = self.context_opts.get(
"mssql_batch_separator", self.batch_separator
)
def _exec(self, constr... | from sqlalchemy import types as sqltypes
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.schema import Column
from sqlalchemy.schema import CreateIndex
from sqlalchemy.sql.expression import ClauseElement
from sqlalchemy.sql.expression import Executable
from .base import AddColumn
from .base import alter_c... | 151 | 256 | 905 | 7 | 143 | kenmutuma001/Blog | virtual/lib/python3.6/site-packages/alembic/ddl/mssql.py | Python | MSSQLImpl | MSSQLImpl | 24 | 150 | 24 | 24 | a77d3bb750db58c71a147ed3433923691cb598ea | bigcode/the-stack | train |
77cc34507946511153423b4c | train | class | class _ExecDropFKConstraint(Executable, ClauseElement):
def __init__(self, tname, colname):
self.tname = tname
self.colname = colname
| class _ExecDropFKConstraint(Executable, ClauseElement):
| def __init__(self, tname, colname):
self.tname = tname
self.colname = colname
| )
class _ExecDropConstraint(Executable, ClauseElement):
def __init__(self, tname, colname, type_):
self.tname = tname
self.colname = colname
self.type_ = type_
class _ExecDropFKConstraint(Executable, ClauseElement):
| 63 | 64 | 41 | 12 | 51 | kenmutuma001/Blog | virtual/lib/python3.6/site-packages/alembic/ddl/mssql.py | Python | _ExecDropFKConstraint | _ExecDropFKConstraint | 160 | 163 | 160 | 160 | d44873f26136bf32a91a66c415c25fb34a61a8d2 | bigcode/the-stack | train |
5d37a941417ee538c32b8db1 | train | function | @compiles(ColumnName, "mssql")
def visit_rename_column(element, compiler, **kw):
return "EXEC sp_rename '%s.%s', %s, 'COLUMN'" % (
format_table_name(compiler, element.table_name, element.schema),
format_column_name(compiler, element.column_name),
format_column_name(compiler, element.newname)... | @compiles(ColumnName, "mssql")
def visit_rename_column(element, compiler, **kw):
| return "EXEC sp_rename '%s.%s', %s, 'COLUMN'" % (
format_table_name(compiler, element.table_name, element.schema),
format_column_name(compiler, element.column_name),
format_column_name(compiler, element.newname),
)
| FOR %s" % (
alter_table(compiler, element.table_name, element.schema),
format_server_default(compiler, element.default),
format_column_name(compiler, element.column_name),
)
@compiles(ColumnName, "mssql")
def visit_rename_column(element, compiler, **kw):
| 64 | 64 | 80 | 22 | 42 | kenmutuma001/Blog | virtual/lib/python3.6/site-packages/alembic/ddl/mssql.py | Python | visit_rename_column | visit_rename_column | 234 | 240 | 234 | 235 | c49f641f7537a69919eda63cc675f2ca09fcbe2a | bigcode/the-stack | train |
f4598d647c3e163b2036d966 | train | class | class DirectoryHandler(BaseHandler):
def __init__(self, hs: "HomeServer"):
super().__init__(hs)
self.state = hs.get_state_handler()
self.appservice_handler = hs.get_application_service_handler()
self.event_creation_handler = hs.get_event_creation_handler()
self.store = hs.ge... | class DirectoryHandler(BaseHandler):
| def __init__(self, hs: "HomeServer"):
super().__init__(hs)
self.state = hs.get_state_handler()
self.appservice_handler = hs.get_application_service_handler()
self.event_creation_handler = hs.get_event_creation_handler()
self.store = hs.get_datastore()
self.config = h... | "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 applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHO... | 256 | 256 | 3,628 | 6 | 250 | yunwah/synapse | synapse/handlers/directory.py | Python | DirectoryHandler | DirectoryHandler | 41 | 510 | 41 | 41 | 1a2b6ecc9fe903746419d80c590fa3508af43d68 | bigcode/the-stack | train |
afe1023322bbdfdfcf30ecd6 | train | class | class Migration(migrations.Migration):
dependencies = [
('builds', '0001_initial'),
('projects', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='ImportedFile',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=Fals... | class Migration(migrations.Migration):
| dependencies = [
('builds', '0001_initial'),
('projects', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='ImportedFile',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True))... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
| 31 | 65 | 217 | 7 | 23 | ank-forked/readthedocs.org | readthedocs/projects/migrations/0002_add_importedfile_model.py | Python | Migration | Migration | 7 | 28 | 7 | 8 | fb586b19efba543d0d177e7bf55359d2174e7628 | bigcode/the-stack | train |
b7de785492295e887794e879 | train | class | class Portfolio(ccobra.CCobraModel):
def __init__(self, name='Portfolio', optimize_rating=False):
super(Portfolio, self).__init__(name, ['syllogistic-belief'], ['verify'])
self.selectivescrutiny = ss.SelectiveScrutinyRestr()
self.misinterpretednecessity = mn.MisinterpretedNecessityRestr()
... | class Portfolio(ccobra.CCobraModel):
| def __init__(self, name='Portfolio', optimize_rating=False):
super(Portfolio, self).__init__(name, ['syllogistic-belief'], ['verify'])
self.selectivescrutiny = ss.SelectiveScrutinyRestr()
self.misinterpretednecessity = mn.MisinterpretedNecessityRestr()
self.nobelief = nobel.NoBelief... | import logging
import time
import ccobra
import numpy as np
import mreasoner
import fol
import phm
import SelectiveScrutinyModel as ss
import MisinterpretedNecessity as mn
import NoBeliefModel as nobel
logger = logging.getLogger(__name__)
class Portfolio(ccobra.CCobraModel):
| 72 | 256 | 930 | 9 | 63 | Shadownox/cogsci-beliefmodeling | models/portfolio.py | Python | Portfolio | Portfolio | 17 | 123 | 17 | 17 | ee947f9403fdd5ec766892186a3abe92e6af1d1b | bigcode/the-stack | train |
bd90420703f42fdd0361db88 | train | function | def main():
global counter
counter = 0
size = random.randint(1, 500)
arr = random_list(size)
depth = 0
path = "./heap_sort"
try:
os.mkdir(path)
except OSError as error:
pass
file = "./heap_sort/output-{}".format(size)
heapSort(arr, depth, file)
with open("./h... | def main():
| global counter
counter = 0
size = random.randint(1, 500)
arr = random_list(size)
depth = 0
path = "./heap_sort"
try:
os.mkdir(path)
except OSError as error:
pass
file = "./heap_sort/output-{}".format(size)
heapSort(arr, depth, file)
with open("./heap_sort/tra... | , 0, -1):
if depth==0:
counter = counter + 1
arr[i], arr[0] = arr[0], arr[i] # swap
heapify(arr, i, 0, depth+1, file)
# Driver collect traces
def main():
| 64 | 64 | 117 | 3 | 60 | JIexa/complexity-recurrence | recursive_programs/python/heap_sort.py | Python | main | main | 57 | 73 | 57 | 57 | 39e55e8272d1323a8addd89cfe1872dc01bfd1b4 | bigcode/the-stack | train |
aad82bbe4a324987330353e4 | train | function | def heapify(arr, n, i, depth, file):
with open(file, 'a') as f:
print("{};{}".format(depth, n-i), file=f)
if depth==0:
global counter
counter = counter+1
largest = i
l = 2 * i + 1
r = 2 * i + 2
if l < n and arr[i] < arr[l]:
largest = l
if r < n and arr[lar... | def heapify(arr, n, i, depth, file):
| with open(file, 'a') as f:
print("{};{}".format(depth, n-i), file=f)
if depth==0:
global counter
counter = counter+1
largest = i
l = 2 * i + 1
r = 2 * i + 2
if l < n and arr[i] < arr[l]:
largest = l
if r < n and arr[largest] < arr[r]:
largest = r
... | _list(size):
list = []
for i in range(size):
list.append(random.randint(-10000, 10000))
return list
# Recursive heapsort
#T(n) = T(n-1) + O(log n)
def heapify(arr, n, i, depth, file):
| 64 | 64 | 159 | 13 | 51 | JIexa/complexity-recurrence | recursive_programs/python/heap_sort.py | Python | heapify | heapify | 16 | 37 | 16 | 16 | ec5de39a6c7d9cc817d47ff9e563238806ce7d32 | bigcode/the-stack | train |
27a6032a4d0b4049c8d27980 | train | function | def heapSort(arr, depth, file):
n = len(arr)
global counter
for i in range(n//2 - 1, -1, -1):
if depth==0:
counter = counter + 1
heapify(arr, n, i, depth+1, file)
for i in range(n-1, 0, -1):
if depth==0:
counter = counter + 1
arr[i], arr[0] = arr... | def heapSort(arr, depth, file):
| n = len(arr)
global counter
for i in range(n//2 - 1, -1, -1):
if depth==0:
counter = counter + 1
heapify(arr, n, i, depth+1, file)
for i in range(n-1, 0, -1):
if depth==0:
counter = counter + 1
arr[i], arr[0] = arr[0], arr[i] # swap
heapi... | n and arr[largest] < arr[r]:
largest = r
if largest != i:
arr[i],arr[largest] = arr[largest],arr[i] # swap
heapify(arr, n, largest, depth+1, file)
def heapSort(arr, depth, file):
| 64 | 64 | 130 | 9 | 55 | JIexa/complexity-recurrence | recursive_programs/python/heap_sort.py | Python | heapSort | heapSort | 40 | 53 | 40 | 40 | 109efc885f1fe19dd9bad09e19855f0a6f04ec2e | bigcode/the-stack | train |
ac539da852d67eb21efbaa76 | train | function | def random_list(size):
list = []
for i in range(size):
list.append(random.randint(-10000, 10000))
return list
| def random_list(size):
| list = []
for i in range(size):
list.append(random.randint(-10000, 10000))
return list
| #!/usr/bin/env python3
import random
import os
counter = 0
def random_list(size):
| 23 | 64 | 33 | 5 | 17 | JIexa/complexity-recurrence | recursive_programs/python/heap_sort.py | Python | random_list | random_list | 8 | 12 | 8 | 8 | 337f6998ce70cd5d2c7371f81d6e379ec2f00fd9 | bigcode/the-stack | train |
a1544a773ef0656e1d1d70c4 | train | function | def inference(model, X, y=None, batch_size=16, metric_fn=accuracy_score, **kwargs):
"""inference Run the inference on the given dataset
Arguments:
model {Model} -- The Neural Network model
X {np.ndarray} -- The dataset input
y {np.ndarray} -- The sdataset labels
Keyword Arguments:
metric {function} -- Metr... | def inference(model, X, y=None, batch_size=16, metric_fn=accuracy_score, **kwargs):
| """inference Run the inference on the given dataset
Arguments:
model {Model} -- The Neural Network model
X {np.ndarray} -- The dataset input
y {np.ndarray} -- The sdataset labels
Keyword Arguments:
metric {function} -- Metric function to measure the performance of the model
(default: {accuracy_score})
... | _loss_single += loss_val
correct_val += np.ceil(accuracy_score(pred,labels)*batch_size)
val_acc_single = correct_val/len(val_dataloader.y)
val_acc.append(val_acc_single)
val_loss.append(val_loss_single)
print("Epoch: ", epoch+1, "Validation Accuracy:", 100*val_acc_single,"%", "Validation Loss:", val_... | 135 | 135 | 452 | 23 | 111 | ArvindSubramaniam/Neural-Nets-from-Scratch | main.py | Python | inference | inference | 191 | 236 | 191 | 191 | a90a759fa5a87699fb74651bdf88aa347ebc811a | bigcode/the-stack | train |
d1b24bfa48adf81e4790c92b | train | function | def decay_learning_rate(lr,epochss):
if epochss > 160:
lr = 0.02
return lr
| def decay_learning_rate(lr,epochss):
| if epochss > 160:
lr = 0.02
return lr
| .utils import Dataloader, one_hot_encoding, load_MNIST, save_csv
from sklearn.metrics import accuracy_score
import matplotlib.pyplot as plt
IntType = np.int64
FloatType = np.float64
#Decaying learning rate every 40 epochs
def decay_learning_rate(lr,epochss):
| 64 | 64 | 29 | 10 | 53 | ArvindSubramaniam/Neural-Nets-from-Scratch | main.py | Python | decay_learning_rate | decay_learning_rate | 14 | 17 | 14 | 14 | 3846772dbbfa65ea5d067985f10e4855fd86b784 | bigcode/the-stack | train |
85d3597d2a144a2b8e7bb5ac | train | class | class Model(object):
"""Model Your Deep Neural Network
"""
def __init__(self, input_dim, output_dim):
"""__init__ Constructor
Arguments:
input_dim {IntType or int} -- Number of input dimensions
output_dim {IntType or int} -- Number of classes
"""
self.input_dim = input_dim
self.output_dim = output_d... | class Model(object):
| """Model Your Deep Neural Network
"""
def __init__(self, input_dim, output_dim):
"""__init__ Constructor
Arguments:
input_dim {IntType or int} -- Number of input dimensions
output_dim {IntType or int} -- Number of classes
"""
self.input_dim = input_dim
self.output_dim = output_dim
self.loss_fn = S... | # -*- coding: utf-8 -*-
import numpy as np
from numpynet.layer import Dense, ELU, ReLU, SoftmaxCrossEntropy
from numpynet.function import Softmax
from numpynet.utils import Dataloader, one_hot_encoding, load_MNIST, save_csv
from sklearn.metrics import accuracy_score
import matplotlib.pyplot as plt
IntType = np.int64
... | 132 | 241 | 804 | 4 | 127 | ArvindSubramaniam/Neural-Nets-from-Scratch | main.py | Python | Model | Model | 20 | 115 | 20 | 20 | ddffe1b938e043d8d35a02cc60a425448e47d7ac | bigcode/the-stack | train |
58805ae852d044d33c269281 | train | function | def main():
print('loading data #####')
train_X, train_y = load_MNIST(path ='dataset/',name="train")
val_X, val_y = load_MNIST(path = 'dataset/', name="val")
test_X = load_MNIST(path = 'dataset/', name="test")
one_hot_train_y = one_hot_encoding(train_y)
test_loss, test_acc = None, None
print('loading data... | def main():
| print('loading data #####')
train_X, train_y = load_MNIST(path ='dataset/',name="train")
val_X, val_y = load_MNIST(path = 'dataset/', name="val")
test_X = load_MNIST(path = 'dataset/', name="test")
one_hot_train_y = one_hot_encoding(train_y)
test_loss, test_acc = None, None
print('loading data complete ##... | test_pred = np.concatenate((test_pred, pred), axis=0)
return test_pred[1:,:]
# raise NotImplementedError
else:
val_loss,correct_val = 0,0
for i,(inputs,labels) in enumerate(val_dataloader):
labels_one_hot = one_hot_encoding(labels,num_class=10)
output = model(inputs)
loss_val = model.bprop(output... | 207 | 207 | 693 | 3 | 203 | ArvindSubramaniam/Neural-Nets-from-Scratch | main.py | Python | main | main | 239 | 304 | 239 | 239 | 22cdb7cdde93360ca990bcc2685a6382feb3a9ae | bigcode/the-stack | train |
8853ca451383ef78d3c5ad1c | train | function | def train(model,
train_X,
train_y,
val_X,
val_y,
max_epochs=20,
lr=1e-3,
batch_size=16,
metric_fn=accuracy_score,
**kwargs):
"""train Train the model
Arguments:
model {Model} -- The Model object
train_X {np.ndarray} -- Training dataset
train_y {np.ndarray} -- Training labels... | def train(model,
train_X,
train_y,
val_X,
val_y,
max_epochs=20,
lr=1e-3,
batch_size=16,
metric_fn=accuracy_score,
**kwargs):
| """train Train the model
Arguments:
model {Model} -- The Model object
train_X {np.ndarray} -- Training dataset
train_y {np.ndarray} -- Training labels
val_X {np.ndarray} -- Validation dataset
val_y {np.ndarray} -- Validation labels
Keyword Arguments:
max_epochs {IntType or int} -- Maximum training expo... | ()
grad3 = grad_softm_crossent*self.elu3.bprop()
grad2 = self.Dense3.bprop(grad3)*self.elu2.bprop()
grad1 = self.Dense2.bprop(grad2)*self.elu1.bprop()
grad0 = self.Dense1.bprop(grad1)
return loss
# raise NotImplementedError
def update_parameters(self, lr):
"""update_parameters Update the parameters for ... | 221 | 221 | 739 | 51 | 169 | ArvindSubramaniam/Neural-Nets-from-Scratch | main.py | Python | train | train | 120 | 186 | 120 | 129 | c6fa317d24bd0407592ad71d31a318fef29dc7bb | bigcode/the-stack | train |
8801d24dda58ec53f7308d4c | train | class | class TestStringMethods(unittest.TestCase):
def setUp(self):
"""setup the test"""
# Web browser instance
self.driver = webdriver.Safari()
self.driver.get("http://127.0.0.1:8000/")
def test_homepage(self):
"""setup the test"""
# setup to start linked lis... | class TestStringMethods(unittest.TestCase):
| def setUp(self):
"""setup the test"""
# Web browser instance
self.driver = webdriver.Safari()
self.driver.get("http://127.0.0.1:8000/")
def test_homepage(self):
"""setup the test"""
# setup to start linked list game
# setup player
player_... | test: python -m unittest test_llist_gameboard.py
"""
# BEFORE TESTING: for this iteration (4/29/21),
# in LListGameboard.js : UNCOMMENT and COMMENT the appropriate lines in
# renderChambers() (lines 250 & 251)
import unittest
from selenium import webdriver
from time import sleep
from seleniu... | 99 | 99 | 330 | 8 | 90 | Plongesam/data-structures-game | src/Tests/test_llist_gameboard.py | Python | TestStringMethods | TestStringMethods | 25 | 68 | 25 | 26 | 11fea4098ea14195388d6f09ee55153c10b13b31 | bigcode/the-stack | train |
4b33c83d7b713b46f4c7dcf1 | train | function | def converter(*, sample_dt: str):
date_time_object = datetime.strptime(sample_dt, "%Y/%m/%d, %H:%M:%S")
# Not really going to deal with the whole timezone issue though :D
# local_timezone = pytz.timezone("US/Eastern")
# local_datetime = date_time_object.replace(tzinfo=pytz.utc)
# local_datetime = l... | def converter(*, sample_dt: str):
| date_time_object = datetime.strptime(sample_dt, "%Y/%m/%d, %H:%M:%S")
# Not really going to deal with the whole timezone issue though :D
# local_timezone = pytz.timezone("US/Eastern")
# local_datetime = date_time_object.replace(tzinfo=pytz.utc)
# local_datetime = local_datetime.astimezone(local_tim... | from datetime import datetime
import pytz
def converter(*, sample_dt: str):
| 18 | 64 | 124 | 9 | 8 | constancefr/MIAEtutorial | data/utils.py | Python | converter | converter | 5 | 14 | 5 | 5 | 394e92915d0f447f8363ae70fb4bed91e45c1853 | bigcode/the-stack | train |
07b33ebc6358d46d1dd93f6d | train | function | @pytest.mark.parametrize("dataset", ["cifar10", "cifar100"])
@pytest.mark.parametrize("model_name", ["mobilenetv2_x0_5", "mobilenetv2_x0_75", "mobilenetv2_x1_0", "mobilenetv2_x1_4"])
def test_resnet(dataset, model_name):
num_classes = 10 if dataset == "cifar10" else 100
model = getattr(mobilenetv2, f"{dataset}_... | @pytest.mark.parametrize("dataset", ["cifar10", "cifar100"])
@pytest.mark.parametrize("model_name", ["mobilenetv2_x0_5", "mobilenetv2_x0_75", "mobilenetv2_x1_0", "mobilenetv2_x1_4"])
def test_resnet(dataset, model_name):
| num_classes = 10 if dataset == "cifar10" else 100
model = getattr(mobilenetv2, f"{dataset}_{model_name}")()
x = torch.empty((1, 3, 32, 32))
y = model(x)
assert y.shape == (1, num_classes) | @pytest.mark.parametrize("dataset", ["cifar10", "cifar100"])
@pytest.mark.parametrize("model_name", ["mobilenetv2_x0_5", "mobilenetv2_x0_75", "mobilenetv2_x1_0", "mobilenetv2_x1_4"])
def test_resnet(dataset, model_name):
| 72 | 64 | 142 | 72 | 0 | chenyaofo/pytorch-cifar-models | tests/pytorch_cifar_models/test_mobilenetv2.py | Python | test_resnet | test_resnet | 7 | 14 | 7 | 9 | 7037526916dfde6001b97b758e80a44b87866b96 | bigcode/the-stack | train |
961cd2ac866b360bc9a180f9 | train | function | def Main(args):
print("Do Withdraw Test")
trigger = GetTrigger()
if trigger == Verification():
print("doing verification")
# check to see if the withdrawer is the owner
is_owner = CheckWitness(OWNER)
# always allow owner to withdraw
if is_owner:
ret... | def Main(args):
| print("Do Withdraw Test")
trigger = GetTrigger()
if trigger == Verification():
print("doing verification")
# check to see if the withdrawer is the owner
is_owner = CheckWitness(OWNER)
# always allow owner to withdraw
if is_owner:
return True
... | \xae\x0f\x93\x0e\xbe`\x85\xaf\x90\x93\xe5\xfeV\xb3J\\"\x0c\xcd\xcfn\xfc3o\xc5'
onDeposit = RegisterAction('deposit', 'account', 'amount')
onWithdraw = RegisterAction('withdraw', 'account', 'amount')
onWithdrawReconciled = RegisterAction('withdraw_reconcile', 'account', 'amount')
def Main(args):
| 96 | 96 | 321 | 4 | 92 | chisleu/neo-boa | boa/tests/src/WithdrawTest.py | Python | Main | Main | 23 | 87 | 23 | 24 | 954aa3658baf402e085f391e44f36992d63896ff | bigcode/the-stack | train |
2dd301a8ef1b2af70dd9e9dd | train | function | def CanWithdrawNeo():
print("[can withdraw]")
tx = GetScriptContainer()
type = GetType(tx)
print("[can withdraw] got tx type...")
if type == 209:
print("[can withdraw] Is invocation!!")
# this is the contract's address
sender_addr = GetExecutingScriptHash()
wit... | def CanWithdrawNeo():
| print("[can withdraw]")
tx = GetScriptContainer()
type = GetType(tx)
print("[can withdraw] got tx type...")
if type == 209:
print("[can withdraw] Is invocation!!")
# this is the contract's address
sender_addr = GetExecutingScriptHash()
withdrawal_amount = 0
... | don't really care what operation is called
# no matter what we will try to reconcile
did_withdraw = ReconcileBalances()
operation = args[0]
if operation == 'deposit':
if not did_withdraw:
deposit = DepositNeo()
return deposit
e... | 128 | 128 | 427 | 5 | 122 | chisleu/neo-boa | boa/tests/src/WithdrawTest.py | Python | CanWithdrawNeo | CanWithdrawNeo | 90 | 177 | 90 | 91 | 37d0e31b2383e7bead2e2f497d8f300a151699dc | bigcode/the-stack | train |
8ad176aaad8ab46b4fe218d5 | train | function | def ReconcileBalances():
print("[Reconcile balances]")
# this is the contract's address
sender_addr = GetExecutingScriptHash()
tx = GetScriptContainer()
withdrawal_amount = 0
receiver_addr = bytearray(0)
# go through the outputs of the tx
# and find ones that are neo
# and also ... | def ReconcileBalances():
| print("[Reconcile balances]")
# this is the contract's address
sender_addr = GetExecutingScriptHash()
tx = GetScriptContainer()
withdrawal_amount = 0
receiver_addr = bytearray(0)
# go through the outputs of the tx
# and find ones that are neo
# and also the receiver cannot be the... | True
return False
def BalanceOf(account):
"""
Method to return the current balance of an address
:param account: the account address to retrieve the balance for
:type account: bytearray
:return: the current balance of an address
:rtype: int
"""
print("getting balance of...")
... | 123 | 123 | 412 | 5 | 117 | chisleu/neo-boa | boa/tests/src/WithdrawTest.py | Python | ReconcileBalances | ReconcileBalances | 271 | 350 | 271 | 272 | c5fad4e42b935588f1b9848f5603514cbfb2a99e | bigcode/the-stack | train |
6d23e428d11ebb614171ce83 | train | function | def DepositNeo():
# get reference to the tx the invocation is in
tx = GetScriptContainer()
references = tx.References
if len(references) < 1:
print("no neo attached")
return False
# we need to determine who sent the tx
reference = references[0]
sender = GetScriptHash(refe... | def DepositNeo():
# get reference to the tx the invocation is in
| tx = GetScriptContainer()
references = tx.References
if len(references) < 1:
print("no neo attached")
return False
# we need to determine who sent the tx
reference = references[0]
sender = GetScriptHash(reference)
# this will keep track of how much neo was deposited
v... | _amount)
if withdrawal_amount <= current_balance:
print("[can withdraw] withdrawl amount il less than balance")
onWithdraw(receiver_addr, withdrawal_amount)
return True
else:
print("[can withdraw] not enough to witdraw")
... | 104 | 104 | 349 | 16 | 87 | chisleu/neo-boa | boa/tests/src/WithdrawTest.py | Python | DepositNeo | DepositNeo | 180 | 245 | 180 | 182 | 31009b39caab24750877da6aca01b15482c60817 | bigcode/the-stack | train |
c864f277bc146163984a105c | train | function | def BalanceOf(account):
"""
Method to return the current balance of an address
:param account: the account address to retrieve the balance for
:type account: bytearray
:return: the current balance of an address
:rtype: int
"""
print("getting balance of...")
context = GetContext()
... | def BalanceOf(account):
| """
Method to return the current balance of an address
:param account: the account address to retrieve the balance for
:type account: bytearray
:return: the current balance of an address
:rtype: int
"""
print("getting balance of...")
context = GetContext()
print("getting conte... | balance...")
Notify(current_balance)
new_balance = current_balance + value
print("new balance..")
Notify(new_balance)
Put(context, sender, new_balance)
print("deposited")
onDeposit(sender, value)
return True
return False
def BalanceOf(account):... | 64 | 64 | 112 | 5 | 58 | chisleu/neo-boa | boa/tests/src/WithdrawTest.py | Python | BalanceOf | BalanceOf | 248 | 268 | 248 | 248 | eead9a57e2bbdead14021d6d89eaa7b93e16b831 | bigcode/the-stack | train |
ad8c8e07567407853989d7b8 | train | class | class DrillV08(Drill):
def __init__(self):
super(DrillV08, self).__init__()
self._version = '0.8'
| class DrillV08(Drill):
| def __init__(self):
super(DrillV08, self).__init__()
self._version = '0.8'
| instances)
for instance in instances:
cmd.re_configure_sh(instance, cluster_context)
class DrillV07(Drill):
def __init__(self):
super(DrillV07, self).__init__()
self._version = '0.7'
class DrillV08(Drill):
| 64 | 64 | 37 | 8 | 56 | ksshanam/sahara | sahara/plugins/mapr/services/drill/drill.py | Python | DrillV08 | DrillV08 | 65 | 68 | 65 | 65 | c0a026a00825a00812c783f668349593c61bc554 | bigcode/the-stack | train |
3d15bb81d8261cdc26c8a00d | train | class | class Drill(s.Service):
def __init__(self):
super(Drill, self).__init__()
self._name = 'drill'
self._ui_name = 'Drill'
self._node_processes = [DRILL]
self._ui_info = [('Drill', DRILL, {s.SERVICE_UI: 'http://%s:8047'})]
self._validation_rules = [
vu.node_cl... | class Drill(s.Service):
| def __init__(self):
super(Drill, self).__init__()
self._name = 'drill'
self._ui_name = 'Drill'
self._node_processes = [DRILL]
self._ui_info = [('Drill', DRILL, {s.SERVICE_UI: 'http://%s:8047'})]
self._validation_rules = [
vu.node_client_package_conflict_vr... | r-drill',
open_ports=[8047]
)
DRILL_YARN = np.NodeProcess(
name='drill-bits-yarn',
ui_name='Drill on YARN',
package='mapr-drill-yarn',
open_ports=[8047]
)
class Drill(s.Service):
| 64 | 64 | 195 | 5 | 59 | ksshanam/sahara | sahara/plugins/mapr/services/drill/drill.py | Python | Drill | Drill | 36 | 56 | 36 | 36 | 22527a55cfbe95827ec34dedbea2c4fcd49d0755 | bigcode/the-stack | train |
793de861a60916e7c696a232 | train | class | class DrillV14(Drill):
def __init__(self):
super(DrillV14, self).__init__()
self._version = "1.4"
| class DrillV14(Drill):
| def __init__(self):
super(DrillV14, self).__init__()
self._version = "1.4"
| DrillV11, self).__init__()
self._version = "1.1"
class DrillV12(Drill):
def __init__(self):
super(DrillV12, self).__init__()
self._version = "1.2"
class DrillV14(Drill):
| 64 | 64 | 37 | 8 | 56 | ksshanam/sahara | sahara/plugins/mapr/services/drill/drill.py | Python | DrillV14 | DrillV14 | 89 | 92 | 89 | 89 | 5d6740fe5d50c80484297f0b3c5c1a76ffd44f43 | bigcode/the-stack | train |
0e11d294dafb393448bf3cbd | train | class | class DrillV16(Drill):
def __init__(self):
super(DrillV16, self).__init__()
self._version = "1.6"
| class DrillV16(Drill):
| def __init__(self):
super(DrillV16, self).__init__()
self._version = "1.6"
| DrillV12, self).__init__()
self._version = "1.2"
class DrillV14(Drill):
def __init__(self):
super(DrillV14, self).__init__()
self._version = "1.4"
class DrillV16(Drill):
| 64 | 64 | 37 | 8 | 56 | ksshanam/sahara | sahara/plugins/mapr/services/drill/drill.py | Python | DrillV16 | DrillV16 | 95 | 98 | 95 | 95 | 5c90fb943a5dc9d3f7e37316f29cbbb6126fb760 | bigcode/the-stack | train |
c56382e0851beeb54daf2f99 | train | class | class DrillV07(Drill):
def __init__(self):
super(DrillV07, self).__init__()
self._version = '0.7'
| class DrillV07(Drill):
| def __init__(self):
super(DrillV07, self).__init__()
self._version = '0.7'
| instances = instances or cluster_context.get_instances(DRILL)
super(Drill, self).install(cluster_context, instances)
self._set_service_dir_owner(cluster_context, instances)
for instance in instances:
cmd.re_configure_sh(instance, cluster_context)
class DrillV07(Drill):
| 64 | 64 | 37 | 8 | 56 | ksshanam/sahara | sahara/plugins/mapr/services/drill/drill.py | Python | DrillV07 | DrillV07 | 59 | 62 | 59 | 59 | 19f7c7ff98f7a0ba474b78da6fa8cda31405489d | bigcode/the-stack | train |
2cd41f6e345c98cfe1bf6880 | train | class | class DrillV19(Drill):
def __init__(self):
super(DrillV19, self).__init__()
self._version = "1.8"
self._node_processes = [DRILL, DRILL_YARN]
| class DrillV19(Drill):
| def __init__(self):
super(DrillV19, self).__init__()
self._version = "1.8"
self._node_processes = [DRILL, DRILL_YARN]
| .6"
class DrillV18(Drill):
def __init__(self):
super(DrillV18, self).__init__()
self._version = "1.8"
self._node_processes = [DRILL, DRILL_YARN]
class DrillV19(Drill):
| 64 | 64 | 53 | 8 | 56 | ksshanam/sahara | sahara/plugins/mapr/services/drill/drill.py | Python | DrillV19 | DrillV19 | 108 | 112 | 108 | 108 | b614472086fc7a07a38e838563ce9b27fa89d927 | bigcode/the-stack | train |
efd082b96ae0939458a9bc8c | train | class | class DrillV18(Drill):
def __init__(self):
super(DrillV18, self).__init__()
self._version = "1.8"
self._node_processes = [DRILL, DRILL_YARN]
| class DrillV18(Drill):
| def __init__(self):
super(DrillV18, self).__init__()
self._version = "1.8"
self._node_processes = [DRILL, DRILL_YARN]
| DrillV14, self).__init__()
self._version = "1.4"
class DrillV16(Drill):
def __init__(self):
super(DrillV16, self).__init__()
self._version = "1.6"
class DrillV18(Drill):
| 64 | 64 | 53 | 8 | 56 | ksshanam/sahara | sahara/plugins/mapr/services/drill/drill.py | Python | DrillV18 | DrillV18 | 101 | 105 | 101 | 101 | f173532e7c8dde6dc8bc11d5d51f8d77b49d7e1d | bigcode/the-stack | train |
f386e37473dbe9d58514bb12 | train | class | class DrillV12(Drill):
def __init__(self):
super(DrillV12, self).__init__()
self._version = "1.2"
| class DrillV12(Drill):
| def __init__(self):
super(DrillV12, self).__init__()
self._version = "1.2"
| DrillV09, self).__init__()
self._version = '0.9'
class DrillV11(Drill):
def __init__(self):
super(DrillV11, self).__init__()
self._version = "1.1"
class DrillV12(Drill):
| 64 | 64 | 37 | 8 | 56 | ksshanam/sahara | sahara/plugins/mapr/services/drill/drill.py | Python | DrillV12 | DrillV12 | 83 | 86 | 83 | 83 | e7bf84ad20f24559e87737fe78e43cd836ad6b78 | bigcode/the-stack | train |
443b1a59a8dd59a5eb3a8299 | train | class | class DrillV09(Drill):
def __init__(self):
super(DrillV09, self).__init__()
self._version = '0.9'
| class DrillV09(Drill):
| def __init__(self):
super(DrillV09, self).__init__()
self._version = '0.9'
| DrillV07, self).__init__()
self._version = '0.7'
class DrillV08(Drill):
def __init__(self):
super(DrillV08, self).__init__()
self._version = '0.8'
class DrillV09(Drill):
| 64 | 64 | 37 | 8 | 56 | ksshanam/sahara | sahara/plugins/mapr/services/drill/drill.py | Python | DrillV09 | DrillV09 | 71 | 74 | 71 | 71 | 236c7f3e314bcfa5520593f1b07b9e1a9fba0490 | bigcode/the-stack | train |
4decd6809e56cfa930f241c0 | train | class | class DrillV11(Drill):
def __init__(self):
super(DrillV11, self).__init__()
self._version = "1.1"
| class DrillV11(Drill):
| def __init__(self):
super(DrillV11, self).__init__()
self._version = "1.1"
| DrillV08, self).__init__()
self._version = '0.8'
class DrillV09(Drill):
def __init__(self):
super(DrillV09, self).__init__()
self._version = '0.9'
class DrillV11(Drill):
| 64 | 64 | 37 | 8 | 56 | ksshanam/sahara | sahara/plugins/mapr/services/drill/drill.py | Python | DrillV11 | DrillV11 | 77 | 80 | 77 | 77 | cfeaf0db6bb9bf3370b7ebc1fcaef63c012d3394 | bigcode/the-stack | train |
95d611ea10f07f41ccf35ee6 | train | function | def recursive_dict_of_lists(d, helper=None, prev_key=None):
"""
Builds dictionary of lists by recursively traversing a JSON-like
structure.
Arguments:
d (dict): JSON-like dictionary.
prev_key (str): Prefix used to create dictionary keys like: prefix_key.
Passed by recursive ... | def recursive_dict_of_lists(d, helper=None, prev_key=None):
| """
Builds dictionary of lists by recursively traversing a JSON-like
structure.
Arguments:
d (dict): JSON-like dictionary.
prev_key (str): Prefix used to create dictionary keys like: prefix_key.
Passed by recursive step, not intended to be used.
helper (dict): In cas... | tened.keys())
writer.writerows(zip_longest(*flattened.values()))
elif self.output.suffix == '.xlsx':
wb = Workbook()
ws = wb.active
ws.append((_ for _ in flattened.keys())) # doesn't take dict_keys ...
for row in zip_longest(*flattened.values()):... | 116 | 117 | 393 | 14 | 103 | tomasfarias/json2excel | converter.py | Python | recursive_dict_of_lists | recursive_dict_of_lists | 84 | 131 | 84 | 84 | 9240d06186510d3b212855d344d99662dd579d59 | bigcode/the-stack | train |
709799284c910c37e68f6e81 | train | class | class Converter:
"""
Converts JSON file to Excel or CSV file. Nested structures are flattened
by recursively appending lists of values.
"""
def __init__(self, input_file=None, output_file='result.csv'):
if input_file is not None:
self.input = Path(input_file)
self.output... | class Converter:
| """
Converts JSON file to Excel or CSV file. Nested structures are flattened
by recursively appending lists of values.
"""
def __init__(self, input_file=None, output_file='result.csv'):
if input_file is not None:
self.input = Path(input_file)
self.output = Path(output_fi... | import json
import csv
from pathlib import Path
from itertools import zip_longest
from openpyxl import Workbook
class Converter:
| 28 | 149 | 497 | 3 | 24 | tomasfarias/json2excel | converter.py | Python | Converter | Converter | 9 | 81 | 9 | 9 | 62726c097a7f5797acfa3ed370619d76bdfd04f8 | bigcode/the-stack | train |
75a29b61fa4c4c46f8fc72cb | train | function | def ds(k1, k2, r_vec_i, r_vec_j, cn_vec_i, cn_vec_j):
if k1 == 0:
ds_k1 = r_vec_i - r_vec_j
elif k1 == 1:
ds_k1 = cn_vec_i - cn_vec_j
if k2 == 0:
ds_k2 = r_vec_i - r_vec_j
elif k2 == 1:
ds_k2 = cn_vec_i - cn_vec_j
return (ds_k1*ds_k2)
| def ds(k1, k2, r_vec_i, r_vec_j, cn_vec_i, cn_vec_j):
| if k1 == 0:
ds_k1 = r_vec_i - r_vec_j
elif k1 == 1:
ds_k1 = cn_vec_i - cn_vec_j
if k2 == 0:
ds_k2 = r_vec_i - r_vec_j
elif k2 == 1:
ds_k2 = cn_vec_i - cn_vec_j
return (ds_k1*ds_k2)
| .exp(-0.5*((((r_vec_i - r_vec_j)**2)/(theta_r**2)) + (((cn_vec_i - cn_vec_j)**2)/(theta_cn**2)))))
def ds(k1, k2, r_vec_i, r_vec_j, cn_vec_i, cn_vec_j):
| 63 | 64 | 119 | 24 | 40 | KhunWasut/chempython | fe_construct.py | Python | ds | ds | 15 | 25 | 15 | 15 | 2cc19eb3dbd91877393ad9c3fb84a7c65f8591b6 | bigcode/the-stack | train |
fdcf99f013e9ae30c151727e | train | function | def fe_fit(r_vec, cn_vec, theta_r, theta_cn, chi, icf_vec, icf_var_vec, xi_star_vec):
# ICF's size: nD x 1
# icf_var_vec's size: nD x 1
var_mat = np.diag(icf_var_vec)
K = K_construct(r_vec, cn_vec, theta_r, theta_cn, chi)
inv_term = np.inv(K + var_mat)
icf_trans_vec = np.matmul(inv_term, icf_v... | def fe_fit(r_vec, cn_vec, theta_r, theta_cn, chi, icf_vec, icf_var_vec, xi_star_vec):
# ICF's size: nD x 1
# icf_var_vec's size: nD x 1
| var_mat = np.diag(icf_var_vec)
K = K_construct(r_vec, cn_vec, theta_r, theta_cn, chi)
inv_term = np.inv(K + var_mat)
icf_trans_vec = np.matmul(inv_term, icf_vec)
k_star_vec = k_star(r_vec, cn_vec, theta_r, theta_cn, chi, xi_star_vec)
free_energy = np.dot(k_star_vec, icf_trans_vec)
# Retu... | r_vec.shape*num_cv))
def fe_fit(r_vec, cn_vec, theta_r, theta_cn, chi, icf_vec, icf_var_vec, xi_star_vec):
# ICF's size: nD x 1
# icf_var_vec's size: nD x 1
| 64 | 64 | 182 | 58 | 6 | KhunWasut/chempython | fe_construct.py | Python | fe_fit | fe_fit | 67 | 82 | 67 | 70 | 22cc27d3ea0929c4ff62228c8a53b95a220b880f | bigcode/the-stack | train |
00303c6f316b0784aee1c9d4 | train | function | def kron_del(i,j):
if i == j:
return 1.0
else:
return 0.0
| def kron_del(i,j):
| if i == j:
return 1.0
else:
return 0.0
| ##### fe_construct.py #####
import numpy as np
def kron_del(i,j):
| 17 | 64 | 29 | 6 | 10 | KhunWasut/chempython | fe_construct.py | Python | kron_del | kron_del | 5 | 9 | 5 | 5 | d7aabcbbb2497a7a0e05022365ef4db201336d32 | bigcode/the-stack | train |
4c693463d0316b7f418ca8c7 | train | function | def k_star(r_vec, cn_vec, theta_r, theta_cn, chi, xi_star_vec, num_cv=2):
k_star_vec = []
for i in range(r_vec.shape):
dk_dr_i = (-1.0)*(chi**2)*(r_vec[i] - xi_star_vec[0])*exp_term(r_vec[i], xi_star_vec[0], cn_vec[i], xi_star_vec[1], theta_r, theta_cn)/(theta_r**2)
dk_dcn_i = (-1.0)*(chi**2)*(... | def k_star(r_vec, cn_vec, theta_r, theta_cn, chi, xi_star_vec, num_cv=2):
| k_star_vec = []
for i in range(r_vec.shape):
dk_dr_i = (-1.0)*(chi**2)*(r_vec[i] - xi_star_vec[0])*exp_term(r_vec[i], xi_star_vec[0], cn_vec[i], xi_star_vec[1], theta_r, theta_cn)/(theta_r**2)
dk_dcn_i = (-1.0)*(chi**2)*(cn_vec[i] - xi_star_vec[1])*exp_term(r_vec[i], xi_star_vec[0], cn_vec[i], ... | _i - r_vec_j
elif k2 == 1:
ds_k2 = cn_vec_i - cn_vec_j
return (ds_k1*ds_k2)
def k_star(r_vec, cn_vec, theta_r, theta_cn, chi, xi_star_vec, num_cv=2):
| 64 | 64 | 187 | 26 | 38 | KhunWasut/chempython | fe_construct.py | Python | k_star | k_star | 28 | 37 | 28 | 28 | a20a517c6cfe74214ac45e0120dbc294e4d8300b | bigcode/the-stack | train |
d9063141f3c1dba5191a75fe | train | function | def exp_term(r_vec_i, r_vec_j, cn_vec_i, cn_vec_j, theta_r, theta_cn):
return (np.exp(-0.5*((((r_vec_i - r_vec_j)**2)/(theta_r**2)) + (((cn_vec_i - cn_vec_j)**2)/(theta_cn**2)))))
| def exp_term(r_vec_i, r_vec_j, cn_vec_i, cn_vec_j, theta_r, theta_cn):
| return (np.exp(-0.5*((((r_vec_i - r_vec_j)**2)/(theta_r**2)) + (((cn_vec_i - cn_vec_j)**2)/(theta_cn**2)))))
| fe_construct.py #####
import numpy as np
def kron_del(i,j):
if i == j:
return 1.0
else:
return 0.0
def exp_term(r_vec_i, r_vec_j, cn_vec_i, cn_vec_j, theta_r, theta_cn):
| 64 | 64 | 68 | 25 | 38 | KhunWasut/chempython | fe_construct.py | Python | exp_term | exp_term | 11 | 12 | 11 | 11 | 0dc67c2bf73da41163db51f08a2182643e8cc19a | bigcode/the-stack | train |
3b9555b402cbe2c6cfba629c | train | function | def K_construct(r_vec, cn_vec, theta_r, theta_cn, chi, num_cv=2):
# The resulting matrix' size is nD x nD from n^2 D x D submatrices
dd_submatrices = []
for i in range(r_vec.shape):
for j in range(cn_vec.shape):
# In this loop, create DxD matrices and append to a list
dd_subm... | def K_construct(r_vec, cn_vec, theta_r, theta_cn, chi, num_cv=2):
# The resulting matrix' size is nD x nD from n^2 D x D submatrices
| dd_submatrices = []
for i in range(r_vec.shape):
for j in range(cn_vec.shape):
# In this loop, create DxD matrices and append to a list
dd_submatrix = []
for ii in range(num_cv):
for jj in range(num_cv):
fac = (chi**2)/((theta_r**2)... | cn_vec[i], xi_star_vec[1], theta_r, theta_cn)/(theta_cn**2)
k_star_vec.append(dk_dr_i)
k_star_vec.append(dk_dcn_i)
return np.array(k_star_vec)
# Populating K matrix
def K_construct(r_vec, cn_vec, theta_r, theta_cn, chi, num_cv=2):
# The resulting matrix' size is nD x nD from n^2 D x D submat... | 102 | 102 | 340 | 46 | 55 | KhunWasut/chempython | fe_construct.py | Python | K_construct | K_construct | 41 | 64 | 41 | 42 | 2f18c6f437c0e189366bd606ed901427211dbc01 | bigcode/the-stack | train |
707e33958fbe22a0d9e80c38 | train | class | class ApiAuthConfig(AppConfig):
name = 'api_auth'
| class ApiAuthConfig(AppConfig):
| name = 'api_auth'
| from django.apps import AppConfig
class ApiAuthConfig(AppConfig):
| 14 | 64 | 14 | 7 | 6 | chohankyun/chohankyun | api_auth/apps.py | Python | ApiAuthConfig | ApiAuthConfig | 4 | 5 | 4 | 4 | 7808d30590f03c9267db59cfc6ed1379f708da4a | bigcode/the-stack | train |
97cf6ad05321a00026cce440 | train | function | def random_book():
number_of_records = Book.objects.count()
random_index = int(random.random() * number_of_records) + 1
return Book.objects.get(pk=random_index)
| def random_book():
| number_of_records = Book.objects.count()
random_index = int(random.random() * number_of_records) + 1
return Book.objects.get(pk=random_index)
| "
__copyright__ = "Copyright (C) 2017, Vladimir Gerasimenko"
__version__ = "0.0.1"
__maintainer__ = "Vladimir Gerasimenko"
__email__ = "vladworldss@yandex.ru"
def random_book():
| 64 | 64 | 39 | 4 | 60 | vladworldss/arhivist | arhivist/books/views.py | Python | random_book | random_book | 18 | 21 | 18 | 18 | 6702ea45600bdf9bc8542d0fbf9a52264379196d | bigcode/the-stack | train |
fa96eea8301439f475ea1744 | train | class | class CategoryList(ListView):
queryset = Category.objects.all().order_by("name")
template_name = "category.html"
paginate_by = 10
| class CategoryList(ListView):
| queryset = Category.objects.all().order_by("name")
template_name = "category.html"
paginate_by = 10
| , **kwargs):
context = super().get_context_data(**kwargs)
context["pn"] = self.request.GET.get("page", "1")
context["cats"] = Category.objects.order_by("name")
context["random_book"] = random_book()
return context
class CategoryList(ListView):
| 64 | 64 | 33 | 6 | 57 | vladworldss/arhivist | arhivist/books/views.py | Python | CategoryList | CategoryList | 65 | 69 | 65 | 66 | 95e5f298fb3c79dd498c5da0a7aafab66c0f831e | bigcode/the-stack | train |
30ecb38c0ace4b74d1585208 | train | class | class BookDetail(DetailView):
template_name = "book.html"
model = Book
pk_url_kwarg = "book_id"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["pn"] = self.request.GET.get("page", "1")
context["cats"] = Category.objects.order_by("name... | class BookDetail(DetailView):
| template_name = "book.html"
model = Book
pk_url_kwarg = "book_id"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["pn"] = self.request.GET.get("page", "1")
context["cats"] = Category.objects.order_by("name")
context["random_book... | = self.cat
context["random_book"] = random_book()
return context
def get_queryset(self):
if self.cat:
return Book.objects.filter(category=self.cat).order_by("title")
else:
return Book.objects.all().order_by("title")
class BookDetail(DetailView):
| 64 | 64 | 94 | 7 | 57 | vladworldss/arhivist | arhivist/books/views.py | Python | BookDetail | BookDetail | 51 | 62 | 51 | 52 | 90d32c99afa795e3df1fc2199c36543205efc312 | bigcode/the-stack | train |
9349cc600aabbab5558a5f50 | train | class | class BooksList(ListView):
queryset = Book.objects.all()
template_name = "index.html"
paginate_by = 3
cat = None
def get(self, request, *args, **kw):
cat_id = self.kwargs["cat_id"]
if cat_id:
self.cat = Category.objects.get(pk=cat_id)
return super().get(request,... | class BooksList(ListView):
| queryset = Book.objects.all()
template_name = "index.html"
paginate_by = 3
cat = None
def get(self, request, *args, **kw):
cat_id = self.kwargs["cat_id"]
if cat_id:
self.cat = Category.objects.get(pk=cat_id)
return super().get(request, *args, **kw)
def get_c... | Gerasimenko"
__email__ = "vladworldss@yandex.ru"
def random_book():
number_of_records = Book.objects.count()
random_index = int(random.random() * number_of_records) + 1
return Book.objects.get(pk=random_index)
class BooksList(ListView):
| 64 | 64 | 183 | 6 | 58 | vladworldss/arhivist | arhivist/books/views.py | Python | BooksList | BooksList | 24 | 48 | 24 | 25 | d09d36b2100786eb9bd50a93909be0f720bcc378 | bigcode/the-stack | train |
d2a71a1a7a16bd8620101038 | train | class | class SelectionTexture2D(texture2d.Texture2D, SelectionTextureBase):
"""The ``SelectionTexture2D`` class is a :class:`.Texture2D` which can be
used to store a :class:`.Selection` instance. The ``Selection`` image
array is stored as a single channel 2D texture, which is updated whenever
the :attr:`.Sele... | class SelectionTexture2D(texture2d.Texture2D, SelectionTextureBase):
| """The ``SelectionTexture2D`` class is a :class:`.Texture2D` which can be
used to store a :class:`.Selection` instance. The ``Selection`` image
array is stored as a single channel 2D texture, which is updated whenever
the :attr:`.Selection.selection` property changes - updates are managed by
the :c... | (self):
"""Must be called when this ``SelectionTexture3D`` is no longer needed.
Calls the :meth:`.Texture.destroy` method, and removes the listener
on the :attr:`.Selection.selection` property.
"""
texture3d.Texture3D .destroy(self)
SelectionTextureBase.destroy(self)
clas... | 85 | 85 | 286 | 16 | 69 | pauldmccarthy/fsleyes | fsleyes/gl/textures/selectiontexture.py | Python | SelectionTexture2D | SelectionTexture2D | 114 | 144 | 114 | 114 | b1e8da67ece95dcb288c97c5ce79366b056db735 | bigcode/the-stack | train |
b6f077153854d08d041dda58 | train | class | class SelectionTexture3D(texture3d.Texture3D, SelectionTextureBase):
"""The ``SelectionTexture3D`` class is a :class:`.Texture3D` which can be
used to store a :class:`.Selection` instance. The ``Selection`` image
array is stored as a single channel 3D texture, which is updated whenever
the :attr:`.Sele... | class SelectionTexture3D(texture3d.Texture3D, SelectionTextureBase):
| """The ``SelectionTexture3D`` class is a :class:`.Texture3D` which can be
used to store a :class:`.Selection` instance. The ``Selection`` image
array is stored as a single channel 3D texture, which is updated whenever
the :attr:`.Selection.selection` property changes - updates are managed by
the :c... | data * 255).astype(np.uint8)
if init or (new is None):
data = prepare(self.__selection.getSelection(), shape)
self.set(data=data)
else:
data = prepare(new)
offset = affine.transform(offset, self.texCoordXform(shape))
self.doPatch(data, offse... | 85 | 85 | 286 | 16 | 69 | pauldmccarthy/fsleyes | fsleyes/gl/textures/selectiontexture.py | Python | SelectionTexture3D | SelectionTexture3D | 81 | 111 | 81 | 81 | fb057ab70ee9bee40e766500113d444216f53bba | bigcode/the-stack | train |
f914185442a5c31078ae5db7 | train | class | class SelectionTextureBase:
"""Base class shared by the :class:`SelectionTexture2D` and
:class:`SelectionTexture3D`. Manages updates from the :class:`.Selection`
object.
"""
def __init__(self, selection):
"""
This method must be called *after* :meth:`.Texture.__init__`.
"""
... | class SelectionTextureBase:
| """Base class shared by the :class:`SelectionTexture2D` and
:class:`SelectionTexture3D`. Manages updates from the :class:`.Selection`
object.
"""
def __init__(self, selection):
"""
This method must be called *after* :meth:`.Texture.__init__`.
"""
self.__selection = s... | Texture` types which can be used
to store :class:`.Selection` instances.
The ``SelectionTexture2D/3D`` classes are used by the :class:`.VoxelSelection`
annotation to display the contents of a :class:`.Selection` instance.
"""
import logging
import numpy as np
import OpenGL.GL as gl
import fsl.transform.affine ... | 110 | 110 | 368 | 5 | 105 | pauldmccarthy/fsleyes | fsleyes/gl/textures/selectiontexture.py | Python | SelectionTextureBase | SelectionTextureBase | 29 | 78 | 29 | 29 | a3bdccc5c848fc60c16ae06fde44e881f8042620 | bigcode/the-stack | train |
8c744cba8f17b4d4fe0fdb16 | train | function | def test_everything(realish_eventrouter, mock_websocket):
eventrouter = realish_eventrouter
t = eventrouter.teams.keys()[0]
socket = mock_websocket
eventrouter.teams[t].ws = socket
datafiles = glob.glob("_pytest/data/websocket/*.json")
for fname in sorted(datafiles):
data = json.loa... | def test_everything(realish_eventrouter, mock_websocket):
| eventrouter = realish_eventrouter
t = eventrouter.teams.keys()[0]
socket = mock_websocket
eventrouter.teams[t].ws = socket
datafiles = glob.glob("_pytest/data/websocket/*.json")
for fname in sorted(datafiles):
data = json.loads(open(fname, 'r').read())
socket.add(data)
... | import glob
import json
def test_everything(realish_eventrouter, mock_websocket):
| 19 | 64 | 116 | 13 | 5 | tomasv/wee-slack | _pytest/test_everything.py | Python | test_everything | test_everything | 4 | 21 | 4 | 5 | 657912b57cbf2fd3e10f9ccac1d9f03dfe6221b1 | bigcode/the-stack | train |
4196c1e15138799cf24b5fa8 | train | class | class ThanksView(TemplateView):
template_name = 'thanks.html'
| class ThanksView(TemplateView):
| template_name = 'thanks.html'
| _donor')
def form_invalid(self, form):
"""If the form is invalid, render the invalid form."""
return self.render_to_response(self.get_context_data(form=form))
def form_valid(self, form):
form.save()
return super().form_valid(form)
class ThanksView(TemplateView):
| 64 | 64 | 15 | 7 | 57 | aleducode/help-abejorral | abjhelp/users/views.py | Python | ThanksView | ThanksView | 48 | 49 | 48 | 48 | 8eb645c9145765463f57267d60803e0de0b62dff | bigcode/the-stack | train |
b6c7642887c4c1f812e42789 | train | class | class DonorRequestView(FormView):
template_name = 'donor_request.html'
form_class = DonorRequestForm
success_url = reverse_lazy('users:thanks_donor')
def form_invalid(self, form):
"""If the form is invalid, render the invalid form."""
return self.render_to_response(self.get_context_data... | class DonorRequestView(FormView):
| template_name = 'donor_request.html'
form_class = DonorRequestForm
success_url = reverse_lazy('users:thanks_donor')
def form_invalid(self, form):
"""If the form is invalid, render the invalid form."""
return self.render_to_response(self.get_context_data(form=form))
def form_valid(s... | '
class HelpRequestView(FormView):
template_name = 'help_request.html'
form_class = HelpRequestForm
success_url = reverse_lazy('users:thanks')
def form_valid(self, form):
form.save()
return super().form_valid(form)
class DonorRequestView(FormView):
| 64 | 64 | 94 | 8 | 56 | aleducode/help-abejorral | abjhelp/users/views.py | Python | DonorRequestView | DonorRequestView | 34 | 45 | 34 | 34 | 116a311abc2ec8863ae0266d18758a480750e9ca | bigcode/the-stack | train |
1cc4fc27a425f57c6650cb71 | train | class | class DisclaimerView(TemplateView):
template_name = 'disclaimer.html'
| class DisclaimerView(TemplateView):
| template_name = 'disclaimer.html'
| FormView, DetailView
from django.urls import reverse_lazy
# Forms
from abjhelp.users.forms import HelpRequestForm, DonorRequestForm
from abjhelp.users.models import HelpRequest
class DashboardView(TemplateView):
template_name = 'index.html'
class DisclaimerView(TemplateView):
| 64 | 64 | 16 | 7 | 57 | aleducode/help-abejorral | abjhelp/users/views.py | Python | DisclaimerView | DisclaimerView | 16 | 17 | 16 | 16 | bfa3d2674b8a05157ad6e566f45247344452f849 | bigcode/the-stack | train |
8d994eefd2300ecf9b5ef627 | train | class | class ThanksDonorView(TemplateView):
template_name = 'thank_donor.html'
| class ThanksDonorView(TemplateView):
| template_name = 'thank_donor.html'
| invalid, render the invalid form."""
return self.render_to_response(self.get_context_data(form=form))
def form_valid(self, form):
form.save()
return super().form_valid(form)
class ThanksView(TemplateView):
template_name = 'thanks.html'
class ThanksDonorView(TemplateView):
| 64 | 64 | 19 | 9 | 55 | aleducode/help-abejorral | abjhelp/users/views.py | Python | ThanksDonorView | ThanksDonorView | 52 | 53 | 52 | 52 | 82984a3b479f5784c6f76077536902612a5f71a8 | bigcode/the-stack | train |
37a49e9c5a4b7bb54df9ee36 | train | class | class DashboardView(TemplateView):
template_name = 'index.html'
| class DashboardView(TemplateView):
| template_name = 'index.html'
| """Branches Views."""
# Django
from django.views.generic import TemplateView, FormView, DetailView
from django.urls import reverse_lazy
# Forms
from abjhelp.users.forms import HelpRequestForm, DonorRequestForm
from abjhelp.users.models import HelpRequest
class DashboardView(TemplateView):
| 64 | 64 | 15 | 7 | 56 | aleducode/help-abejorral | abjhelp/users/views.py | Python | DashboardView | DashboardView | 12 | 13 | 12 | 12 | 832ecc1e975f52630c4663815303f1a6bb51e133 | bigcode/the-stack | train |
3e18079672a71ba0877b5e83 | train | class | class InformationView(TemplateView):
template_name = 'information.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["helps"] = HelpRequest.objects.all()
return context
| class InformationView(TemplateView):
| template_name = 'information.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["helps"] = HelpRequest.objects.all()
return context
| super().form_valid(form)
class ThanksView(TemplateView):
template_name = 'thanks.html'
class ThanksDonorView(TemplateView):
template_name = 'thank_donor.html'
class AdvisorView(TemplateView):
template_name = 'legal_advisor.html'
class InformationView(TemplateView):
| 64 | 64 | 51 | 7 | 57 | aleducode/help-abejorral | abjhelp/users/views.py | Python | InformationView | InformationView | 60 | 66 | 60 | 60 | feeb9fda2f019db7e853f7ff5ab9d2825904164f | bigcode/the-stack | train |
ce0ff9a4c45cce8a5dce779f | train | class | class AdvisorView(TemplateView):
template_name = 'legal_advisor.html'
| class AdvisorView(TemplateView):
| template_name = 'legal_advisor.html'
| (form=form))
def form_valid(self, form):
form.save()
return super().form_valid(form)
class ThanksView(TemplateView):
template_name = 'thanks.html'
class ThanksDonorView(TemplateView):
template_name = 'thank_donor.html'
class AdvisorView(TemplateView):
| 64 | 64 | 17 | 7 | 57 | aleducode/help-abejorral | abjhelp/users/views.py | Python | AdvisorView | AdvisorView | 56 | 57 | 56 | 56 | e8c8af07235c40f27de46e9f912357e3cb42ead8 | bigcode/the-stack | train |
725b5955f23042f31d6b35d7 | train | class | class DisclaimerDonorView(TemplateView):
template_name = 'disclaimer_donor.html'
| class DisclaimerDonorView(TemplateView):
| template_name = 'disclaimer_donor.html'
| jhelp.users.forms import HelpRequestForm, DonorRequestForm
from abjhelp.users.models import HelpRequest
class DashboardView(TemplateView):
template_name = 'index.html'
class DisclaimerView(TemplateView):
template_name = 'disclaimer.html'
class DisclaimerDonorView(TemplateView):
| 64 | 64 | 20 | 9 | 55 | aleducode/help-abejorral | abjhelp/users/views.py | Python | DisclaimerDonorView | DisclaimerDonorView | 20 | 21 | 20 | 20 | 450cfe1dc52b0ee97cac1737b8abd5ef1a7ecae3 | bigcode/the-stack | train |
c96ff1a70c6317cce24883f7 | train | class | class RequestDetailView(DetailView):
template_name = 'detail.html'
slug_field = 'pk'
slug_url_kwarg = 'pk'
queryset = HelpRequest.objects.all()
context_object_name = 'help'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
help_request = self.get... | class RequestDetailView(DetailView):
| template_name = 'detail.html'
slug_field = 'pk'
slug_url_kwarg = 'pk'
queryset = HelpRequest.objects.all()
context_object_name = 'help'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
help_request = self.get_object()
context["whatsapp"]... | legal_advisor.html'
class InformationView(TemplateView):
template_name = 'information.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["helps"] = HelpRequest.objects.all()
return context
class RequestDetailView(DetailView):
| 64 | 64 | 163 | 8 | 55 | aleducode/help-abejorral | abjhelp/users/views.py | Python | RequestDetailView | RequestDetailView | 68 | 79 | 68 | 68 | 0eeb013e17ad1ed12c199aafd4a49a6b7d24dcfc | bigcode/the-stack | train |
829e2a5ab888a65d211e1dd5 | train | class | class HelpRequestView(FormView):
template_name = 'help_request.html'
form_class = HelpRequestForm
success_url = reverse_lazy('users:thanks')
def form_valid(self, form):
form.save()
return super().form_valid(form)
| class HelpRequestView(FormView):
| template_name = 'help_request.html'
form_class = HelpRequestForm
success_url = reverse_lazy('users:thanks')
def form_valid(self, form):
form.save()
return super().form_valid(form)
| .users.models import HelpRequest
class DashboardView(TemplateView):
template_name = 'index.html'
class DisclaimerView(TemplateView):
template_name = 'disclaimer.html'
class DisclaimerDonorView(TemplateView):
template_name = 'disclaimer_donor.html'
class HelpRequestView(FormView):
| 64 | 64 | 55 | 7 | 57 | aleducode/help-abejorral | abjhelp/users/views.py | Python | HelpRequestView | HelpRequestView | 24 | 31 | 24 | 24 | aa12786f2ca91e9d6ac15a2a5c7f8f4b2197cd31 | bigcode/the-stack | train |
94eb4f58dacd6d55be4acf8f | train | class | class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Contact',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
... | class Migration(migrations.Migration):
| initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Contact',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(ma... | # Generated by Django 3.2.4 on 2021-08-29 09:09
from django.db import migrations, models
class Migration(migrations.Migration):
| 38 | 64 | 101 | 7 | 30 | Snehal0203/Supportwall1 | supportwall/home/migrations/0001_initial.py | Python | Migration | Migration | 6 | 23 | 6 | 7 | 81a40084d7ae642f7b9a1adcc06b690bc54cdb6c | bigcode/the-stack | train |
fab18571c542374b9f2d84dd | train | class | @pytest.mark.skipif(should_skip, reason="No environment variables configured")
class TestWallet:
def test_create_wallet(self):
qiwi_wallet = Wallet(TOKEN, number=NUMBER)
assert isinstance(qiwi_wallet, Wallet)
qiwi_wallet = Wallet(TOKEN)
assert isinstance(qiwi_wallet, Wallet)
def... | @pytest.mark.skipif(should_skip, reason="No environment variables configured")
class TestWallet:
| def test_create_wallet(self):
qiwi_wallet = Wallet(TOKEN, number=NUMBER)
assert isinstance(qiwi_wallet, Wallet)
qiwi_wallet = Wallet(TOKEN)
assert isinstance(qiwi_wallet, Wallet)
def test_check_history(self):
qiwi_wallet = Wallet(TOKEN, number=NUMBER)
assert isin... | # -*- coding: utf-8 -*-
import sys
sys.path.append('../')
import pytest
import os
import datetime
import pyqiwi
from pyqiwi import Wallet
from pyqiwi.util import url_params, merge_dicts, split_float
from urllib.parse import unquote
should_skip = 'TOKEN' and 'NUMBER' not in os.environ
if not should_skip:
TOKEN ... | 115 | 232 | 776 | 19 | 96 | arichr/pyqiwi | tests/test_wallet.py | Python | TestWallet | TestWallet | 22 | 100 | 22 | 23 | 97eeccb18ce5236c95322ce6a53a2bb58f7a988a | bigcode/the-stack | train |
ffdf5c600afaf154ea6915cb | train | function | def run(spark, predict_data, model):
input_data = predict_data.select("payload")
dataframe = spark.read.json(input_data.rdd.map(lambda r: r.payload))
for col_name in dataframe.columns:
test = dataframe.withColumn(col_name, dataframe[col_name].cast(DoubleType()))
if test.where(test[col_name].isNull()).count() ==... | def run(spark, predict_data, model):
| input_data = predict_data.select("payload")
dataframe = spark.read.json(input_data.rdd.map(lambda r: r.payload))
for col_name in dataframe.columns:
test = dataframe.withColumn(col_name, dataframe[col_name].cast(DoubleType()))
if test.where(test[col_name].isNull()).count() == dataframe.count():
indexer = Stri... | from pyspark.ml.feature import VectorAssembler, StringIndexer
from pyspark.sql.types import DoubleType
def run(spark, predict_data, model):
| 31 | 64 | 188 | 10 | 20 | selisproject/bda | bda-analytics-ml/src/main/resources/shared_recipes/linear_regression_predict.py | Python | run | run | 4 | 22 | 4 | 4 | 0a368c5e4d300ab01bc916cf858bdde9340ad5b9 | bigcode/the-stack | train |
35b00f1991e0f1d2ed088373 | train | class | class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Category',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
... | class Migration(migrations.Migration):
| initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Category',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(blank=True, de... | # -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-12-08 23:03
from __future__ import unicode_literals
import ckeditor_uploader.fields
from django.db import migrations, models
import django.db.models.deletion
import django.db.models.manager
import embed_video.fields
import mptt.fields
class Migration(migratio... | 85 | 256 | 1,591 | 7 | 77 | skylifewww/pangolinreact | product/migrations/0001_initial.py | Python | Migration | Migration | 13 | 152 | 13 | 14 | d095f10a99ba905bcfe9237ca0c7ab365b7c3f01 | bigcode/the-stack | train |
0ad0f3262a6d6b8b8aec9422 | train | function | def password_generator(num_lowercase=-1, num_uppercase=-1, num_numbers=-1, num_characters=-1):
lowercase = list(string.ascii_lowercase) # generate a list of lowercase characters in ascii
uppercase = list(string.ascii_uppercase) # generate a list of uppercase characters in ascii
numbers = list(number for n... | def password_generator(num_lowercase=-1, num_uppercase=-1, num_numbers=-1, num_characters=-1):
| lowercase = list(string.ascii_lowercase) # generate a list of lowercase characters in ascii
uppercase = list(string.ascii_uppercase) # generate a list of uppercase characters in ascii
numbers = list(number for number in range(10)) # generate a list of numbers
characters = list(c for c in (chr(i) for ... | import string
from random import choice, shuffle
def password_generator(num_lowercase=-1, num_uppercase=-1, num_numbers=-1, num_characters=-1):
| 36 | 131 | 439 | 26 | 9 | amgad01/algorithms | 100 days of code/password-generator.py | Python | password_generator | password_generator | 5 | 32 | 5 | 5 | 59e3ef035483b5e24a0bdf604af5f814726f6eda | bigcode/the-stack | train |
3905305f8b0d311f23608069 | train | class | class Geometry:
"""
A Geometry manages all of the viewports and measurement-related variables
for a widget.
"""
DEFAULT_ZOOM = [100.0, 100.0]
LAYOUT_BORDER = 0
ZOOM_RANGE = [[0.1, 10.0], [2000.0, 400.0]]
def __init__(self):
ortho_view = BoundedOrthoView(
scene_rect=R... | class Geometry:
| """
A Geometry manages all of the viewports and measurement-related variables
for a widget.
"""
DEFAULT_ZOOM = [100.0, 100.0]
LAYOUT_BORDER = 0
ZOOM_RANGE = [[0.1, 10.0], [2000.0, 400.0]]
def __init__(self):
ortho_view = BoundedOrthoView(
scene_rect=Rect(),
... | import numpy as np
from rectangle import Rect
from glx import BoundedOrthoView, OrthoProjection, Viewport
class Geometry:
| 30 | 159 | 533 | 3 | 26 | NeilGirdhar/glx | demonstration/geometry.py | Python | Geometry | Geometry | 7 | 81 | 7 | 7 | f162c791fadcfd0685bf214f8de4017fce9dd211 | bigcode/the-stack | train |
2a379777c376aa1bb86524d1 | train | function | def parse_command_line_arguments() -> CLArgs:
default_directory = os.path.join('output', ds.script_name_no_ext())
parser = argparse.ArgumentParser( # noqa
description='Small example design for testing.',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-o', '--o... | def parse_command_line_arguments() -> CLArgs:
| default_directory = os.path.join('output', ds.script_name_no_ext())
parser = argparse.ArgumentParser( # noqa
description='Small example design for testing.',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-o', '--output-dir', type=str, default=default_director... | _nupack as dv # type: ignore
import dsd.search as ds # type: ignore
from dsd.constraints import NumpyConstraint
# command-line arguments
class CLArgs(NamedTuple):
directory: str
restart: bool
def parse_command_line_arguments() -> CLArgs:
| 64 | 64 | 214 | 10 | 53 | dsd-test-nupack-in-github-workflow/dsd | examples/many_strands_no_common_domains.py | Python | parse_command_line_arguments | parse_command_line_arguments | 19 | 37 | 19 | 19 | 33cd9e06d37e520e214c569fad2f67afaeb7e6f1 | bigcode/the-stack | train |
b83a55d9f15124c348976fb0 | train | function | def main() -> None:
args: CLArgs = parse_command_line_arguments()
# dc.logger.setLevel(logging.DEBUG)
dc.logger.setLevel(logging.INFO)
random_seed = 1
# many 4-domain strands with no common domains, 4 domains each, every domain length = 10
# just for testing parallel processing
# num_str... | def main() -> None:
| args: CLArgs = parse_command_line_arguments()
# dc.logger.setLevel(logging.DEBUG)
dc.logger.setLevel(logging.INFO)
random_seed = 1
# many 4-domain strands with no common domains, 4 domains each, every domain length = 10
# just for testing parallel processing
# num_strands = 2
# num_s... | # type: ignore
from dsd.constraints import NumpyConstraint
# command-line arguments
class CLArgs(NamedTuple):
directory: str
restart: bool
def parse_command_line_arguments() -> CLArgs:
default_directory = os.path.join('output', ds.script_name_no_ext())
parser = argparse.ArgumentParser( # noqa
... | 256 | 256 | 1,263 | 6 | 250 | dsd-test-nupack-in-github-workflow/dsd | examples/many_strands_no_common_domains.py | Python | main | main | 40 | 167 | 40 | 40 | 3a3c962073f1d5fc6182873fc82054e58b83f7b9 | bigcode/the-stack | train |
7281ec653a13660d5b2de90a | train | class | class CLArgs(NamedTuple):
directory: str
restart: bool
| class CLArgs(NamedTuple):
| directory: str
restart: bool
| import List
import dsd.constraints as dc # type: ignore
import dsd.vienna_nupack as dv # type: ignore
import dsd.search as ds # type: ignore
from dsd.constraints import NumpyConstraint
# command-line arguments
class CLArgs(NamedTuple):
| 64 | 64 | 17 | 7 | 56 | dsd-test-nupack-in-github-workflow/dsd | examples/many_strands_no_common_domains.py | Python | CLArgs | CLArgs | 14 | 16 | 14 | 14 | d48d990161aafe6cdcef715cdf2b41598f925c33 | bigcode/the-stack | train |
143db08e92f860c52fd9be88 | train | class | class ExceptionInfo(object):
def __init__(self, *info):
if not info:
info = sys.exc_info()
self.type, self.value, self.traceback = info
def __bool__(self):
"""
Return True if an exception occurred
"""
return bool(self.type)
__nonzero__ = __bool__... | class ExceptionInfo(object):
| def __init__(self, *info):
if not info:
info = sys.exc_info()
self.type, self.value, self.traceback = info
def __bool__(self):
"""
Return True if an exception occurred
"""
return bool(self.type)
__nonzero__ = __bool__
| self.exc_info = object.__new__(ExceptionInfo)
return self.exc_info
def __exit__(self, *exc_info):
self.exc_info.__init__(*exc_info)
return self.exc_info.type and issubclass(
self.exc_info.type, self.ExpectedException)
class ExceptionInfo(object):
| 64 | 64 | 74 | 5 | 59 | jerumanu/pitches2 | virtual/lib/python3.6/site-packages/keyring/errors.py | Python | ExceptionInfo | ExceptionInfo | 44 | 56 | 44 | 44 | daa114bc47432c0b01850f8ee0ac632d4baa134b | bigcode/the-stack | train |
66a5e672c0e1f7dd935ba84a | train | class | class KeyringError(Exception):
"""Base class for exceptions in keyring
"""
| class KeyringError(Exception):
| """Base class for exceptions in keyring
"""
| import sys
class KeyringError(Exception):
| 9 | 64 | 18 | 6 | 2 | jerumanu/pitches2 | virtual/lib/python3.6/site-packages/keyring/errors.py | Python | KeyringError | KeyringError | 4 | 6 | 4 | 4 | 356d686f09453460e20d28a29d8b75cabacb7a7d | bigcode/the-stack | train |
80e6a89ef3a1f207e0686809 | train | class | class PasswordDeleteError(KeyringError):
"""Raised when the password can't be deleted.
"""
| class PasswordDeleteError(KeyringError):
| """Raised when the password can't be deleted.
"""
| import sys
class KeyringError(Exception):
"""Base class for exceptions in keyring
"""
class PasswordSetError(KeyringError):
"""Raised when the password can't be set.
"""
class PasswordDeleteError(KeyringError):
| 50 | 64 | 20 | 8 | 42 | jerumanu/pitches2 | virtual/lib/python3.6/site-packages/keyring/errors.py | Python | PasswordDeleteError | PasswordDeleteError | 14 | 16 | 14 | 14 | 7920700f2f961d5c0e8d09be7f77eefcbce2d771 | bigcode/the-stack | train |
9b1d420282e2e95706681b86 | train | class | class InitError(KeyringError):
"""Raised when the keyring could not be initialised
"""
| class InitError(KeyringError):
| """Raised when the keyring could not be initialised
"""
| (Exception):
"""Base class for exceptions in keyring
"""
class PasswordSetError(KeyringError):
"""Raised when the password can't be set.
"""
class PasswordDeleteError(KeyringError):
"""Raised when the password can't be deleted.
"""
class InitError(KeyringError):
| 63 | 64 | 22 | 7 | 56 | jerumanu/pitches2 | virtual/lib/python3.6/site-packages/keyring/errors.py | Python | InitError | InitError | 19 | 21 | 19 | 19 | 983778bb9d36c5043053301fe7ab06bfd6bdb915 | bigcode/the-stack | train |
3aff7ea6969cf03b524963e7 | train | class | class PasswordSetError(KeyringError):
"""Raised when the password can't be set.
"""
| class PasswordSetError(KeyringError):
| """Raised when the password can't be set.
"""
| import sys
class KeyringError(Exception):
"""Base class for exceptions in keyring
"""
class PasswordSetError(KeyringError):
| 29 | 64 | 20 | 8 | 21 | jerumanu/pitches2 | virtual/lib/python3.6/site-packages/keyring/errors.py | Python | PasswordSetError | PasswordSetError | 9 | 11 | 9 | 9 | 715975f6ddd85dce16dfe555208bc60ab00d0b92 | bigcode/the-stack | train |
a7dd02af73e5599e55de0389 | train | class | class ExceptionRaisedContext(object):
"""
An exception-trapping context that indicates whether an exception was
raised.
"""
def __init__(self, ExpectedException=Exception):
self.ExpectedException = ExpectedException
self.exc_info = None
def __enter__(self):
self.exc_inf... | class ExceptionRaisedContext(object):
| """
An exception-trapping context that indicates whether an exception was
raised.
"""
def __init__(self, ExpectedException=Exception):
self.ExpectedException = ExpectedException
self.exc_info = None
def __enter__(self):
self.exc_info = object.__new__(ExceptionInfo)
... | ):
"""Raised when the password can't be set.
"""
class PasswordDeleteError(KeyringError):
"""Raised when the password can't be deleted.
"""
class InitError(KeyringError):
"""Raised when the keyring could not be initialised
"""
class ExceptionRaisedContext(object):
| 63 | 64 | 120 | 6 | 57 | jerumanu/pitches2 | virtual/lib/python3.6/site-packages/keyring/errors.py | Python | ExceptionRaisedContext | ExceptionRaisedContext | 24 | 41 | 24 | 24 | f162bdbb6f36876281181d856aed9c034877662f | bigcode/the-stack | train |
030567f5a7f8ba5f8169b2eb | train | class | class OAuthAddonConfigViewsTestCaseMixin(OAuthAddonTestCaseMixin):
@property
def folder(self):
raise NotImplementedError("This test suite must expose a 'folder' property.")
@property
def Serializer(self):
raise NotImplementedError()
@property
def client(self):
raise No... | class OAuthAddonConfigViewsTestCaseMixin(OAuthAddonTestCaseMixin):
@property
| def folder(self):
raise NotImplementedError("This test suite must expose a 'folder' property.")
@property
def Serializer(self):
raise NotImplementedError()
@property
def client(self):
raise NotImplementedError()
def test_import_auth(self):
ea = self.ExternalAcc... | mock.patch.object(self.Provider, 'auth_callback') as mock_callback:
mock_callback.return_value = True
res = self.app.get(url, auth=self.user.auth)
assert_equal(res.status_code, http.OK)
name, args, kwargs = mock_callback.mock_calls[0]
assert_equal(kwargs['user']._id, sel... | 256 | 256 | 1,357 | 19 | 237 | sf2ne/Playground | website/addons/base/testing/views.py | Python | OAuthAddonConfigViewsTestCaseMixin | OAuthAddonConfigViewsTestCaseMixin | 71 | 218 | 71 | 73 | 570afca46a502474938fd16c0fdf814ee15d4301 | bigcode/the-stack | train |
c6523b4d9a4f9878940bb56d | train | class | class OAuthAddonAuthViewsTestCaseMixin(OAuthAddonTestCaseMixin):
@property
def Provider(self):
raise NotImplementedError()
def test_oauth_start(self):
url = api_url_for(
'oauth_connect',
service_name=self.ADDON_SHORT_NAME
)
res = self.app.get(url, au... | class OAuthAddonAuthViewsTestCaseMixin(OAuthAddonTestCaseMixin):
@property
| def Provider(self):
raise NotImplementedError()
def test_oauth_start(self):
url = api_url_for(
'oauth_connect',
service_name=self.ADDON_SHORT_NAME
)
res = self.app.get(url, auth=self.user.auth)
assert_equal(res.status_code, http.FOUND)
red... | # -*- coding: utf-8 -*-
import httplib as http
import urlparse
import mock
from nose.tools import * # noqa (PEP8 asserts)
from framework.auth import Auth
from website.addons.base.testing.base import OAuthAddonTestCaseMixin
from website.util import api_url_for, web_url_for, permissions
from tests.factories import A... | 100 | 133 | 444 | 19 | 80 | sf2ne/Playground | website/addons/base/testing/views.py | Python | OAuthAddonAuthViewsTestCaseMixin | OAuthAddonAuthViewsTestCaseMixin | 16 | 69 | 16 | 18 | 750b72abfb3f4ac787c3a7241c6ac23268dd5f6a | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.