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
75f34dfd7bba9302f0bd2d45
train
class
class HistoryDialog(QDialog, history_settings.Ui_Dialog): def __init__(self, pump, parent = None): super(HistoryDialog, self).__init__(parent) self.setupUi(self) self.pump = pump self.__appname__ = "Command History" self.setWindowTitle(self.__appname__) self.connec...
class HistoryDialog(QDialog, history_settings.Ui_Dialog):
def __init__(self, pump, parent = None): super(HistoryDialog, self).__init__(parent) self.setupUi(self) self.pump = pump self.__appname__ = "Command History" self.setWindowTitle(self.__appname__) self.connect(self.refresh_Btn,\ SIGNAL("clicked()"),\...
self.Start_Velocity_Edit_2.text()), ('slope', self.SlopeEdit.text()) ] for pair in pairs: if pair[1].isdigit(): print("Pair[1] {}".format(pair[1])) self.pump.property_set(*pair) class HistoryDialog(QDialog, history_settings.Ui...
72
72
242
12
60
ezirayw/Pump3000
for_keep/final_code/classes_used.py
Python
HistoryDialog
HistoryDialog
43
78
43
43
4120d7866e4e20257ddc94b7f382df3fd572415a
bigcode/the-stack
train
495650454a9c041aa2ac9de0
train
class
class NewDevDialog(QDialog, device_configuration.Ui_Dialog): def __init__(self, pump, parent=None): super(NewDevDialog, self).__init__(parent) self.setupUi(self) self.__appname__ = "Device Configuration" self.setWindowTitle(self.__appname__) self.comports = comports ...
class NewDevDialog(QDialog, device_configuration.Ui_Dialog):
def __init__(self, pump, parent=None): super(NewDevDialog, self).__init__(parent) self.setupUi(self) self.__appname__ = "Device Configuration" self.setWindowTitle(self.__appname__) self.comports = comports self.pump = pump ports_available = list(self.compor...
.scene.setForegroundBrush(\ QBrush(Qt.lightGray, Qt.CrossPattern)) else: self.window.refresh_status = True self.window.refreshQtimer.start() self.window.scene.setForegroundBrush(\ Qt.NoBrush) class NewDevDialog(QDialog, devi...
64
64
164
13
51
ezirayw/Pump3000
for_keep/final_code/classes_used.py
Python
NewDevDialog
NewDevDialog
163
182
163
164
41177e0cd2df3f7f8c4008ca808f57a0e4a990df
bigcode/the-stack
train
135a63396ec22321227e177a
train
class
class ParametersChange(QDialog, parameters_change.Ui_Dialog): def __init__(self, pump, parent = None): super(ParametersChange, self).__init__(parent) self.setupUi(self) self.pump = pump def update_pump_param(self): pairs = [('top_velocity', self.Top_Velocity_Edit_2.text()), ...
class ParametersChange(QDialog, parameters_change.Ui_Dialog):
def __init__(self, pump, parent = None): super(ParametersChange, self).__init__(parent) self.setupUi(self) self.pump = pump def update_pump_param(self): pairs = [('top_velocity', self.Top_Velocity_Edit_2.text()), ('cutoff_velocity', self.Cutoff_Velocity_Edit_2.te...
* # Module imports import sys import os from serial.tools.list_ports import comports # Qt-Designer compiled python code import python_gui import python_settings import history_settings import device_configuration import parameters_change import about_dialog class ParametersChange(QDialog, parameters_change.Ui_Dialog...
64
64
174
12
51
ezirayw/Pump3000
for_keep/final_code/classes_used.py
Python
ParametersChange
ParametersChange
24
41
24
24
985a3bd63ebf681a81a1dd81c6a6bfecec4ed995
bigcode/the-stack
train
22a9066bb1d9a5fd9b3465c7
train
class
class SyringePickDialog(QDialog, device_configuration.Ui_Dialog): def __init__(self, pump, parent=None): super(SyringePickDialog, self).__init__(parent) self.setupUi(self) self.__appname__ = "Syringe Configuration" self.setWindowTitle(self.__appname__) self.pump = pump ...
class SyringePickDialog(QDialog, device_configuration.Ui_Dialog):
def __init__(self, pump, parent=None): super(SyringePickDialog, self).__init__(parent) self.setupUi(self) self.__appname__ = "Syringe Configuration" self.setWindowTitle(self.__appname__) self.pump = pump syringe_sizes = ['50 micro', '100 micro', '250 micro', '500 mi...
Item(ports_available[i][0]) def connect_with_port(self): """Passes the selected item into the connect_new method of the pump.""" port = self.listWidget.currentItem().text() self.pump.connect_new(port) class SyringePickDialog(QDialog, device_configuration.Ui_Dialog):
64
64
205
14
50
ezirayw/Pump3000
for_keep/final_code/classes_used.py
Python
SyringePickDialog
SyringePickDialog
184
204
184
185
ebb5cbecac31c5407c6e74413aa55ee8de54cd50
bigcode/the-stack
train
76b2bb6be7dcfe6c0e33006a
train
class
class AboutDialog(QDialog, about_dialog.Ui_Form): def __init__(self, text, appname, parent = None): super(AboutDialog, self).__init__(parent) self.setupUi(self) self.__appname__ = appname self.setWindowTitle(self.__appname__) self.text = text self.load_text() d...
class AboutDialog(QDialog, about_dialog.Ui_Form):
def __init__(self, text, appname, parent = None): super(AboutDialog, self).__init__(parent) self.setupUi(self) self.__appname__ = appname self.setWindowTitle(self.__appname__) self.text = text self.load_text() def load_text(self): self.textBrowser.setTex...
of the pump.""" syringe = self.listWidget.currentItem().text().split()[0] self.pump.syringe_size = syringe print("syringe is set to {size}".format(size = self.pump.syringe_size)) class AboutDialog(QDialog, about_dialog.Ui_Form):
64
64
91
11
53
ezirayw/Pump3000
for_keep/final_code/classes_used.py
Python
AboutDialog
AboutDialog
206
218
206
207
77dfc7190de52943689424f1cf82f4abe285e97e
bigcode/the-stack
train
70fd08a558241e17e49e6aec
train
class
class ReportsDialog(QDialog, python_settings.Ui_Dialog): def __init__(self, pump, window, parent=None): super(ReportsDialog, self).__init__(parent) self.setupUi(self) self.__appname__ = "Reports Screen" self.setWindowTitle(self.__appname__) self.pump = pump self.wi...
class ReportsDialog(QDialog, python_settings.Ui_Dialog):
def __init__(self, pump, window, parent=None): super(ReportsDialog, self).__init__(parent) self.setupUi(self) self.__appname__ = "Reports Screen" self.setWindowTitle(self.__appname__) self.pump = pump self.window = window self.connect(self.refresh_interval_...
name__) self.connect(self.refresh_Btn,\ SIGNAL("clicked()"),\ self.refresh) self.connect(self.commands_only,\ SIGNAL("clicked()"),\ self.refresh) self.connect(self.clear_history_btn,\ SIGNAL("clicked()"),\ ...
184
184
616
12
172
ezirayw/Pump3000
for_keep/final_code/classes_used.py
Python
ReportsDialog
ReportsDialog
80
160
80
81
068c9be386adc378904fa0bbf161fa52e3b5b5e3
bigcode/the-stack
train
3d2383a5fefe84a066cbd2fc
train
class
class AboutDialog2(QDialog, about_dialog.Ui_Form): def __init__(self, text, appname, parent = None): super(AboutDialog2, self).__init__(parent) self.setupUi(self) self.__appname__ = appname self.setWindowTitle(self.__appname__) self.text = text self.load_text() ...
class AboutDialog2(QDialog, about_dialog.Ui_Form):
def __init__(self, text, appname, parent = None): super(AboutDialog2, self).__init__(parent) self.setupUi(self) self.__appname__ = appname self.setWindowTitle(self.__appname__) self.text = text self.load_text() self.QtButton = QPushButton("About Qt") ...
self.setupUi(self) self.__appname__ = appname self.setWindowTitle(self.__appname__) self.text = text self.load_text() def load_text(self): self.textBrowser.setText(self.text) class AboutDialog2(QDialog, about_dialog.Ui_Form):
64
64
155
12
52
ezirayw/Pump3000
for_keep/final_code/classes_used.py
Python
AboutDialog2
AboutDialog2
220
240
220
221
93a10d9b85209b96a2923cfbeda24f0c69775ac5
bigcode/the-stack
train
ba8aef35169d14332d8de1ea
train
function
@click.command() @click.option('--seed', default=42) @click.option('--num_steps', default=1e7) @click.option('--steps_per_epoch', default=30000) @click.option('--save_freq', default=50) @click.option('--target_kl', default=0.01) @click.option('--cost_lim', default=25) @click.option('--cpu', default=1) @click.option('--...
@click.command() @click.option('--seed', default=42) @click.option('--num_steps', default=1e7) @click.option('--steps_per_epoch', default=30000) @click.option('--save_freq', default=50) @click.option('--target_kl', default=0.01) @click.option('--cost_lim', default=25) @click.option('--cpu', default=1) @click.option('--...
mpi_fork(cpu) epochs = int(num_steps / steps_per_epoch) logger_kwargs = setup_logger_kwargs(exp_name, seed) env = HW3D() ppo_lagrangian( env_fn = lambda : HW3DWrapper(env), ac_kwargs = dict(hidden_sizes=(256,256)), epochs = epochs, steps_per_epoch = steps_per_epoch, save_freq=save_freq, target_kl=ta...
@click.command() @click.option('--seed', default=42) @click.option('--num_steps', default=1e7) @click.option('--steps_per_epoch', default=30000) @click.option('--save_freq', default=50) @click.option('--target_kl', default=0.01) @click.option('--cost_lim', default=25) @click.option('--cpu', default=1) @click.option('--...
127
76
254
127
0
michahu/safety-starter-agents
experiments/ppol_hw3d.py
Python
ppo_lagrangian_hw3d
ppo_lagrangian_hw3d
16
45
16
27
dae0dd3c9aacb5cada82b4512853bd2b74587934
bigcode/the-stack
train
008ae3d56ef2fc32137726a3
train
function
def CheckFeatures(lyr, field1='foo5', field2='bar10', field3='baz15', field4='baw20'): expected_values = [ ['foo0', None, None, None], ['foo1', 'bar1', None, None], ['foo2', 'bar2_01234', 'baz2_0123456789', None], ['foo3', 'bar3_01234', 'baz3_0123456789', 'baw3_012345678901234'] ...
def CheckFeatures(lyr, field1='foo5', field2='bar10', field3='baz15', field4='baw20'):
expected_values = [ ['foo0', None, None, None], ['foo1', 'bar1', None, None], ['foo2', 'bar2_01234', 'baz2_0123456789', None], ['foo3', 'bar3_01234', 'baz3_0123456789', 'baw3_012345678901234'] ] lyr_defn = lyr.GetLayerDefn() lyr.ResetReading() feat = lyr.GetNextFeat...
=unused-argument # if val is None: # return val # return val[0:lyr_defn.GetFieldDefn(lyr_defn.GetFieldIndex(fieldname)).GetWidth()] # Mem driver doesn't actually truncate return val def CheckFeatures(lyr, field1='foo5', field2='bar10', field3='baz15', field4='baw20'):
92
92
309
33
58
ajolma/gdal
autotest/ogr/ogr_rfc35_mem.py
Python
CheckFeatures
CheckFeatures
98
120
98
99
90a107c8a14bf0440697e09f4d686f657b14536a
bigcode/the-stack
train
3106d227ddae22ac89979673
train
function
def test_ogr_rfc35_mem_2(): lyr = gdaltest.rfc35_mem_ds.GetLayer(0) assert lyr.TestCapability(ogr.OLCReorderFields) == 1 feat = ogr.Feature(lyr.GetLayerDefn()) feat.SetField(0, 'foo3') feat.SetField(1, 'bar3_01234') feat.SetField(2, 'baz3_0123456789') feat.SetField(3, 'baw3_01234567890123...
def test_ogr_rfc35_mem_2():
lyr = gdaltest.rfc35_mem_ds.GetLayer(0) assert lyr.TestCapability(ogr.OLCReorderFields) == 1 feat = ogr.Feature(lyr.GetLayerDefn()) feat.SetField(0, 'foo3') feat.SetField(1, 'bar3_01234') feat.SetField(2, 'baz3_0123456789') feat.SetField(3, 'baw3_012345678901234') lyr.CreateFeature(fea...
4 is not None and feat.GetField(field4) != Truncate(expected_values[i][3], lyr_defn, field4)): feat.DumpReadable() pytest.fail() feat = lyr.GetNextFeature() i = i + 1 def CheckColumnOrder(lyr, expected_order): lyr_defn = lyr.GetLayerDefn() for i, exp_order in enum...
144
144
480
11
133
ajolma/gdal
autotest/ogr/ogr_rfc35_mem.py
Python
test_ogr_rfc35_mem_2
test_ogr_rfc35_mem_2
139
180
139
140
f144c9d3d52ed21d861d81aadae5879d0d24ed16
bigcode/the-stack
train
854869fb703a15714a613e62
train
function
def test_ogr_rfc35_mem_1(): gdaltest.rfc35_mem_ds = ogr.GetDriverByName('Memory').CreateDataSource('rfc35_test') lyr = gdaltest.rfc35_mem_ds.CreateLayer('rfc35_test') lyr.ReorderFields([]) fd = ogr.FieldDefn('foo5', ogr.OFTString) fd.SetWidth(5) lyr.CreateField(fd) feat = ogr.Feature(lyr...
def test_ogr_rfc35_mem_1():
gdaltest.rfc35_mem_ds = ogr.GetDriverByName('Memory').CreateDataSource('rfc35_test') lyr = gdaltest.rfc35_mem_ds.CreateLayer('rfc35_test') lyr.ReorderFields([]) fd = ogr.FieldDefn('foo5', ogr.OFTString) fd.SetWidth(5) lyr.CreateField(fd) feat = ogr.Feature(lyr.GetLayerDefn()) feat.Set...
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. #######################################################################...
99
99
330
11
87
ajolma/gdal
autotest/ogr/ogr_rfc35_mem.py
Python
test_ogr_rfc35_mem_1
test_ogr_rfc35_mem_1
42
81
42
43
1054841d2b4271b99915f6d9f66a9b5ca77c3662
bigcode/the-stack
train
0c9c82b55635de0449808eb0
train
function
def Check(lyr, expected_order): CheckColumnOrder(lyr, expected_order) CheckFeatures(lyr)
def Check(lyr, expected_order):
CheckColumnOrder(lyr, expected_order) CheckFeatures(lyr)
1 def CheckColumnOrder(lyr, expected_order): lyr_defn = lyr.GetLayerDefn() for i, exp_order in enumerate(expected_order): assert lyr_defn.GetFieldDefn(i).GetName() == exp_order def Check(lyr, expected_order):
63
64
27
9
53
ajolma/gdal
autotest/ogr/ogr_rfc35_mem.py
Python
Check
Check
132
136
132
133
348f98e45b07f6a82681e86a2cf0ffbbd7ea9666
bigcode/the-stack
train
b0f948a42e9dcdbb99799f45
train
function
def test_ogr_rfc35_mem_4(): lyr = gdaltest.rfc35_mem_ds.GetLayer(0) lyr_defn = lyr.GetLayerDefn() assert lyr.TestCapability(ogr.OLCAlterFieldDefn) == 1 fd = ogr.FieldDefn("intfield", ogr.OFTInteger) lyr.CreateField(fd) lyr.ReorderField(lyr_defn.GetFieldIndex("intfield"), 0) lyr.ResetRea...
def test_ogr_rfc35_mem_4():
lyr = gdaltest.rfc35_mem_ds.GetLayer(0) lyr_defn = lyr.GetLayerDefn() assert lyr.TestCapability(ogr.OLCAlterFieldDefn) == 1 fd = ogr.FieldDefn("intfield", ogr.OFTInteger) lyr.CreateField(fd) lyr.ReorderField(lyr_defn.GetFieldIndex("intfield"), 0) lyr.ResetReading() feat = lyr.GetNext...
ErrorHandler() assert ret != 0 lyr.AlterFieldDefn(lyr_defn.GetFieldIndex("baz15"), fd, ogr.ALTER_ALL_FLAG) ret = CheckFeatures(lyr, field3='baz25') fd = ogr.FieldDefn("baz5", ogr.OFTString) fd.SetWidth(5) lyr_defn = lyr.GetLayerDefn() lyr.AlterFieldDefn(lyr_defn.GetFieldIndex("baz25"), f...
213
213
711
11
201
ajolma/gdal
autotest/ogr/ogr_rfc35_mem.py
Python
test_ogr_rfc35_mem_4
test_ogr_rfc35_mem_4
227
311
227
228
f58be8181f41f74f54e25d9cab3565823a4e43da
bigcode/the-stack
train
ee4c0f35f64434818c430110
train
function
def Truncate(val, lyr_defn, fieldname): # pylint: disable=unused-argument # if val is None: # return val # return val[0:lyr_defn.GetFieldDefn(lyr_defn.GetFieldIndex(fieldname)).GetWidth()] # Mem driver doesn't actually truncate return val
def Truncate(val, lyr_defn, fieldname): # pylint: disable=unused-argument # if val is None: # return val # return val[0:lyr_defn.GetFieldDefn(lyr_defn.GetFieldIndex(fieldname)).GetWidth()] # Mem driver doesn't actually truncate
return val
def Truncate(val, lyr_defn, fieldname): # pylint: disable=unused-argument # if val is None: # return val # return val[0:lyr_defn.GetFieldDefn(lyr_defn.GetFieldIndex(fieldname)).GetWidth()] # Mem driver doesn't actually truncate
72
64
76
72
0
ajolma/gdal
autotest/ogr/ogr_rfc35_mem.py
Python
Truncate
Truncate
87
95
87
94
ad74f0dbdf36e79d746997cfc995bef385d118e1
bigcode/the-stack
train
55df50be5445940e1f1147d8
train
function
def test_ogr_rfc35_mem_cleanup(): gdaltest.rfc35_mem_ds = None
def test_ogr_rfc35_mem_cleanup():
gdaltest.rfc35_mem_ds = None
assert lyr.DeleteField(lyr_defn.GetFieldIndex('bar10')) == 0 ret = CheckFeatures(lyr, field1=None, field2=None, field3=None, field4=None) ############################################################################### # Initiate the test file def test_ogr_rfc35_mem_cleanup():
64
64
22
10
53
ajolma/gdal
autotest/ogr/ogr_rfc35_mem.py
Python
test_ogr_rfc35_mem_cleanup
test_ogr_rfc35_mem_cleanup
356
358
356
357
d064e36b0f2fad0253d4275a32ba796de6faa344
bigcode/the-stack
train
e70471eaa3f4e22eab04c160
train
function
def CheckColumnOrder(lyr, expected_order): lyr_defn = lyr.GetLayerDefn() for i, exp_order in enumerate(expected_order): assert lyr_defn.GetFieldDefn(i).GetName() == exp_order
def CheckColumnOrder(lyr, expected_order):
lyr_defn = lyr.GetLayerDefn() for i, exp_order in enumerate(expected_order): assert lyr_defn.GetFieldDefn(i).GetName() == exp_order
is not None and feat.GetField(field4) != Truncate(expected_values[i][3], lyr_defn, field4)): feat.DumpReadable() pytest.fail() feat = lyr.GetNextFeature() i = i + 1 def CheckColumnOrder(lyr, expected_order):
63
64
51
11
51
ajolma/gdal
autotest/ogr/ogr_rfc35_mem.py
Python
CheckColumnOrder
CheckColumnOrder
124
128
124
125
24e9b712534e627c13577d1ec5964f235506cd12
bigcode/the-stack
train
d41837cf26c88a71dea6c8fc
train
function
def test_ogr_rfc35_mem_3(): lyr = gdaltest.rfc35_mem_ds.GetLayer(0) fd = ogr.FieldDefn("baz25", ogr.OFTString) fd.SetWidth(25) lyr_defn = lyr.GetLayerDefn() gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.AlterFieldDefn(-1, fd, ogr.ALTER_ALL_FLAG) gdal.PopErrorHandler() asser...
def test_ogr_rfc35_mem_3():
lyr = gdaltest.rfc35_mem_ds.GetLayer(0) fd = ogr.FieldDefn("baz25", ogr.OFTString) fd.SetWidth(25) lyr_defn = lyr.GetLayerDefn() gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.AlterFieldDefn(-1, fd, ogr.ALTER_ALL_FLAG) gdal.PopErrorHandler() assert ret != 0 gdal.PushErro...
0]) ret = Check(lyr, ['foo5', 'bar10', 'baz15', 'baw20']) gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.ReorderFields([0, 0, 0, 0]) gdal.PopErrorHandler() assert ret != 0 ############################################################################### # Test AlterFieldDefn() for change o...
101
101
337
11
89
ajolma/gdal
autotest/ogr/ogr_rfc35_mem.py
Python
test_ogr_rfc35_mem_3
test_ogr_rfc35_mem_3
186
221
186
187
885c07146f3ba57773f7bc02f337159b74557b7f
bigcode/the-stack
train
e58ef690b0ac120c08a375e2
train
function
def test_ogr_rfc35_mem_5(): lyr = gdaltest.rfc35_mem_ds.GetLayer(0) lyr_defn = lyr.GetLayerDefn() assert lyr.TestCapability(ogr.OLCDeleteField) == 1 gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.DeleteField(-1) gdal.PopErrorHandler() assert ret != 0 gdal.PushErrorHandler('C...
def test_ogr_rfc35_mem_5():
lyr = gdaltest.rfc35_mem_ds.GetLayer(0) lyr_defn = lyr.GetLayerDefn() assert lyr.TestCapability(ogr.OLCDeleteField) == 1 gdal.PushErrorHandler('CPLQuietErrorHandler') ret = lyr.DeleteField(-1) gdal.PopErrorHandler() assert ret != 0 gdal.PushErrorHandler('CPLQuietErrorHandler') ret...
6) lyr.AlterFieldDefn(lyr_defn.GetFieldIndex("intfield"), fd, ogr.ALTER_ALL_FLAG) lyr.ResetReading() feat = lyr.GetNextFeature() assert feat.GetField("oldintfld") == '98765' feat = None CheckFeatures(lyr, field3='baz5') #########################################################################...
92
92
309
11
81
ajolma/gdal
autotest/ogr/ogr_rfc35_mem.py
Python
test_ogr_rfc35_mem_5
test_ogr_rfc35_mem_5
317
350
317
318
b7aa84994f8338dc25bfeacf4ec4abdc1ceed22d
bigcode/the-stack
train
b2929389e31da11ef63e4097
train
function
def test_stat(mail_server: MailServer): stat = mail_server.stat() assert isinstance(stat, tuple) assert isinstance(stat[0], int) assert isinstance(stat[1], int)
def test_stat(mail_server: MailServer):
stat = mail_server.stat() assert isinstance(stat, tuple) assert isinstance(stat[0], int) assert isinstance(stat[1], int)
config.copy() config_with_error_timeout.update(timeout=NotImplemented) MailServer(**config_with_error_timeout) def test_smtp_able_and_pop_able(mail_server: MailServer): assert mail_server.smtp_able() assert mail_server.pop_able() def test_stat(mail_server: MailServer):
64
64
41
9
55
wsgfz/zmail
tests/test_server.py
Python
test_stat
test_stat
77
82
77
77
456af30ee81b6eec6c2e1d944ab1176da305827a
bigcode/the-stack
train
f31f125e7470c227e0c24865
train
function
def test_send_and_get(mail_server: MailServer, here): datetime_stamp = str(datetime.datetime.now()) mail_as_dict = { 'subject': '新测试邮件test! ' + datetime_stamp, 'content_text': ['测试内容1_1\r\n', '测试内容1_2'], 'content_html': '<html> \n<body>\n <h1>标题</h1>\n</body>', 'from': 'ZMAIL测试',...
def test_send_and_get(mail_server: MailServer, here):
datetime_stamp = str(datetime.datetime.now()) mail_as_dict = { 'subject': '新测试邮件test! ' + datetime_stamp, 'content_text': ['测试内容1_1\r\n', '测试内容1_2'], 'content_html': '<html> \n<body>\n <h1>标题</h1>\n</body>', 'from': 'ZMAIL测试', 'to': 'ZMAIL测试', 'attachments': [os.p...
= config.copy() mock_logger = logging.Logger('mock') config_defined.update(timeout=30, debug=True, log=mock_logger, auto_add_from=False, auto_add_to=False) server_defined = MailServer(**config_defined) assert server_defined.timeout == 30 assert server_defined.debug is True...
256
256
5,200
13
243
wsgfz/zmail
tests/test_server.py
Python
test_send_and_get
test_send_and_get
85
149
85
85
62e9262b779cd9d617d5cbffd2ef2d1e6730ea87
bigcode/the-stack
train
2750ba2083329a798657882c
train
function
def test_initiate_server(mail_server_config): config = mail_server_config server = MailServer(**config) for k, v in config.items(): assert getattr(server, k) is v assert isinstance(server.smtp_server, SMTPServer) assert isinstance(server.pop_server, POPServer) assert server.log is logge...
def test_initiate_server(mail_server_config):
config = mail_server_config server = MailServer(**config) for k, v in config.items(): assert getattr(server, k) is v assert isinstance(server.smtp_server, SMTPServer) assert isinstance(server.pop_server, POPServer) assert server.log is logger # Test user-defined arguments. conf...
= {k: v for k, v in auto_generate_config.items() if 'imap' not in k} auto_generate_config.update(username=username, password=password) return auto_generate_config @pytest.fixture def mail_server(mail_server_config: dict) -> MailServer: return MailServer(**mail_server_config) def test_initiate_server(ma...
75
75
251
10
65
wsgfz/zmail
tests/test_server.py
Python
test_initiate_server
test_initiate_server
39
69
39
39
e610935b130378a23e684f04fbe968d379a3bfe9
bigcode/the-stack
train
73cb0c7e8255a3b298cc92c9
train
function
def test_smtp_able_and_pop_able(mail_server: MailServer): assert mail_server.smtp_able() assert mail_server.pop_able()
def test_smtp_able_and_pop_able(mail_server: MailServer):
assert mail_server.smtp_able() assert mail_server.pop_able()
Implemented) MailServer(**config_with_error_logger) with pytest.raises(InvalidArguments): config_with_error_timeout = config.copy() config_with_error_timeout.update(timeout=NotImplemented) MailServer(**config_with_error_timeout) def test_smtp_able_and_pop_able(mail_server: MailServe...
64
64
32
16
48
wsgfz/zmail
tests/test_server.py
Python
test_smtp_able_and_pop_able
test_smtp_able_and_pop_able
72
74
72
72
471c74e6ce8ca19cb46ab3fed34f5f38b867111a
bigcode/the-stack
train
fb8a8f63defb8f39efbe61e1
train
function
def test_send_cc(mail_server: MailServer): mail_as_dict = { 'subject': 'test_cc', 'content_text': ['测试内容1_1\r\n', '测试内容1_2'], } now_latest_num = mail_server.stat()[0] mail_server.send_mail(mail_server.username, mail_as_dict, cc=mail_server.username) t = 0 while True: if ...
def test_send_cc(mail_server: MailServer):
mail_as_dict = { 'subject': 'test_cc', 'content_text': ['测试内容1_1\r\n', '测试内容1_2'], } now_latest_num = mail_server.stat()[0] mail_server.send_mail(mail_server.username, mail_as_dict, cc=mail_server.username) t = 0 while True: if now_latest_num < mail_server.stat()[0]: ...
_time=b'test', end_time=b'test') # Test delete() assert mail_server.delete(mail_receive['id']) assert mail_server.stat()[0] < mail_receive['id'] or mail_server.get_mail(mail_receive['id']) != mail_receive def test_send_cc(mail_server: MailServer):
64
64
207
10
53
wsgfz/zmail
tests/test_server.py
Python
test_send_cc
test_send_cc
152
175
152
152
3b1e79450af970c237096c9197e22865b69373fc
bigcode/the-stack
train
cfeb129bf35cf489c4d3793d
train
function
@pytest.fixture def mail_server(mail_server_config: dict) -> MailServer: return MailServer(**mail_server_config)
@pytest.fixture def mail_server(mail_server_config: dict) -> MailServer:
return MailServer(**mail_server_config)
IMAP config. auto_generate_config = {k: v for k, v in auto_generate_config.items() if 'imap' not in k} auto_generate_config.update(username=username, password=password) return auto_generate_config @pytest.fixture def mail_server(mail_server_config: dict) -> MailServer:
64
64
25
16
47
wsgfz/zmail
tests/test_server.py
Python
mail_server
mail_server
34
36
34
35
4ce357059f17cae3cba2a8d1deb04de27a3023c7
bigcode/the-stack
train
29d63f2eda9d4149a7f9012b
train
function
def test_all_account_smtp_and_pop_able(accounts): if not accounts: pytest.skip('Can not get accounts') for account in accounts: username = account[0] password = account[1] auto_generate_config = get_supported_server_info(username) # Ignore IMAP config. auto_gen...
def test_all_account_smtp_and_pop_able(accounts):
if not accounts: pytest.skip('Can not get accounts') for account in accounts: username = account[0] password = account[1] auto_generate_config = get_supported_server_info(username) # Ignore IMAP config. auto_generate_config = {k: v for k, v in auto_generate_con...
content_html', 'attachments'): assert mail_receive[k] == mail_receive_next[k], k # TODO:Add 'to' # Delete these mails. mail_server.delete(mail_receive_next['id']) mail_server.delete(mail_receive['id']) def test_all_account_smtp_and_pop_able(accounts):
63
64
126
12
51
wsgfz/zmail
tests/test_server.py
Python
test_all_account_smtp_and_pop_able
test_all_account_smtp_and_pop_able
218
236
218
218
57075e441d776c0c1e9e35865181fb29ae586555
bigcode/the-stack
train
cba727ae7e97065b1000777f
train
function
@pytest.fixture def mail_server_config(accounts) -> dict: if not accounts: pytest.skip('Can not get accounts') account = accounts[0] username = account[0] password = account[1] auto_generate_config = get_supported_server_info(username) # Ignore IMAP config. auto_generate_config = ...
@pytest.fixture def mail_server_config(accounts) -> dict:
if not accounts: pytest.skip('Can not get accounts') account = accounts[0] username = account[0] password = account[1] auto_generate_config = get_supported_server_info(username) # Ignore IMAP config. auto_generate_config = {k: v for k, v in auto_generate_config.items() if 'imap' n...
logging import os import time import pytest from zmail.exceptions import InvalidArguments from zmail.info import get_supported_server_info from zmail.server import MailServer, POPServer, SMTPServer logger = logging.getLogger('zmail') @pytest.fixture def mail_server_config(accounts) -> dict:
64
64
109
12
52
wsgfz/zmail
tests/test_server.py
Python
mail_server_config
mail_server_config
15
31
15
16
1d3fff1632531930961f01e45eff598a58d8881d
bigcode/the-stack
train
1d03b8cbe130bd0f60eacc18
train
function
def test_resend(mail_server: MailServer, here): mail_as_dict = {'subject': str(datetime.datetime.now()), 'attachments': os.path.join(here, 'favicon.ico'), 'content_text': ['111', '222'], 'content_html': ['222', '333']} # Send first mail. now_latest...
def test_resend(mail_server: MailServer, here):
mail_as_dict = {'subject': str(datetime.datetime.now()), 'attachments': os.path.join(here, 'favicon.ico'), 'content_text': ['111', '222'], 'content_html': ['222', '333']} # Send first mail. now_latest_num = mail_server.stat()[0] mail_server.sen...
break else: t += 1 if t == 120: raise TimeoutError('Test timeout({}s).'.format(t * 0.5)) time.sleep(0.5) for k in mail_as_dict: assert mail_receive[k] == mail_receive[k] assert mail_receive['headers']['Cc'] == '<{}>'.format(mail_s...
105
106
355
12
93
wsgfz/zmail
tests/test_server.py
Python
test_resend
test_resend
178
215
178
178
bcc6acfbc7a17172f91e1b98867eda82a635b544
bigcode/the-stack
train
33801d7279943a0685780e83
train
class
class Migration(migrations.Migration): initial = True dependencies = [ ('wagtailcore', '0062_comment_models_and_pagesubscription'), ] operations = [ migrations.CreateModel( name='BasePage', fields=[ ('page_ptr', models.OneToOneField(auto_created...
class Migration(migrations.Migration):
initial = True dependencies = [ ('wagtailcore', '0062_comment_models_and_pagesubscription'), ] operations = [ migrations.CreateModel( name='BasePage', fields=[ ('page_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deleti...
# Generated by Django 3.1.12 on 2021-07-22 12:05 from django.db import migrations, models import django.db.models.deletion import wagtail.core.blocks import wagtail.core.blocks.field_block import wagtail.core.fields import wagtail.images.blocks import wagtailnhsukfrontend.blocks class Migration(migrations.Migration): ...
80
256
11,573
7
72
dragon-dxw/nhs-ei.website
cms/pages/migrations/0001_initial.py
Python
Migration
Migration
12
119
12
13
3686c6bc4cf52bd68316b1905efe0e3a65af9328
bigcode/the-stack
train
82c372780715f8cf9a046b7b
train
function
def test_net(): device = "cuda" if torch.cuda.is_available() else "cpu" x = torch.randn(64, 1, 32, 32).to(device) model = LeNet(num_classes=10).to(device) return model(x)
def test_net():
device = "cuda" if torch.cuda.is_available() else "cpu" x = torch.randn(64, 1, 32, 32).to(device) model = LeNet(num_classes=10).to(device) return model(x)
= self.pool(x) x = self.conv3(x) x = self.relu(x) x = x.reshape(x.shape[0], -1) x = self.linear1(x) x = self.relu(x) x = self.linear2(x) return x def test_net():
64
64
54
4
59
rohitkuk/EmotionDetection
LeNet.py
Python
test_net
test_net
66
70
66
66
941557fe8d66474c7a58a00724279b2ae013ba8b
bigcode/the-stack
train
0b0806693b4dd5136f81354c
train
class
class LeNet(nn.Module): def __init__(self, num_classes): super(LeNet, self).__init__() self.relu = nn.ReLU() self.pool = nn.AvgPool2d(kernel_size = (2,2), stride = (2,2)) self.conv1 = nn.Conv2d( in_channels = 1, out_channels = 6, kernel_size = (5,5), stride = (1,1), ...
class LeNet(nn.Module):
def __init__(self, num_classes): super(LeNet, self).__init__() self.relu = nn.ReLU() self.pool = nn.AvgPool2d(kernel_size = (2,2), stride = (2,2)) self.conv1 = nn.Conv2d( in_channels = 1, out_channels = 6, kernel_size = (5,5), stride = (1,1), padding = (0,0)...
""" An Implementation of the LeNet Architecture by Yann lecun in referance to Video explanation: https://youtu.be/fcOW-Zyb5Bo. PaperLink : http://yann.lecun.com/exdb/publis/pdf/lecun-98.pdf @Author: Rohit Kukreja @Email : rohit.kukreja01@gmail.com """ import torch import torch.nn as nn class LeNet(nn.Module):
92
111
370
6
85
rohitkuk/EmotionDetection
LeNet.py
Python
LeNet
LeNet
16
63
16
16
a1997f5aacd06fe5071c21eecad6b3e8f63082f5
bigcode/the-stack
train
769d58ae19f5140932f6ce93
train
function
@auth.route("/logout") @login_required def logout(): logout_user() return redirect(url_for("auth.login"))
@auth.route("/logout") @login_required def logout():
logout_user() return redirect(url_for("auth.login"))
return redirect(url_for("views.home")) else: flash("Incorrect password, try again!", category="error") else: flash("Email does not exist!", category="error") return render_template("login.html", user=current_user) @auth.route("/logout") @login_required...
64
64
25
12
52
ceyeoh/fyp_doppler
website/auth.py
Python
logout
logout
65
69
65
67
0722dc75cb11bd8baaa8678bbbe517e601b697af
bigcode/the-stack
train
c34b43d51a9fd89c14e56dee
train
function
@auth.route("/signup", methods=["GET", "POST"]) def signup(): if request.method == "POST": firstname = request.form.get("firstname") email = request.form.get("email") password0 = request.form.get("password0") password1 = request.form.get("password1") user = User.query.filter_...
@auth.route("/signup", methods=["GET", "POST"]) def signup():
if request.method == "POST": firstname = request.form.get("firstname") email = request.form.get("email") password0 = request.form.get("password0") password1 = request.form.get("password1") user = User.query.filter_by(email=email).first() if user: flash("Us...
, request, flash, redirect, url_for from werkzeug.security import generate_password_hash, check_password_hash from . import db from .database import User from flask_login import login_user, login_required, current_user, logout_user auth = Blueprint( "auth", __name__, ) @auth.route("/signup", methods=["GET", "...
79
79
266
16
63
ceyeoh/fyp_doppler
website/auth.py
Python
signup
signup
14
42
14
15
e15f09b6c104d9932b5ba676d838bcef78ea8a94
bigcode/the-stack
train
1a15132a107b1fabfa73be36
train
function
@auth.route("/", methods=["GET", "POST"]) @auth.route("/login", methods=["GET", "POST"]) def login(): if request.method == "POST": email = request.form.get("email") password = request.form.get("password") user = User.query.filter_by(email=email).first() if user: if check...
@auth.route("/", methods=["GET", "POST"]) @auth.route("/login", methods=["GET", "POST"]) def login():
if request.method == "POST": email = request.form.get("email") password = request.form.get("password") user = User.query.filter_by(email=email).first() if user: if check_password_hash(user.password, password): flash("Login successfully!", category="succes...
db.session.commit() flash("Account created successfully!", category="succcess") return redirect(url_for("auth.login")) return render_template("signup.html", user=current_user) @auth.route("/", methods=["GET", "POST"]) @auth.route("/login", methods=["GET", "POST"]) def login():
64
64
149
27
37
ceyeoh/fyp_doppler
website/auth.py
Python
login
login
45
62
45
47
417be2e64937685be56e28b782e6742aba0e0286
bigcode/the-stack
train
23db2da210a560c6cf6d31af
train
class
class Filter(Element): def configure(self): self.inp = Input(SizeT, "void*", "void*") self.out = Output(SizeT, "void*", "void*") self.other = Output("void*", "void*") def impl(self): self.run_c(r''' (size_t size, void* pkt, void* buff) = inp(); bool pass = false; udp_message* ...
class Filter(Element):
def configure(self): self.inp = Input(SizeT, "void*", "void*") self.out = Output(SizeT, "void*", "void*") self.other = Output("void*", "void*") def impl(self): self.run_c(r''' (size_t size, void* pkt, void* buff) = inp(); bool pass = false; udp_message* m = (udp_message*) pkt; ...
("send pkt: worker = %s, group_id = %s\n", param_msg->member_id, param_msg->group_id); #endif output { out(size, pkt, buff); } ''' % (self.worker_id, n_workers/2, '%d', '%d')) class Filter(Element):
63
64
177
4
59
mangpo/floem
apps/parameter_server/server.py
Python
Filter
Filter
209
234
209
210
48524857426edb2fda4913ad7f734f2e78dec5c4
bigcode/the-stack
train
2689acd4a07ac4ed23b99b28
train
class
class param_aggregate(State): group_id = Field(Int) start_id = Field(Uint(64)) n = Field(Int) bitmap = Field(Int) parameters = Field(Array(Int, buffer_size)) layout = [group_id, start_id, n, bitmap, parameters]
class param_aggregate(State):
group_id = Field(Int) start_id = Field(Uint(64)) n = Field(Int) bitmap = Field(Int) parameters = Field(Array(Int, buffer_size)) layout = [group_id, start_id, n, bitmap, parameters]
14\x05"}, // dikdik }; ''' class MyState(State): pkt_buff = Field('void*') pkt = Field('void*') parameters = Field('int*') n = Field(Int) group_id = Field(Int) define_state(param_message) class param_aggregate(State):
64
64
61
6
58
mangpo/floem
apps/parameter_server/server.py
Python
param_aggregate
param_aggregate
30
36
30
30
4ed21f20dd3cf627acc250d638d04d24710fc93b
bigcode/the-stack
train
ab8646712360aaa6c0927c1d
train
class
class param_buffer(State): groups = Field(Array(param_aggregate, n_groups+1))
class param_buffer(State):
groups = Field(Array(param_aggregate, n_groups+1))
_aggregate(State): group_id = Field(Int) start_id = Field(Uint(64)) n = Field(Int) bitmap = Field(Int) parameters = Field(Array(Int, buffer_size)) layout = [group_id, start_id, n, bitmap, parameters] class param_buffer(State):
64
64
19
5
59
mangpo/floem
apps/parameter_server/server.py
Python
param_buffer
param_buffer
38
39
38
38
cefc2ee3d4d1d8e55f11648e499d827cf49123d3
bigcode/the-stack
train
474c23a0cfe2d132e156fda9
train
class
class Aggregate(Element): buffer = Persistent(param_buffer) def configure(self): self.inp = Input("void*") self.up = Output("param_aggregate*") self.other = Output() self.buffer = param_buffer_inst def impl(self): self.run_c(r''' (void* pkt) = inp(); udp_message* ud...
class Aggregate(Element):
buffer = Persistent(param_buffer) def configure(self): self.inp = Input("void*") self.up = Output("param_aggregate*") self.other = Output() self.buffer = param_buffer_inst def impl(self): self.run_c(r''' (void* pkt) = inp(); udp_message* udp_msg = pkt; param_message...
n = Field(Int) group_id = Field(Int) define_state(param_message) class param_aggregate(State): group_id = Field(Int) start_id = Field(Uint(64)) n = Field(Int) bitmap = Field(Int) parameters = Field(Array(Int, buffer_size)) layout = [group_id, start_id, n, bitmap, parameters] class param_...
160
160
535
4
156
mangpo/floem
apps/parameter_server/server.py
Python
Aggregate
Aggregate
52
128
52
52
9bdbe3fb47456417082daa955ccc099c7e2b72e6
bigcode/the-stack
train
0ec681115977c1fcd7bd9084
train
class
class UpdateParam(Element): buffer = Persistent(param_buffer) store = Persistent(param_store) def configure(self): self.inp = Input("param_aggregate*") self.out = Output(SizeT) self.buffer = param_buffer_inst self.store = param_store_inst def impl(self): self.r...
class UpdateParam(Element):
buffer = Persistent(param_buffer) store = Persistent(param_store) def configure(self): self.inp = Input("param_aggregate*") self.out = Output(SizeT) self.buffer = param_buffer_inst self.store = param_store_inst def impl(self): self.run_c(r''' (param_aggregate* ...
sync_fetch_and_add32(&agg->parameters[i], param_msg->parameters[i]); } //assert(new_bitmap == BITMAP_FULL); if(new_bitmap == BITMAP_FULL) update = true; } if(!pass) assert(0); output switch { case update: up(agg); else: other(); } ''') class UpdateParam(Element):
78
78
260
5
73
mangpo/floem
apps/parameter_server/server.py
Python
UpdateParam
UpdateParam
131
171
131
131
ab86fa4b4c47a21588d14e2181fae1faa86aafbc
bigcode/the-stack
train
fd17e3b885cbba77fd205137
train
class
class SavePkt(Element): def configure(self): self.inp = Input(SizeT, "void *", "void *") self.out = Output("void*") def impl(self): self.run_c(r''' (size_t size, void* pkt, void* buff) = inp(); state->pkt_buff = buff; state->pkt = pkt; output { out(pkt); } ...
class SavePkt(Element):
def configure(self): self.inp = Input(SizeT, "void *", "void *") self.out = Output("void*") def impl(self): self.run_c(r''' (size_t size, void* pkt, void* buff) = inp(); state->pkt_buff = buff; state->pkt = pkt; output { out(pkt); } ''')
ipv4._proto == 17 && m->ether.type == htons(ETHERTYPE_IPv4) ) { pass = true; } output switch { case pass: out(size, pkt, buff); else: other(pkt, buff); } ''') class SavePkt(Element):
64
64
89
5
59
mangpo/floem
apps/parameter_server/server.py
Python
SavePkt
SavePkt
237
248
237
237
91f1b04bd38a7b9afee190474bc447a7816a34a7
bigcode/the-stack
train
b1424c93a80e143f13e63628
train
class
class Copy(Element): def configure(self, worker_id): self.inp = Input(SizeT, "void*", "void*") self.out = Output(SizeT, "void*", "void*") self.worker_id = worker_id def impl(self): self.run_c(r''' (size_t size, void* pkt, void* buff) = inp(); memcpy(pkt, state->pkt, sizeof(udp_m...
class Copy(Element):
def configure(self, worker_id): self.inp = Input(SizeT, "void*", "void*") self.out = Output(SizeT, "void*", "void*") self.worker_id = worker_id def impl(self): self.run_c(r''' (size_t size, void* pkt, void* buff) = inp(); memcpy(pkt, state->pkt, sizeof(udp_message) + sizeof(para...
learning_rate = 1/2^8 } // Reset aggregrate buffer memset(agg->parameters, 0, agg->n * sizeof(int)); agg->bitmap = 0; agg->group_id = 0; int size = sizeof(udp_message) + sizeof(param_message) + agg->n * sizeof(int); output { out(size); } ''') class Copy(Element):
85
85
285
4
81
mangpo/floem
apps/parameter_server/server.py
Python
Copy
Copy
174
206
174
174
7de07c39f7b296fd5fc424dcdfeeb42d698fcd40
bigcode/the-stack
train
c1ba710c6535cef683610ca2
train
class
class GetPkt(Element): def configure(self): self.inp = Input() self.out = Output('void*', 'void*') def impl(self): self.run_c(r''' void* pkt = state->pkt; void* buff = state->pkt_buff; output { out(pkt, buff); } ''')
class GetPkt(Element):
def configure(self): self.inp = Input() self.out = Output('void*', 'void*') def impl(self): self.run_c(r''' void* pkt = state->pkt; void* buff = state->pkt_buff; output { out(pkt, buff); } ''')
= Output("void*") def impl(self): self.run_c(r''' (size_t size, void* pkt, void* buff) = inp(); state->pkt_buff = buff; state->pkt = pkt; output { out(pkt); } ''') class GetPkt(Element):
64
64
72
5
59
mangpo/floem
apps/parameter_server/server.py
Python
GetPkt
GetPkt
250
260
250
250
d2e543634881d122ac1b41f3d530eb501a91015b
bigcode/the-stack
train
38dea0eb2f4e601d96b1ad20
train
class
class param_store(State): parameters = Field(Array(Int, n_params)) def init(self): self.parameters = lambda x: 'memset(%s, 0.5, N_PARAMS);' % x
class param_store(State):
parameters = Field(Array(Int, n_params)) def init(self): self.parameters = lambda x: 'memset(%s, 0.5, N_PARAMS);' % x
64)) n = Field(Int) bitmap = Field(Int) parameters = Field(Array(Int, buffer_size)) layout = [group_id, start_id, n, bitmap, parameters] class param_buffer(State): groups = Field(Array(param_aggregate, n_groups+1)) class param_store(State):
64
64
45
5
59
mangpo/floem
apps/parameter_server/server.py
Python
param_store
param_store
41
45
41
41
115c4a92413279e40b4a2bc2c5b57c045d0670a5
bigcode/the-stack
train
1bf799d4427f878c3053082c
train
class
class main(Flow): state = PerPacket(MyState) def impl(self): class nic_rx(Segment): def impl(self): from_net = net.FromNet(configure=[32]) to_net = net.ToNet(configure=["alloc",1]) net_free = net.FromNetFree() filter = Filter(...
class main(Flow):
state = PerPacket(MyState) def impl(self): class nic_rx(Segment): def impl(self): from_net = net.FromNet(configure=[32]) to_net = net.ToNet(configure=["alloc",1]) net_free = net.FromNetFree() filter = Filter() ...
def configure(self): self.inp = Input() self.out = Output('void*', 'void*') def impl(self): self.run_c(r''' void* pkt = state->pkt; void* buff = state->pkt_buff; output { out(pkt, buff); } ''') class main(Flow):
72
72
242
5
67
mangpo/floem
apps/parameter_server/server.py
Python
main
main
262
296
262
262
8592f627f8e01e8e446652747d9d1056ae35cef0
bigcode/the-stack
train
509af4949024ed7911bd4670
train
class
class MyState(State): pkt_buff = Field('void*') pkt = Field('void*') parameters = Field('int*') n = Field(Int) group_id = Field(Int)
class MyState(State):
pkt_buff = Field('void*') pkt = Field('void*') parameters = Field('int*') n = Field(Int) group_id = Field(Int)
= "\x0a\x64\x14\x09" }, // hippopotamus {.addr = "\x0a\x64\x14\x08"}, // guanaco {.addr = "\x0a\x64\x14\x05"}, // dikdik }; ''' class MyState(State):
64
64
43
5
59
mangpo/floem
apps/parameter_server/server.py
Python
MyState
MyState
21
26
21
21
ae6a42a4c3095b6619206b477d66032e2839c4a9
bigcode/the-stack
train
0db709b53e515892a000e5c9
train
class
class RunningAvg: """Average values over a sliding window of samples.""" def __init__(self, max_samples): self.samples = deque(maxlen=max_samples) def reset(self): self.samples.clear() def process(self, value): if value is not None: self.samples.append(value) ...
class RunningAvg:
"""Average values over a sliding window of samples.""" def __init__(self, max_samples): self.samples = deque(maxlen=max_samples) def reset(self): self.samples.clear() def process(self, value): if value is not None: self.samples.append(value) if len(self.sa...
"""Mathematical, general purpose computations.""" import time from statistics import mean from collections import deque from numpy import trapz from scipy.stats import linregress class RunningAvg:
40
64
86
4
35
VMS19/Inhalator
logic/computations.py
Python
RunningAvg
RunningAvg
10
26
10
10
9d2bcb05f51758edcb96a0ab1527e9cea6fd4b4a
bigcode/the-stack
train
aaf00a28a5bef7147206f7ca
train
class
class RunningSlope: """Calculate slope on window of samples.""" def __init__(self, num_samples=10, period_ms=100): self.period_ms = period_ms self.max_samples = num_samples self.data = deque(maxlen=num_samples) self.timestamps = deque(maxlen=num_samples) def reset(self): ...
class RunningSlope:
"""Calculate slope on window of samples.""" def __init__(self, num_samples=10, period_ms=100): self.period_ms = period_ms self.max_samples = num_samples self.data = deque(maxlen=num_samples) self.timestamps = deque(maxlen=num_samples) def reset(self): self.data.clea...
() self.timestamps = deque() def add_sample(self, timestamp, value): self.samples.append(value) self.timestamps.append(timestamp) def integrate(self): return trapz(self.samples, x=self.timestamps) def reset(self): self.samples.clear() self.timestamps.clear(...
64
64
159
4
60
VMS19/Inhalator
logic/computations.py
Python
RunningSlope
RunningSlope
48
69
48
48
a6047e8bec1b24f4e34a06d01ecfa2836805ab0b
bigcode/the-stack
train
17db74d5f4399f9f8a3d56f4
train
class
class Accumulator: """Accumulate volumes using Trapezoidal numerical integration.""" def __init__(self): self.samples = deque() self.timestamps = deque() def add_sample(self, timestamp, value): self.samples.append(value) self.timestamps.append(timestamp) def integrate(...
class Accumulator:
"""Accumulate volumes using Trapezoidal numerical integration.""" def __init__(self): self.samples = deque() self.timestamps = deque() def add_sample(self, timestamp, value): self.samples.append(value) self.timestamps.append(timestamp) def integrate(self): retu...
self.samples = deque(maxlen=max_samples) def reset(self): self.samples.clear() def process(self, value): if value is not None: self.samples.append(value) if len(self.samples) == 0: return 0 return mean(self.samples) class Accumulator:
64
64
89
4
60
VMS19/Inhalator
logic/computations.py
Python
Accumulator
Accumulator
29
45
29
29
9ecfdce4c961b3d25b6a76a82625a9353c479cd4
bigcode/the-stack
train
ee1eb5aea7e6f2f51bd386d8
train
function
def test_staff_form_create_valid( admin_client, staff_user, permission_manage_products): assert staff_user.user_permissions.count() == 0 url = reverse('dashboard:staff-details', kwargs={'pk': staff_user.pk}) data = { 'email': 'staff@example.com', 'user_permissions': permission_manage...
def test_staff_form_create_valid( admin_client, staff_user, permission_manage_products):
assert staff_user.user_permissions.count() == 0 url = reverse('dashboard:staff-details', kwargs={'pk': staff_user.pk}) data = { 'email': 'staff@example.com', 'user_permissions': permission_manage_products.pk} admin_client.post(url, data) staff_user = User.objects.get(pk=staff_user.pk...
import StaffForm from saleor.settings import DEFAULT_FROM_EMAIL def test_staff_form_not_valid(db): data = {'user_permissions': 1} form = StaffForm(data=data) assert not form.is_valid() def test_staff_form_create_valid( admin_client, staff_user, permission_manage_products):
64
64
104
18
46
Iahack/saleor
tests/dashboard/test_staff.py
Python
test_staff_form_create_valid
test_staff_form_create_valid
20
29
20
21
ba60efaad4387a1fae8e30f2a2bd1831555aaa4f
bigcode/the-stack
train
3d35520cbcbb4a1a133a3dac
train
function
def test_staff_create_email_with_set_link_password(admin_client): user_count = User.objects.count() mail_outbox_count = len(mail.outbox) url = reverse('dashboard:staff-create') data = {'email': 'staff3@example.com', 'is_staff': True} response = admin_client.post(url, data) assert User.objects.c...
def test_staff_create_email_with_set_link_password(admin_client):
user_count = User.objects.count() mail_outbox_count = len(mail.outbox) url = reverse('dashboard:staff-create') data = {'email': 'staff3@example.com', 'is_staff': True} response = admin_client.post(url, data) assert User.objects.count() == user_count + 1 assert len(mail.outbox) == mail_outbo...
assert User.objects.all().count() == user_count staff_user.refresh_from_db() # Instead, his privileges are taken away assert not staff_user.is_staff assert response['Location'] == reverse('dashboard:staff-list') def test_staff_create_email_with_set_link_password(admin_client):
64
64
112
12
52
Iahack/saleor
tests/dashboard/test_staff.py
Python
test_staff_create_email_with_set_link_password
test_staff_create_email_with_set_link_password
86
95
86
86
194e1b1a849bf8e4d2e4817d95b072ae8413c135
bigcode/the-stack
train
e7500ba4bcbaa0073591a04f
train
function
def test_create_staff_from_customer( admin_client, customer_user, permission_manage_products): url = reverse('dashboard:staff-create') data = { 'email': customer_user.email, 'user_permissions': permission_manage_products.pk} admin_client.post(url, data) customer_user.refresh_from...
def test_create_staff_from_customer( admin_client, customer_user, permission_manage_products):
url = reverse('dashboard:staff-create') data = { 'email': customer_user.email, 'user_permissions': permission_manage_products.pk} admin_client.post(url, data) customer_user.refresh_from_db() assert customer_user.is_staff
response.status_code == 302 assert response['Location'] == reverse('account:reset-password-complete') new_user = User.objects.get(email='staff3@example.com') assert new_user.has_usable_password() def test_create_staff_from_customer( admin_client, customer_user, permission_manage_products):
64
64
72
18
46
Iahack/saleor
tests/dashboard/test_staff.py
Python
test_create_staff_from_customer
test_create_staff_from_customer
146
154
146
147
414599fe094dca6f7f8a07f2d816ba839c0e4d77
bigcode/the-stack
train
ee1915ec24c32fc8d106b478
train
function
def test_create_staff_and_set_password(admin_client): url = reverse('dashboard:staff-create') data = {'email': 'staff3@example.com', 'is_staff': True} response = admin_client.post(url, data) assert response.status_code == 302 new_user = User.objects.get(email='staff3@example.com') assert not new...
def test_create_staff_and_set_password(admin_client):
url = reverse('dashboard:staff-create') data = {'email': 'staff3@example.com', 'is_staff': True} response = admin_client.post(url, data) assert response.status_code == 302 new_user = User.objects.get(email='staff3@example.com') assert not new_user.has_usable_password() uid = urlsafe_base64_e...
-confirm', kwargs={ 'uidb64': ctx['uid'], 'token': ctx['token']}) absolute_generated_link = build_absolute_uri(generated_link) sended_message = mail.outbox[0].body assert absolute_generated_link in sended_message def test_create_staff_and_set_password(admin_client):
69
69
233
10
58
Iahack/saleor
tests/dashboard/test_staff.py
Python
test_create_staff_and_set_password
test_create_staff_and_set_password
122
143
122
122
e7b5d68f661b61b44a71beb5a4a546549c01e4c3
bigcode/the-stack
train
9d5c9eddc667e2337b76f4ae
train
function
def test_delete_staff_with_orders(admin_client, staff_user, order): order.user = staff_user order.save() user_count = User.objects.all().count() url = reverse('dashboard:staff-delete', kwargs={'pk': staff_user.pk}) data = {'pk': staff_user.pk} response = admin_client.post(url, data) # Staff...
def test_delete_staff_with_orders(admin_client, staff_user, order):
order.user = staff_user order.save() user_count = User.objects.all().count() url = reverse('dashboard:staff-delete', kwargs={'pk': staff_user.pk}) data = {'pk': staff_user.pk} response = admin_client.post(url, data) # Staff placed some orders in the past, so his acc should be not deleted ...
, staff_user): user_count = User.objects.all().count() url = reverse('dashboard:staff-delete', kwargs={'pk': staff_user.pk}) admin_client.get(url) assert User.objects.all().count() == user_count def test_delete_staff_with_orders(admin_client, staff_user, order):
64
64
142
14
49
Iahack/saleor
tests/dashboard/test_staff.py
Python
test_delete_staff_with_orders
test_delete_staff_with_orders
70
83
70
70
2bb85fe8071f62ece264e63e7b480cd8b9847375
bigcode/the-stack
train
36735eb0b3a868cf17926ed1
train
function
def test_admin_cant_change_his_permissions(admin_client, admin_user): assert admin_user.is_active assert admin_user.is_staff url = reverse('dashboard:staff-details', kwargs={'pk': admin_user.pk}) data = {'is_active': False, 'is_staff': False} response = admin_client.post(url, data) admin_user =...
def test_admin_cant_change_his_permissions(admin_client, admin_user):
assert admin_user.is_active assert admin_user.is_staff url = reverse('dashboard:staff-details', kwargs={'pk': admin_user.pk}) data = {'is_active': False, 'is_staff': False} response = admin_client.post(url, data) admin_user = User.objects.get(pk=admin_user.pk) assert response.status_code =...
': staff_user.pk}) data = {'csrf': 'examplecsfr'} admin_client.post(url, data) staff_user = User.objects.get(pk=staff_user.pk) assert staff_user.user_permissions.count() == 0 def test_admin_cant_change_his_permissions(admin_client, admin_user):
64
64
108
15
48
Iahack/saleor
tests/dashboard/test_staff.py
Python
test_admin_cant_change_his_permissions
test_admin_cant_change_his_permissions
40
51
40
40
f890fde8aa54d73d11e7a48419bd1ef28a844b4a
bigcode/the-stack
train
36e3ed84ff77f9a8094b0514
train
function
def test_staff_form_not_valid(db): data = {'user_permissions': 1} form = StaffForm(data=data) assert not form.is_valid()
def test_staff_form_not_valid(db):
data = {'user_permissions': 1} form = StaffForm(data=data) assert not form.is_valid()
.http import urlsafe_base64_encode from templated_email import send_templated_mail from saleor.account.models import User from saleor.core.utils import build_absolute_uri from saleor.dashboard.staff.forms import StaffForm from saleor.settings import DEFAULT_FROM_EMAIL def test_staff_form_not_valid(db):
64
64
33
8
55
Iahack/saleor
tests/dashboard/test_staff.py
Python
test_staff_form_not_valid
test_staff_form_not_valid
14
17
14
14
636bddd36caee6951ccfffe16721f529505702cb
bigcode/the-stack
train
2ada2264776ad5e256d6583d
train
function
def test_delete_staff_no_post(admin_client, staff_user): user_count = User.objects.all().count() url = reverse('dashboard:staff-delete', kwargs={'pk': staff_user.pk}) admin_client.get(url) assert User.objects.all().count() == user_count
def test_delete_staff_no_post(admin_client, staff_user):
user_count = User.objects.all().count() url = reverse('dashboard:staff-delete', kwargs={'pk': staff_user.pk}) admin_client.get(url) assert User.objects.all().count() == user_count
_user.pk}) data = {'pk': staff_user.pk} response = admin_client.post(url, data) assert User.objects.all().count() == user_count - 1 assert response['Location'] == reverse('dashboard:staff-list') def test_delete_staff_no_post(admin_client, staff_user):
64
64
58
12
52
Iahack/saleor
tests/dashboard/test_staff.py
Python
test_delete_staff_no_post
test_delete_staff_no_post
63
67
63
63
77f70a341cfcd161cbe3ab7c524d8fcfcb8d2be9
bigcode/the-stack
train
ae6e61bc85e8d2eda9c50e42
train
function
def test_staff_form_create_not_valid(admin_client, staff_user): url = reverse('dashboard:staff-details', kwargs={'pk': staff_user.pk}) data = {'csrf': 'examplecsfr'} admin_client.post(url, data) staff_user = User.objects.get(pk=staff_user.pk) assert staff_user.user_permissions.count() == 0
def test_staff_form_create_not_valid(admin_client, staff_user):
url = reverse('dashboard:staff-details', kwargs={'pk': staff_user.pk}) data = {'csrf': 'examplecsfr'} admin_client.post(url, data) staff_user = User.objects.get(pk=staff_user.pk) assert staff_user.user_permissions.count() == 0
'email': 'staff@example.com', 'user_permissions': permission_manage_products.pk} admin_client.post(url, data) staff_user = User.objects.get(pk=staff_user.pk) assert staff_user.user_permissions.count() == 1 def test_staff_form_create_not_valid(admin_client, staff_user):
64
64
75
13
50
Iahack/saleor
tests/dashboard/test_staff.py
Python
test_staff_form_create_not_valid
test_staff_form_create_not_valid
32
37
32
32
2f568db109b6f3bdfd18e39d13e369d55ee94e26
bigcode/the-stack
train
c227bf39d91ae4c9042faa44
train
function
def test_delete_staff(admin_client, staff_user): user_count = User.objects.all().count() url = reverse('dashboard:staff-delete', kwargs={'pk': staff_user.pk}) data = {'pk': staff_user.pk} response = admin_client.post(url, data) assert User.objects.all().count() == user_count - 1 assert response[...
def test_delete_staff(admin_client, staff_user):
user_count = User.objects.all().count() url = reverse('dashboard:staff-delete', kwargs={'pk': staff_user.pk}) data = {'pk': staff_user.pk} response = admin_client.post(url, data) assert User.objects.all().count() == user_count - 1 assert response['Location'] == reverse('dashboard:staff-list')
False, 'is_staff': False} response = admin_client.post(url, data) admin_user = User.objects.get(pk=admin_user.pk) assert response.status_code == 200 assert admin_user.is_active assert admin_user.is_staff def test_delete_staff(admin_client, staff_user):
64
64
87
10
53
Iahack/saleor
tests/dashboard/test_staff.py
Python
test_delete_staff
test_delete_staff
54
60
54
54
88496b1680ef710952ea2ee61eac3399d69fe7b4
bigcode/the-stack
train
0ca77a3904da5fbd69c02fd8
train
function
def test_send_set_password_email(staff_user, site_settings): site = site_settings.site ctx = { 'protocol': 'http', 'domain': site.domain, 'site_name': site.name, 'uid': urlsafe_base64_encode(force_bytes(staff_user.pk)).decode(), 'token': default_token_generator.make_token...
def test_send_set_password_email(staff_user, site_settings):
site = site_settings.site ctx = { 'protocol': 'http', 'domain': site.domain, 'site_name': site.name, 'uid': urlsafe_base64_encode(force_bytes(staff_user.pk)).decode(), 'token': default_token_generator.make_token(staff_user)} send_templated_mail( template_name=...
= admin_client.post(url, data) assert User.objects.count() == user_count + 1 assert len(mail.outbox) == mail_outbox_count + 1 assert response['Location'] == reverse('dashboard:staff-list') def test_send_set_password_email(staff_user, site_settings):
64
64
197
13
51
Iahack/saleor
tests/dashboard/test_staff.py
Python
test_send_set_password_email
test_send_set_password_email
98
119
98
98
d428a9db846ca018d9ea78377ab58c5e361bf13a
bigcode/the-stack
train
a745287c5da90372802ac091
train
class
class ResponseLevelMock: status_code = 200 text = test_text_response()
class ResponseLevelMock:
status_code = 200 text = test_text_response()
TURE.open() as f: dashboard_fixtures = json.loads(f.read()) return dashboard_fixtures def test_text_response() -> str: with LEVEL_TEXT_FIXTURE.open() as f: dashboard_fixtures = f.read() return dashboard_fixtures class ResponseLevelMock:
64
64
19
5
58
kolesnikov-bn/django-memrise-scraper
memrise/tests/repos/test_repos.py
Python
ResponseLevelMock
ResponseLevelMock
51
53
51
51
b1372cfc0d7a8477f1705b9f7ba6618a0a5459ba
bigcode/the-stack
train
00948eb85edc51a0862f1d0d
train
function
def test_text_response() -> str: with LEVEL_TEXT_FIXTURE.open() as f: dashboard_fixtures = f.read() return dashboard_fixtures
def test_text_response() -> str:
with LEVEL_TEXT_FIXTURE.open() as f: dashboard_fixtures = f.read() return dashboard_fixtures
fixtures/level_text_response.html" class ResponseCourseMock: status_code = 200 def json(self) -> Dict: with DASHBOARD_FIXTURE.open() as f: dashboard_fixtures = json.loads(f.read()) return dashboard_fixtures def test_text_response() -> str:
64
64
35
8
55
kolesnikov-bn/django-memrise-scraper
memrise/tests/repos/test_repos.py
Python
test_text_response
test_text_response
44
48
44
44
4fbc7bf004044ca63310dd868132401ebf166589
bigcode/the-stack
train
73be6e2332a52b4ee90a9781
train
class
class TestJsonRep(TestCase): def setUp(self) -> None: self.repo = JsonRep(JsonActionsBatch()) def test_get_courses(self) -> None: courses = self.repo.get_courses() self.assertEqual(len(courses), 5) excepted = [1987730, 2147115, 5605650, 2014031, 2014042] self.assertEqual...
class TestJsonRep(TestCase):
def setUp(self) -> None: self.repo = JsonRep(JsonActionsBatch()) def test_get_courses(self) -> None: courses = self.repo.get_courses() self.assertEqual(len(courses), 5) excepted = [1987730, 2147115, 5605650, 2014031, 2014042] self.assertEqual([x.id for x in courses], exc...
: with DASHBOARD_FIXTURE.open() as f: dashboard_fixtures = json.loads(f.read()) return dashboard_fixtures def test_text_response() -> str: with LEVEL_TEXT_FIXTURE.open() as f: dashboard_fixtures = f.read() return dashboard_fixtures class ResponseLevelMock: status_co...
91
91
304
7
84
kolesnikov-bn/django-memrise-scraper
memrise/tests/repos/test_repos.py
Python
TestJsonRep
TestJsonRep
56
87
56
56
72820e0886a1e7d9cdf59a838c3dbd60f0c464b2
bigcode/the-stack
train
7d6ba0b48055e2b856270054
train
class
class ResponseCourseMock: status_code = 200 def json(self) -> Dict: with DASHBOARD_FIXTURE.open() as f: dashboard_fixtures = json.loads(f.read()) return dashboard_fixtures
class ResponseCourseMock:
status_code = 200 def json(self) -> Dict: with DASHBOARD_FIXTURE.open() as f: dashboard_fixtures = json.loads(f.read()) return dashboard_fixtures
, Word from memrise.shares.contants import DASHBOARD_FIXTURE from memrise.tests.data_for_test import ( fresh_course_entities, fresh_level_entities, fresh_word_entities, ) LEVEL_TEXT_FIXTURE = settings.RESOURSES / "fixtures/level_text_response.html" class ResponseCourseMock:
64
64
49
5
59
kolesnikov-bn/django-memrise-scraper
memrise/tests/repos/test_repos.py
Python
ResponseCourseMock
ResponseCourseMock
34
41
34
34
e5cdf019de27ad4fe11204e411a38b2a06f7c47e
bigcode/the-stack
train
a3d9223287b8661b05b2ea96
train
class
class TestMemriseRep(AioHTTPTestCase): async def get_application(self): return web.Application() def set_get_mock_response(self, mock_get, status, json_data): mock_get.return_value.__aenter__.return_value.status = status mock_get.return_value.__aenter__.return_value.json = CoroutineMock...
class TestMemriseRep(AioHTTPTestCase):
async def get_application(self): return web.Application() def set_get_mock_response(self, mock_get, status, json_data): mock_get.return_value.__aenter__.return_value.status = status mock_get.return_value.__aenter__.return_value.json = CoroutineMock( return_value=json_data ...
in=course_records) self.assertEqual(len(levels_after), 8) def test_save_words(self) -> None: level = Level.objects.first() words = Word.objects.filter(level=level).all() # Check before. self.assertEqual(len(words), 4) self.assertEqual( [x.id for x in wor...
255
256
1,463
11
244
kolesnikov-bn/django-memrise-scraper
memrise/tests/repos/test_repos.py
Python
TestMemriseRep
TestMemriseRep
216
434
216
216
afc2da75cf0f9e0242a008e3606f188af223169c
bigcode/the-stack
train
7e580e0848567d3cfa4c2422
train
class
class TestDBRep(TestCase): fixtures = ["db"] def setUp(self) -> None: self.repo = DBRep(DBActionsBatch()) def test_get_courses(self) -> None: courses = self.repo.get_courses() self.assertEqual(len(courses), 5) expected = [1987730, 2147115, 2147124, 2147132, 5605650] ...
class TestDBRep(TestCase):
fixtures = ["db"] def setUp(self) -> None: self.repo = DBRep(DBActionsBatch()) def test_get_courses(self) -> None: courses = self.repo.get_courses() self.assertEqual(len(courses), 5) expected = [1987730, 2147115, 2147124, 2147132, 5605650] self.assertEqual([x.id for...
excepted = [1987730, 2147115, 5605650, 2014031, 2014042] self.assertEqual([x.id for x in courses], excepted) def test_get_levels(self) -> None: with DASHBOARD_FIXTURE.open() as f: dashboard_fixtures_response = json.loads(f.read()) courses_response = CoursesResponse(**da...
256
256
1,238
7
249
kolesnikov-bn/django-memrise-scraper
memrise/tests/repos/test_repos.py
Python
TestDBRep
TestDBRep
90
213
90
90
297d593e3fec630ae8c189684989dfceadaa6cb9
bigcode/the-stack
train
0d25825a91684dcbd0c65765
train
class
class WTSTransStruct(WTSStruct): ''' C接口传递的逐笔成交数据结构 ''' _fields_ = [("exchg", MAX_EXCHANGE_LENGTH), ("code", MAX_INSTRUMENT_LENGTH), ("trading_date", c_uint32), ("action_date", c_uint32), ("action_time", c_uint32), ...
class WTSTransStruct(WTSStruct):
''' C接口传递的逐笔成交数据结构 ''' _fields_ = [("exchg", MAX_EXCHANGE_LENGTH), ("code", MAX_INSTRUMENT_LENGTH), ("trading_date", c_uint32), ("action_date", c_uint32), ("action_time", c_uint32), ("index", c_uint32), ...
return ( self.date, self.date if isDays else self.time + 199000000000, self.open, self.high, self.low, self.close, self.settle, self.money, self.vol, ...
69
69
233
9
60
systemtrader/wtpy
wtpy/WtCoreDefs.py
Python
WTSTransStruct
WTSTransStruct
137
173
137
137
4e46cebf8482e35015d5ea5c39fc83d4a2bf7d3b
bigcode/the-stack
train
c6e83cca1fce6558599316c3
train
class
class BarList(CacheList): def on_read_bar(self, curBar:POINTER(WTSBarStruct), count:int, isLast:bool): ''' 读取bar数据回调函数 @curBar 当前数据块首地址 @count 当前数据块条数 @isLast 是否是最后一块数据块 ''' bsSize = sizeof(WTSBarStruct) addr = addressof(...
class BarList(CacheList):
def on_read_bar(self, curBar:POINTER(WTSBarStruct), count:int, isLast:bool): ''' 读取bar数据回调函数 @curBar 当前数据块首地址 @count 当前数据块条数 @isLast 是否是最后一块数据块 ''' bsSize = sizeof(WTSBarStruct) addr = addressof(curBar.contents) f...
.empty(len(self), dtype=self[0].fields) for k, v in enumerate(self): self[k] = v.values return self.view(np.recarray) def to_pandas(self) -> pd.DataFrame: return pd.DataFrame(self.to_record()) class BarList(CacheList):
63
64
199
6
57
systemtrader/wtpy
wtpy/WtCoreDefs.py
Python
BarList
BarList
251
275
251
251
945a06db178dd97f3bbfab8a2f82f71e5dd3243a
bigcode/the-stack
train
b6bc5011d3829c0da5c23c50
train
class
class CacheList(list): def to_record(self) -> np.recarray: self = np.empty(len(self), dtype=self[0].fields) for k, v in enumerate(self): self[k] = v.values return self.view(np.recarray) def to_pandas(self) -> pd.DataFrame: return pd.DataFrame(self.to_record()...
class CacheList(list):
def to_record(self) -> np.recarray: self = np.empty(len(self), dtype=self[0].fields) for k, v in enumerate(self): self[k] = v.values return self.view(np.recarray) def to_pandas(self) -> pd.DataFrame: return pd.DataFrame(self.to_record())
_date)*1000000000+self.action_time, self.exchg, self.code, self.trading_date, self.action_date, self.action_time, self.index, self.side, self.price, self.volume, ...
63
64
77
5
58
systemtrader/wtpy
wtpy/WtCoreDefs.py
Python
CacheList
CacheList
241
249
241
241
9e93b0711a2a9743dfc6926f0294175da8e4d4be
bigcode/the-stack
train
a588d558bd65ee0e4fe080e2
train
class
class WTSBarStruct(WTSStruct): ''' C接口传递的bar数据结构 ''' _fields_ = [("date", c_uint32), ("reserve", c_uint32), ("time", c_uint64), ("open", c_double), ("high", c_double), ("low", c_double), ("close", c...
class WTSBarStruct(WTSStruct):
''' C接口传递的bar数据结构 ''' _fields_ = [("date", c_uint32), ("reserve", c_uint32), ("time", c_uint64), ("open", c_double), ("high", c_double), ("low", c_double), ("close", c_double), ("set...
self.action_time, self.pre_close, self.pre_settle, self.pre_interest ) \ + tuple(self.bid_prices) \ + tuple(self.ask_prices) \ + tuple(self.bid_qty) \ + tuple(self.ask_qty) class WTSBarStr...
64
64
200
9
55
systemtrader/wtpy
wtpy/WtCoreDefs.py
Python
WTSBarStruct
WTSBarStruct
105
135
105
105
93539f0ced15f266a4d4232a3d73533528534131
bigcode/the-stack
train
a0e9c86a9829f9956f62e597
train
class
class WTSStruct(Structure): @property def fields(self) -> list: return self._fields_ @property def values(self) -> tuple: return tuple(getattr(self, i[0]) for i in self._fields_) @property def to_dict(self) -> dict: return {i[0]:getattr(self, i[0]) for i in s...
class WTSStruct(Structure): @property
def fields(self) -> list: return self._fields_ @property def values(self) -> tuple: return tuple(getattr(self, i[0]) for i in self._fields_) @property def to_dict(self) -> dict: return {i[0]:getattr(self, i[0]) for i in self._fields_}
numpy as np import pandas as pd from typing import Any MAX_INSTRUMENT_LENGTH = c_char*32 MAX_EXCHANGE_LENGTH = c_char*16 PriceQueueType = c_double*10 VolumeQueueType = c_double*10 class WTSStruct(Structure): @property
64
64
93
11
52
systemtrader/wtpy
wtpy/WtCoreDefs.py
Python
WTSStruct
WTSStruct
13
24
13
14
d0eb204251f4597e2575efd1eef4ffd76df55868
bigcode/the-stack
train
1dae194476107483a22ae3dd
train
class
class WTSOrdDtlStruct(WTSStruct): ''' C接口传递的委托明细数据结构 ''' _fields_ = [("exchg", MAX_EXCHANGE_LENGTH), ("code", MAX_INSTRUMENT_LENGTH), ("trading_date", c_uint32), ("action_date", c_uint32), ("action_time", c_uint32), ...
class WTSOrdDtlStruct(WTSStruct):
''' C接口传递的委托明细数据结构 ''' _fields_ = [("exchg", MAX_EXCHANGE_LENGTH), ("code", MAX_INSTRUMENT_LENGTH), ("trading_date", c_uint32), ("action_date", c_uint32), ("action_time", c_uint32), ("index", c_uint32), ...
.action_time, self.exchg, self.code, self.trading_date, self.action_date, self.action_time, self.side, self.price, self.order_items, self.qsize ) + tuple(...
64
64
205
10
54
systemtrader/wtpy
wtpy/WtCoreDefs.py
Python
WTSOrdDtlStruct
WTSOrdDtlStruct
207
238
207
207
94e94a7e13ba3ab1d6e8a0dc6a4bc51479d93ca4
bigcode/the-stack
train
d84d082f3b576c3b3fc1d53b
train
class
class WTSOrdQueStruct(WTSStruct): ''' C接口传递的委托队列数据结构 ''' _fields_ = [("exchg", MAX_EXCHANGE_LENGTH), ("code", MAX_INSTRUMENT_LENGTH), ("trading_date", c_uint32), ("action_date", c_uint32), ("action_time", c_uint32), ...
class WTSOrdQueStruct(WTSStruct):
''' C接口传递的委托队列数据结构 ''' _fields_ = [("exchg", MAX_EXCHANGE_LENGTH), ("code", MAX_INSTRUMENT_LENGTH), ("trading_date", c_uint32), ("action_date", c_uint32), ("action_time", c_uint32), ("side", c_int32), ...
, self.code, self.trading_date, self.action_date, self.action_time, self.index, self.ttype, self.side, self.price, self.volume, self.askorder, ...
64
64
213
10
54
systemtrader/wtpy
wtpy/WtCoreDefs.py
Python
WTSOrdQueStruct
WTSOrdQueStruct
175
205
175
175
e7ca16899208cd43c6bf839633dd023ec40ca0fd
bigcode/the-stack
train
fdaddd9ed770b6d290577f55
train
class
class TickList(CacheList): def on_read_tick(self, curTick:POINTER(WTSTickStruct), count:int, isLast:bool): ''' 读取tick数据回调函数 @curTick 当前数据块首地址 @count 当前数据块条数 @isLast 是否是最后一块数据块 ''' tsSize = sizeof(WTSTickStruct) addr = add...
class TickList(CacheList):
def on_read_tick(self, curTick:POINTER(WTSTickStruct), count:int, isLast:bool): ''' 读取tick数据回调函数 @curTick 当前数据块首地址 @count 当前数据块条数 @isLast 是否是最后一块数据块 ''' tsSize = sizeof(WTSTickStruct) addr = addressof(curTick.contents) ...
''' 读取数据时的总条数回调 该回调有可能会触发,也可能不会触发 如果触发,可以做一个预先分配容量的处理 @count 总的数据条数 ''' pass class TickList(CacheList):
64
64
201
6
57
systemtrader/wtpy
wtpy/WtCoreDefs.py
Python
TickList
TickList
277
301
277
277
202859ca5bc204421f7dffb409f20ba2a4191b85
bigcode/the-stack
train
cb1d95a9b0c040dcd297d35f
train
class
class EngineType(Enum): ''' 引擎类型 枚举变量 ''' ET_CTA = 999 ET_HFT = 1000 ET_SEL = 1001
class EngineType(Enum):
''' 引擎类型 枚举变量 ''' ET_CTA = 999 ET_HFT = 1000 ET_SEL = 1001
架调度 EVENT_BACKTEST_END = 5 #回测结束 CHNL_EVENT_READY = 1000 #通道就绪事件 CHNL_EVENT_LOST = 1001 #通道断开事件 from enum import Enum class EngineType(Enum):
64
64
46
5
58
systemtrader/wtpy
wtpy/WtCoreDefs.py
Python
EngineType
EngineType
359
366
359
359
28919b694391ae91abb899982cb8ab4ba1d0d696
bigcode/the-stack
train
a97c26f81f4e151c146c2523
train
class
class WTSTickStruct(WTSStruct): ''' C接口传递的tick数据结构 ''' _fields_ = [("exchg", MAX_EXCHANGE_LENGTH), ("code", MAX_INSTRUMENT_LENGTH), ("price", c_double), ("open", c_double), ("high", c_double), ("low", c_double), ...
class WTSTickStruct(WTSStruct):
''' C接口传递的tick数据结构 ''' _fields_ = [("exchg", MAX_EXCHANGE_LENGTH), ("code", MAX_INSTRUMENT_LENGTH), ("price", c_double), ("open", c_double), ("high", c_double), ("low", c_double), ("settle_price", c_...
copy import numpy as np import pandas as pd from typing import Any MAX_INSTRUMENT_LENGTH = c_char*32 MAX_EXCHANGE_LENGTH = c_char*16 PriceQueueType = c_double*10 VolumeQueueType = c_double*10 class WTSStruct(Structure): @property def fields(self) -> list: return self._fields_ @pro...
158
158
528
9
149
systemtrader/wtpy
wtpy/WtCoreDefs.py
Python
WTSTickStruct
WTSTickStruct
26
102
26
26
1462b5378a18605d8ad5b82fbca18b916c2a3960
bigcode/the-stack
train
5f6a89c3e2edaf6c3583d424
train
function
def test_morphsnakes_incorrect_ndim(): img = np.zeros((4, 4, 4, 4)) ls = np.zeros((4, 4, 4, 4)) with pytest.raises(ValueError): morphological_chan_vese(img, iterations=1, init_level_set=ls) with pytest.raises(ValueError): morphological_geodesic_active_contour(img, iterations=1, ...
def test_morphsnakes_incorrect_ndim():
img = np.zeros((4, 4, 4, 4)) ls = np.zeros((4, 4, 4, 4)) with pytest.raises(ValueError): morphological_chan_vese(img, iterations=1, init_level_set=ls) with pytest.raises(ValueError): morphological_geodesic_active_contour(img, iterations=1, i...
)) with pytest.raises(ValueError): morphological_chan_vese(img, iterations=1, init_level_set=ls) with pytest.raises(ValueError): morphological_geodesic_active_contour(img, iterations=1, init_level_set=ls) def test_morphsnakes_incorrect_ndim():
64
64
97
11
53
1051556543/morphsnakes
test_morphsnakes.py
Python
test_morphsnakes_incorrect_ndim
test_morphsnakes_incorrect_ndim
29
38
29
30
51a6837b657e878c6d8ce431560121f1b9f076ba
bigcode/the-stack
train
7c8d1ec5f7594a82a3e91ecc
train
function
def test_morphsnakes_simple_shape_geodesic_active_contour(): img = np.float_(circle_level_set((11, 11), (5, 5), 3.5)) gimg = inverse_gaussian_gradient(img, alpha=10.0, sigma=1.0) ls = circle_level_set(img.shape, (5, 5), 6) ref = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0...
def test_morphsnakes_simple_shape_geodesic_active_contour():
img = np.float_(circle_level_set((11, 11), (5, 5), 3.5)) gimg = inverse_gaussian_gradient(img, alpha=10.0, sigma=1.0) ls = circle_level_set(img.shape, (5, 5), 6) ref = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0,...
== np.int8 def test_morphsnakes_simple_shape_chan_vese(): img = gaussian_blob() ls1 = circle_level_set(img.shape, (5, 5), 3) ls2 = circle_level_set(img.shape, (5, 5), 6) acwe_ls1 = morphological_chan_vese(img, iterations=10, init_level_set=ls1) acwe_ls2 = morphological_chan_vese(img, iterations...
154
154
515
15
138
1051556543/morphsnakes
test_morphsnakes.py
Python
test_morphsnakes_simple_shape_geodesic_active_contour
test_morphsnakes_simple_shape_geodesic_active_contour
79
104
79
80
ecebff1689fb190692ab160b10b648ae12cb58ab
bigcode/the-stack
train
15f2c9cac7b86f157f317ac5
train
function
def test_morphsnakes_incorrect_image_shape(): img = np.zeros((10, 10, 3)) ls = np.zeros((10, 9)) with pytest.raises(ValueError): morphological_chan_vese(img, iterations=1, init_level_set=ls) with pytest.raises(ValueError): morphological_geodesic_active_contour(img, iterations=1, ...
def test_morphsnakes_incorrect_image_shape():
img = np.zeros((10, 10, 3)) ls = np.zeros((10, 9)) with pytest.raises(ValueError): morphological_chan_vese(img, iterations=1, init_level_set=ls) with pytest.raises(ValueError): morphological_geodesic_active_contour(img, iterations=1, init_le...
import pytest def gaussian_blob(): coords = np.mgrid[-5:6, -5:6] sqrdistances = (coords ** 2).sum(0) return np.exp(-sqrdistances / 10) def test_morphsnakes_incorrect_image_shape():
64
64
88
11
53
1051556543/morphsnakes
test_morphsnakes.py
Python
test_morphsnakes_incorrect_image_shape
test_morphsnakes_incorrect_image_shape
18
26
18
18
a69d9c2440c8b2b47d2de4478476de6ba163c373
bigcode/the-stack
train
3d97fce29b441026fa02abbc
train
function
def test_morphsnakes_3d(): image = np.zeros((7, 7, 7)) evolution = [] def callback(x): evolution.append(x.sum()) ls = morphological_chan_vese(image, 5, 'circle', iter_callback=callback) # Check that the initial circle level set is correct assert evol...
def test_morphsnakes_3d():
image = np.zeros((7, 7, 7)) evolution = [] def callback(x): evolution.append(x.sum()) ls = morphological_chan_vese(image, 5, 'circle', iter_callback=callback) # Check that the initial circle level set is correct assert evolution[0] == 81 # Check ...
, 1, 1], [0, 0, 1, 1, 1, 0]], dtype=np.int8) assert_array_equal(checkerboard_ls, checkerboard_ref) assert_array_equal(circle_ls, circle_ref) def test_morphsnakes_3d():
64
64
141
10
54
1051556543/morphsnakes
test_morphsnakes.py
Python
test_morphsnakes_3d
test_morphsnakes_3d
130
150
130
131
da363f9fbc75936bd7bf74b3568036a73882dc30
bigcode/the-stack
train
e5e4f5cef3a6d79e3156b4ed
train
function
def gaussian_blob(): coords = np.mgrid[-5:6, -5:6] sqrdistances = (coords ** 2).sum(0) return np.exp(-sqrdistances / 10)
def gaussian_blob():
coords = np.mgrid[-5:6, -5:6] sqrdistances = (coords ** 2).sum(0) return np.exp(-sqrdistances / 10)
import numpy as np from morphsnakes import (morphological_chan_vese, morphological_geodesic_active_contour, inverse_gaussian_gradient, circle_level_set, checkerboard_level_set) from numpy.testing import assert_array_equal import pytest def gaus...
59
64
49
4
54
1051556543/morphsnakes
test_morphsnakes.py
Python
gaussian_blob
gaussian_blob
11
15
11
12
eaadc04d7943a54c23c3665e174ffd7537396aad
bigcode/the-stack
train
7dfa395b2d54ab5738339ae7
train
function
def test_morphsnakes_simple_shape_chan_vese(): img = gaussian_blob() ls1 = circle_level_set(img.shape, (5, 5), 3) ls2 = circle_level_set(img.shape, (5, 5), 6) acwe_ls1 = morphological_chan_vese(img, iterations=10, init_level_set=ls1) acwe_ls2 = morphological_chan_vese(img, iterations=10, init_leve...
def test_morphsnakes_simple_shape_chan_vese():
img = gaussian_blob() ls1 = circle_level_set(img.shape, (5, 5), 3) ls2 = circle_level_set(img.shape, (5, 5), 6) acwe_ls1 = morphological_chan_vese(img, iterations=10, init_level_set=ls1) acwe_ls2 = morphological_chan_vese(img, iterations=10, init_level_set=ls2) assert_array_equal(acwe_ls1, acw...
_level_set=ls, balloon=1, threshold=-1, smoothing=0) assert_array_equal(gac_ls2, ref_ones) assert acwe_ls.dtype == gac_ls.dtype == gac_ls2.dtype == np.int8 def test_morphsnakes_simple_shape_chan_vese():
64
64
134
12
51
1051556543/morphsnakes
test_morphsnakes.py
Python
test_morphsnakes_simple_shape_chan_vese
test_morphsnakes_simple_shape_chan_vese
65
76
65
66
5d26b29b1a62e82f0f86a7f2f6142496e021b6af
bigcode/the-stack
train
2cede0c52566546e24628b52
train
function
def test_init_level_sets(): image = np.zeros((6, 6)) checkerboard_ls = morphological_chan_vese(image, 0, 'checkerboard') checkerboard_ref = np.array([[0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 1], ...
def test_init_level_sets():
image = np.zeros((6, 6)) checkerboard_ls = morphological_chan_vese(image, 0, 'checkerboard') checkerboard_ref = np.array([[0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 1], ...
], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=np.int8) gac_ls = morphological_geodesic_active_contour(gimg, iterations=10, init_level_set=ls, balloon=-1) assert_array_equ...
97
97
326
6
90
1051556543/morphsnakes
test_morphsnakes.py
Python
test_init_level_sets
test_init_level_sets
107
127
107
108
6846aa806526f73b2bfaac8100a8f76656b068b4
bigcode/the-stack
train
698edb0f443a606bca89f566
train
function
def test_morphsnakes_black(): img = np.zeros((11, 11)) ls = circle_level_set(img.shape, (5, 5), 3) ref_zeros = np.zeros(img.shape, dtype=np.int8) ref_ones = np.ones(img.shape, dtype=np.int8) acwe_ls = morphological_chan_vese(img, iterations=6, init_level_set=ls) assert_array_equal(acwe_ls, re...
def test_morphsnakes_black():
img = np.zeros((11, 11)) ls = circle_level_set(img.shape, (5, 5), 3) ref_zeros = np.zeros(img.shape, dtype=np.int8) ref_ones = np.ones(img.shape, dtype=np.int8) acwe_ls = morphological_chan_vese(img, iterations=6, init_level_set=ls) assert_array_equal(acwe_ls, ref_zeros) gac_ls = morpholo...
, 4)) with pytest.raises(ValueError): morphological_chan_vese(img, iterations=1, init_level_set=ls) with pytest.raises(ValueError): morphological_geodesic_active_contour(img, iterations=1, init_level_set=ls) def test_morphsnakes_black():
64
64
208
8
56
1051556543/morphsnakes
test_morphsnakes.py
Python
test_morphsnakes_black
test_morphsnakes_black
41
62
41
42
0323e39749f38bab325ebab01b1a3f5013f543ab
bigcode/the-stack
train
60cc18796a4ae3ece3a43cbf
train
class
class HTTPBasicsTest (BitcoinTestFramework): def setup_nodes(self): return start_nodes(4, self.options.tmpdir) def setup_chain(self): print("Initializing test directory "+self.options.tmpdir) initialize_chain(self.options.tmpdir) #Append rpcauth to bitcoin.conf before initializa...
class HTTPBasicsTest (BitcoinTestFramework):
def setup_nodes(self): return start_nodes(4, self.options.tmpdir) def setup_chain(self): print("Initializing test directory "+self.options.tmpdir) initialize_chain(self.options.tmpdir) #Append rpcauth to bitcoin.conf before initialization rpcauth = "rpcauth=rt:93648e835a...
#!/usr/bin/env python3 # Copyright (c) 2015 The Bitcoin Core developers # Copyright (c) 2015-2017 The Bitcoin Unlimited developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. import test_framework.loginit # # Test mulitple rpc ...
117
256
1,094
9
107
smogm/eccoin
qa/rpc-tests/multi_rpc.py
Python
HTTPBasicsTest
HTTPBasicsTest
17
111
17
17
969be566246e07567f2a382aaf4d60bfab0681ea
bigcode/the-stack
train
20a2a0e9f55c7b32ae6ed06f
train
function
@subscription.command(name='deactivate', short_help="Deactivate a subscription") @click.argument('subscription_type', nargs=1, required=True) @click.argument('subscription_key', nargs=1, required=True) def deactivate(subscription_type, subscription_key): """ SUBSCRIPTION_TYPE: Type of subscription. Valid option...
@subscription.command(name='deactivate', short_help="Deactivate a subscription") @click.argument('subscription_type', nargs=1, required=True) @click.argument('subscription_key', nargs=1, required=True) def deactivate(subscription_type, subscription_key):
""" SUBSCRIPTION_TYPE: Type of subscription. Valid options: - tag_update: Receive notification when new image is pushed - policy_eval: Receive notification when image policy status changes - vuln_update: Receive notification when vulnerabilities are added, removed or modified SUBSCRIP...
(config, 'subscription_activate', {}, err)) if not ecode: ecode = 2 anchorecli.cli.utils.doexit(ecode) @subscription.command(name='deactivate', short_help="Deactivate a subscription") @click.argument('subscription_type', nargs=1, required=True) @click.argument('subscription_key', nargs=1, requi...
82
82
275
49
33
ayanes/anchore-cli
anchorecli/cli/subscription.py
Python
deactivate
deactivate
55
85
55
58
305cb3bb9926acd775262581ff63555f7b53fe2b
bigcode/the-stack
train
0947b78e7ca7752ce0eebd12
train
function
@click.group(name='subscription', short_help='Subscription operations') @click.pass_obj def subscription(ctx_config): global config config = ctx_config try: anchorecli.cli.utils.check_access(config) except Exception as err: print(anchorecli.cli.utils.format_error_output(config, 'subscri...
@click.group(name='subscription', short_help='Subscription operations') @click.pass_obj def subscription(ctx_config):
global config config = ctx_config try: anchorecli.cli.utils.check_access(config) except Exception as err: print(anchorecli.cli.utils.format_error_output(config, 'subscription', {}, err)) sys.exit(2)
import sys import os import re import json import click import anchorecli.clients.apiexternal config = {} @click.group(name='subscription', short_help='Subscription operations') @click.pass_obj def subscription(ctx_config):
48
64
75
21
27
ayanes/anchore-cli
anchorecli/cli/subscription.py
Python
subscription
subscription
11
21
11
13
224cb6a78c852de5acc736b8df1ce320d72380ff
bigcode/the-stack
train
c973f70102074c90b2c98048
train
function
@subscription.command(name='list', short_help="List all current subscriptions") def subscriptionlist(): ecode = 0 try: ret = anchorecli.clients.apiexternal.get_subscription(config) ecode = anchorecli.cli.utils.get_ecode(ret) if ret['success']: print(anchorecli.cli.utils.forma...
@subscription.command(name='list', short_help="List all current subscriptions") def subscriptionlist():
ecode = 0 try: ret = anchorecli.clients.apiexternal.get_subscription(config) ecode = anchorecli.cli.utils.get_ecode(ret) if ret['success']: print(anchorecli.cli.utils.format_output(config, 'subscription_list', {}, ret['payload'])) else: raise Exception( js...
print(anchorecli.cli.utils.format_error_output(config, 'subscription_deactivate', {}, err)) if not ecode: ecode = 2 anchorecli.cli.utils.doexit(ecode) @subscription.command(name='list', short_help="List all current subscriptions") def subscriptionlist():
64
64
151
19
45
ayanes/anchore-cli
anchorecli/cli/subscription.py
Python
subscriptionlist
subscriptionlist
87
103
87
88
abb779c61923ed9d71e61d4f07bb759454f38dea
bigcode/the-stack
train
9deada71fd6a6332b99c791f
train
function
@subscription.command(name='activate', short_help="Activate a subscription") @click.argument('subscription_type', nargs=1, required=True) @click.argument('subscription_key', nargs=1, required=True) def activate(subscription_type, subscription_key): """ SUBSCRIPTION_TYPE: Type of subscription. Valid options: ...
@subscription.command(name='activate', short_help="Activate a subscription") @click.argument('subscription_type', nargs=1, required=True) @click.argument('subscription_key', nargs=1, required=True) def activate(subscription_type, subscription_key):
""" SUBSCRIPTION_TYPE: Type of subscription. Valid options: - tag_update: Receive notification when new image is pushed - policy_eval: Receive notification when image policy status changes - vuln_update: Receive notification when vulnerabilities are added, removed or modified SUBSCRIP...
(config) except Exception as err: print(anchorecli.cli.utils.format_error_output(config, 'subscription', {}, err)) sys.exit(2) @subscription.command(name='activate', short_help="Activate a subscription") @click.argument('subscription_type', nargs=1, required=True) @click.argument('subscription_key',...
81
81
271
48
33
ayanes/anchore-cli
anchorecli/cli/subscription.py
Python
activate
activate
23
53
23
26
bcffe8d9a03ee0db05651726dc7d20cf3b36bbe2
bigcode/the-stack
train
a7d723b0452790fa46c55937
train
function
def chars(w1: str, w2: str) -> int: from itertools import zip_longest return sum([1 for c1, c2 in zip_longest(w1, w2) if c1 != c2 ])
def chars(w1: str, w2: str) -> int:
from itertools import zip_longest return sum([1 for c1, c2 in zip_longest(w1, w2) if c1 != c2 ])
result def stem(w1: str, w2: str) -> int: from stemmer import stemmer st = stemmer.Stemmer() return chars(st.stem(w1), st.stem(w2)) def chars(w1: str, w2: str) -> int:
64
64
56
15
49
zaibacu/masters
rank/util/__init__.py
Python
chars
chars
18
23
18
18
6bab2763d90d97ee5568267b5a6c5b06c933f998
bigcode/the-stack
train
cbef8b2396feef3f1448d7a7
train
function
def stem(w1: str, w2: str) -> int: from stemmer import stemmer st = stemmer.Stemmer() return chars(st.stem(w1), st.stem(w2))
def stem(w1: str, w2: str) -> int:
from stemmer import stemmer st = stemmer.Stemmer() return chars(st.stem(w1), st.stem(w2))
, w2: str) -> int: result = distance(w1, w2) logger.debug("Distance between {0} and {1} is {2}".format(w1, w2, result)) return result def stem(w1: str, w2: str) -> int:
64
64
47
15
48
zaibacu/masters
rank/util/__init__.py
Python
stem
stem
12
15
12
12
9110ede7b33675b20bfb17e7672777a16728f88f
bigcode/the-stack
train
7533dfb611037fdaf7a8fc7c
train
function
def levenshtein(w1: str, w2: str) -> int: result = distance(w1, w2) logger.debug("Distance between {0} and {1} is {2}".format(w1, w2, result)) return result
def levenshtein(w1: str, w2: str) -> int:
result = distance(w1, w2) logger.debug("Distance between {0} and {1} is {2}".format(w1, w2, result)) return result
from Levenshtein import distance import logging logger = logging.getLogger(__name__) def levenshtein(w1: str, w2: str) -> int:
36
64
57
17
19
zaibacu/masters
rank/util/__init__.py
Python
levenshtein
levenshtein
6
9
6
6
49e6a3347a1c17a0fef8148a6142662c100fa6e5
bigcode/the-stack
train
36aaf386d3e524b3567dc2d7
train
function
def purge(raw): import re return re.sub(r"([.,!?'\";:/\(\)]|\s)", " ", raw).lower()
def purge(raw):
import re return re.sub(r"([.,!?'\";:/\(\)]|\s)", " ", raw).lower()
(w2)) def chars(w1: str, w2: str) -> int: from itertools import zip_longest return sum([1 for c1, c2 in zip_longest(w1, w2) if c1 != c2 ]) def purge(raw):
63
64
33
4
59
zaibacu/masters
rank/util/__init__.py
Python
purge
purge
26
28
26
26
db9bbe803e82d455a88a890fc8beec851d8e65ac
bigcode/the-stack
train
ff2b3b04c56b58c4c078f3c9
train
function
@pytest.mark.asyncio async def test_update_game_server_deployment_async(transport: str = "grpc_asyncio"): client = GameServerDeploymentsServiceAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, ...
@pytest.mark.asyncio async def test_update_game_server_deployment_async(transport: str = "grpc_asyncio"):
client = GameServerDeploymentsServiceAsyncClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. request = game_server_deplo...
_server_deployments.UpdateGameServerDeploymentRequest() # Establish that the response is the type that we expect. assert isinstance(response, future.Future) def test_update_game_server_deployment_from_dict(): test_update_game_server_deployment(request_type=dict) @pytest.mark.asyncio async def test_update...
76
76
255
24
52
Yingxin-Jiang/python-game-servers
tests/unit/gapic/gaming_v1/test_game_server_deployments_service.py
Python
test_update_game_server_deployment_async
test_update_game_server_deployment_async
1,491
1,519
1,491
1,492
012df1e0502ded767da36180eaf7393ff2b715be
bigcode/the-stack
train
21aca9106698754111705f91
train
function
@pytest.mark.parametrize( "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"] ) @mock.patch("google.api_core.grpc_helpers_async.create_channel", autospec=True) def test_game_server_deployments_service_grpc_asyncio_transport_channel_mtls_with_adc( grpc_create_channel, api_mtls_endpoint ):...
@pytest.mark.parametrize( "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"] ) @mock.patch("google.api_core.grpc_helpers_async.create_channel", autospec=True) def test_game_server_deployments_service_grpc_asyncio_transport_channel_mtls_with_adc( grpc_create_channel, api_mtls_endpoint ):...
mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel # Mock google.auth.transport.grpc.SslCredentials class. mock_ssl_cred = mock.Mock() with mock.patch.multiple( "google.auth.transport.grpc.SslCredentials", __init__=mock.Mock(return_value=None), ...
@pytest.mark.parametrize( "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"] ) @mock.patch("google.api_core.grpc_helpers_async.create_channel", autospec=True) def test_game_server_deployments_service_grpc_asyncio_transport_channel_mtls_with_adc( grpc_create_channel, api_mtls_endpoint ):...
119
102
341
119
0
Yingxin-Jiang/python-game-servers
tests/unit/gapic/gaming_v1/test_game_server_deployments_service.py
Python
test_game_server_deployments_service_grpc_asyncio_transport_channel_mtls_with_adc
test_game_server_deployments_service_grpc_asyncio_transport_channel_mtls_with_adc
2,766
2,800
2,766
2,774
91e798e2c5b0cae06d8113080c752627336ceea9
bigcode/the-stack
train
b84f6316c94207fd07fd7219
train
function
def test_list_game_server_deployments( transport: str = "grpc", request_type=game_server_deployments.ListGameServerDeploymentsRequest, ): client = GameServerDeploymentsServiceClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as...
def test_list_game_server_deployments( transport: str = "grpc", request_type=game_server_deployments.ListGameServerDeploymentsRequest, ):
client = GameServerDeploymentsServiceClient( credentials=credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, # and we are mocking out the actual API, so just send an empty request. request = request_type() # ...
_transport.assert_called_once_with( credentials=None, credentials_file=None, host="squid.clam.whelk", scopes=None, api_mtls_endpoint="squid.clam.whelk", client_cert_source=None, quota_project_id=None, ) def test_list_game_server...
92
92
307
34
58
Yingxin-Jiang/python-game-servers
tests/unit/gapic/gaming_v1/test_game_server_deployments_service.py
Python
test_list_game_server_deployments
test_list_game_server_deployments
386
420
386
389
028563db716ef6fce7dda0b4da9645f116be8d81
bigcode/the-stack
train
10d137245fc0e559186c8f34
train
function
def test_get_game_server_deployment_rollout_flattened(): client = GameServerDeploymentsServiceClient( credentials=credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client._transport.get_game_server_deplo...
def test_get_game_server_deployment_rollout_flattened():
client = GameServerDeploymentsServiceClient( credentials=credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client._transport.get_game_server_deployment_rollout), "__call__" ) as call: # Desig...
assert args[0] == request # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] def test_get_game_server_deployment_rollout_flattened():
63
64
200
13
50
Yingxin-Jiang/python-game-servers
tests/unit/gapic/gaming_v1/test_game_server_deployments_service.py
Python
test_get_game_server_deployment_rollout_flattened
test_get_game_server_deployment_rollout_flattened
1,845
1,866
1,845
1,845
f84bb14cd1eaf4d2f7f86a7ccab1e41fe6a1ed34
bigcode/the-stack
train
d8dff659ce950927aa19ec5a
train
function
def test_game_server_deployments_service_host_no_port(): client = GameServerDeploymentsServiceClient( credentials=credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="gameservices.googleapis.com" ), ) assert client._transport._hos...
def test_game_server_deployments_service_host_no_port():
client = GameServerDeploymentsServiceClient( credentials=credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="gameservices.googleapis.com" ), ) assert client._transport._host == "gameservices.googleapis.com:443"
Transport( host="squid.clam.whelk", quota_project_id="octopus" ) adc.assert_called_once_with( scopes=("https://www.googleapis.com/auth/cloud-platform",), quota_project_id="octopus", ) def test_game_server_deployments_service_host_no_port():
64
64
68
12
52
Yingxin-Jiang/python-game-servers
tests/unit/gapic/gaming_v1/test_game_server_deployments_service.py
Python
test_game_server_deployments_service_host_no_port
test_game_server_deployments_service_host_no_port
2,605
2,612
2,605
2,605
3018fca2e49555fa8fba8eb829b58e46fcc081a1
bigcode/the-stack
train
70c70887af85f0aa152e19d0
train
function
def test_game_server_deployments_service_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( auth, "load_credentials_from_file" ) as load_creds, mock.patch( "google.cloud.gaming_v1.services.game_server_deployments_service.t...
def test_game_server_deployments_service_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file
with mock.patch.object( auth, "load_credentials_from_file" ) as load_creds, mock.patch( "google.cloud.gaming_v1.services.game_server_deployments_service.transports.GameServerDeploymentsServiceTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None load...
request=object()) # Additionally, the LRO client (a property) should # also raise NotImplementedError with pytest.raises(NotImplementedError): transport.operations_client def test_game_server_deployments_service_base_transport_with_credentials_file(): # Instantiate the base transport with a cre...
64
64
170
25
38
Yingxin-Jiang/python-game-servers
tests/unit/gapic/gaming_v1/test_game_server_deployments_service.py
Python
test_game_server_deployments_service_base_transport_with_credentials_file
test_game_server_deployments_service_base_transport_with_credentials_file
2,561
2,577
2,561
2,562
140d85a3bcc5d1f43ac8292be4b813a6389d6a9b
bigcode/the-stack
train
291f41a95d18e00e0abfaec8
train
function
@pytest.mark.asyncio async def test_get_game_server_deployment_flattened_error_async(): client = GameServerDeploymentsServiceAsyncClient( credentials=credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytes...
@pytest.mark.asyncio async def test_get_game_server_deployment_flattened_error_async():
client = GameServerDeploymentsServiceAsyncClient( credentials=credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): await client.get_game_server_deployment( game_...
underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] assert args[0].name == "name_value" @pytest.mark.asyncio async def test_get_game_server_deployment_flattened_error_async():
64
64
98
19
45
Yingxin-Jiang/python-game-servers
tests/unit/gapic/gaming_v1/test_game_server_deployments_service.py
Python
test_get_game_server_deployment_flattened_error_async
test_get_game_server_deployment_flattened_error_async
1,002
1,013
1,002
1,003
4e1a0c5e44d737f89fce56e5a93c3d9e7bcf6a78
bigcode/the-stack
train
4ad399f47ab19df9463ab4cb
train
function
@pytest.mark.asyncio async def test_delete_game_server_deployment_flattened_async(): client = GameServerDeploymentsServiceAsyncClient( credentials=credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client...
@pytest.mark.asyncio async def test_delete_game_server_deployment_flattened_async():
client = GameServerDeploymentsServiceAsyncClient( credentials=credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client._client._transport.delete_game_server_deployment), "__call__" ) as call: ...
with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.delete_game_server_deployment( game_server_deployments.DeleteGameServerDeploymentRequest(), name="name_value", ) @pytest.mark.asyncio async def test_delete_game_server_d...
68
68
228
18
50
Yingxin-Jiang/python-game-servers
tests/unit/gapic/gaming_v1/test_game_server_deployments_service.py
Python
test_delete_game_server_deployment_flattened_async
test_delete_game_server_deployment_flattened_async
1,413
1,438
1,413
1,414
dcf5a198d20ba034bf3c8854419c1979b9fbb4f3
bigcode/the-stack
train
e748ad1945d627d2ad23e864
train
function
@pytest.mark.asyncio async def test_get_game_server_deployment_flattened_async(): client = GameServerDeploymentsServiceAsyncClient( credentials=credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client._c...
@pytest.mark.asyncio async def test_get_game_server_deployment_flattened_async():
client = GameServerDeploymentsServiceAsyncClient( credentials=credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client._client._transport.get_game_server_deployment), "__call__" ) as call: # ...
method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.get_game_server_deployment( game_server_deployments.GetGameServerDeploymentRequest(), name="name_value", ) @pytest.mark.asyncio async def test_get_game_server_deployment_flat...
68
68
227
18
50
Yingxin-Jiang/python-game-servers
tests/unit/gapic/gaming_v1/test_game_server_deployments_service.py
Python
test_get_game_server_deployment_flattened_async
test_get_game_server_deployment_flattened_async
974
999
974
975
ca9bb7eec0355cd4b341fe139aad8dafb5ce41ad
bigcode/the-stack
train