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
59cf224c1451623e5bfdcd94
train
function
def test_audio_created(audio): assert audio is not None
def test_audio_created(audio):
assert audio is not None
_video_ids(video, video_content_id, video_node_id): assert video.content_id == video_content_id assert video.node_id == video_node_id def test_video_to_dict(video, video_json): assert video.to_dict() == video_json """ *********** AUDIO TESTS *********** """ def test_audio_created(audio):
64
64
12
6
58
radinamatic/ricecooker
tests/test_classes.py
Python
test_audio_created
test_audio_created
395
396
395
395
2188c3ca4786bb83810b1192d082576783370e52
bigcode/the-stack
train
60f10f8deee4536d96c2e395
train
function
@pytest.fixture def root_content_id(channel, channel_internal_domain): return uuid.uuid5(channel_internal_domain, channel.id.hex)
@pytest.fixture def root_content_id(channel, channel_internal_domain):
return uuid.uuid5(channel_internal_domain, channel.id.hex)
channel_uuid): return { "name" : channel_data['title'], "id" : channel_uuid.hex, "thumbnail" : channel.thumbnail, "has_changed" : True, "description" : channel.description, } @pytest.fixture def root_content_id(channel, channel_internal_domain):
64
64
25
13
51
radinamatic/ricecooker
tests/test_classes.py
Python
root_content_id
root_content_id
52
54
52
53
06dc768fa47937fe09b368e4b7da0fd8728893e8
bigcode/the-stack
train
150c5e19642f0a62a102f8c8
train
function
@pytest.fixture def exercise_data(exercise_id): return { "title": "exercise node test", "description": None, "id" : exercise_id, "author": None, "license": constants.L_PD, }
@pytest.fixture def exercise_data(exercise_id):
return { "title": "exercise node test", "description": None, "id" : exercise_id, "author": None, "license": constants.L_PD, }
.fixture def exercise_content_id(channel_internal_domain, exercise_id): return uuid.uuid5(channel_internal_domain, exercise_id) @pytest.fixture def exercise_node_id(topic_node_id, exercise_content_id): return uuid.uuid5(topic_node_id, exercise_content_id.hex) @pytest.fixture def exercise_data(exercise_id):
64
64
52
10
54
radinamatic/ricecooker
tests/test_classes.py
Python
exercise_data
exercise_data
280
288
280
281
3abcda27ffd396bf53165561fc51a874570c2faf
bigcode/the-stack
train
fa580a883c70bd3025ce9403
train
function
@pytest.fixture def exercise_node_id(topic_node_id, exercise_content_id): return uuid.uuid5(topic_node_id, exercise_content_id.hex)
@pytest.fixture def exercise_node_id(topic_node_id, exercise_content_id):
return uuid.uuid5(topic_node_id, exercise_content_id.hex)
EXERCISE FIXTURES *********** """ @pytest.fixture def exercise_id(): return "exercise-id" @pytest.fixture def exercise_content_id(channel_internal_domain, exercise_id): return uuid.uuid5(channel_internal_domain, exercise_id) @pytest.fixture def exercise_node_id(topic_node_id, exercise_content_id):
64
64
29
15
49
radinamatic/ricecooker
tests/test_classes.py
Python
exercise_node_id
exercise_node_id
276
278
276
277
809c10025249bc0674806b5ec492336ec8a9ce55
bigcode/the-stack
train
b2de8aad01d0d77395ee47ce
train
function
@pytest.fixture def topic_id(): return "topic-id"
@pytest.fixture def topic_id():
return "topic-id"
root_content_id(channel, channel_internal_domain): return uuid.uuid5(channel_internal_domain, channel.id.hex) @pytest.fixture def root_node_id(channel, root_content_id): return uuid.uuid5(channel.id, root_content_id.hex) """ *********** TOPIC FIXTURES *********** """ @pytest.fixture def topic_id():
64
64
13
7
57
radinamatic/ricecooker
tests/test_classes.py
Python
topic_id
topic_id
63
65
63
64
776560790b7f1335df0e3c2cb2d2ee0ca261c599
bigcode/the-stack
train
7ddde6d8f7d1733e279cdcb7
train
function
def test_exercise_data(exercise, exercise_data): assert exercise.id == exercise_data['id'] assert exercise.title == exercise_data['title'] assert exercise.description == exercise_data['description'] assert exercise.author == exercise_data['author'] assert exercise.license == exercise_data['license'] assert exerci...
def test_exercise_data(exercise, exercise_data):
assert exercise.id == exercise_data['id'] assert exercise.title == exercise_data['title'] assert exercise.description == exercise_data['description'] assert exercise.author == exercise_data['author'] assert exercise.license == exercise_data['license'] assert exercise.kind == constants.CK_EXERCISE
document.node_id == document_node_id def test_document_to_dict(document, document_json): assert document.to_dict() == document_json """ *********** EXERCISE TESTS *********** """ def test_exercise_created(exercise): assert exercise is not None def test_exercise_data(exercise, exercise_data):
64
64
69
11
52
radinamatic/ricecooker
tests/test_classes.py
Python
test_exercise_data
test_exercise_data
446
452
446
446
953c2fb585c5b0d4e228f5f24c90958ed6328f61
bigcode/the-stack
train
bccb7d747a090d566de8a0e7
train
function
@pytest.fixture def channel_data(channel_id, channel_domain): return { "domain" : channel_domain, "channel_id" : channel_id, "title" : "Sample Channel", }
@pytest.fixture def channel_data(channel_id, channel_domain):
return { "domain" : channel_domain, "channel_id" : channel_id, "title" : "Sample Channel", }
_domain(channel_domain): return uuid.uuid5(uuid.NAMESPACE_DNS, channel_domain) @pytest.fixture def channel_uuid(channel_id): return uuid.uuid3(uuid.NAMESPACE_DNS, uuid.uuid5(uuid.NAMESPACE_DNS, channel_id).hex) @pytest.fixture def channel_data(channel_id, channel_domain):
64
64
44
12
52
radinamatic/ricecooker
tests/test_classes.py
Python
channel_data
channel_data
26
32
26
27
7d359853c57ba034c1ddb2cbb761749e6186b50c
bigcode/the-stack
train
bfdf1498962c5c208da46984
train
function
def test_exercise_to_dict(exercise, exercise_json): assert exercise.to_dict() == exercise_json
def test_exercise_to_dict(exercise, exercise_json):
assert exercise.to_dict() == exercise_json
reset(exercise): assert exercise.default_preset == constants.FP_EXERCISE def test_exercise_ids(exercise, exercise_content_id, exercise_node_id): assert exercise.content_id == exercise_content_id assert exercise.node_id == exercise_node_id def test_exercise_to_dict(exercise, exercise_json):
64
64
21
12
51
radinamatic/ricecooker
tests/test_classes.py
Python
test_exercise_to_dict
test_exercise_to_dict
461
462
461
461
13d475f64e1932fa2b47d81c63302925c9654e1d
bigcode/the-stack
train
977786200c5770725d62a7a4
train
function
def test_channel_data(channel, channel_data, channel_uuid): assert channel.domain == channel_data['domain'] assert channel.name == channel_data['title'] assert channel.id == channel_uuid
def test_channel_data(channel, channel_data, channel_uuid):
assert channel.domain == channel_data['domain'] assert channel.name == channel_data['title'] assert channel.id == channel_uuid
children": [], "files": [], "kind": constants.CK_EXERCISE, "license": exercise_data['license'], } """ *********** CHANNEL TESTS *********** """ def test_channel_created(channel): assert channel is not None def test_channel_data(channel, channel_data, channel_uuid):
64
64
37
12
51
radinamatic/ricecooker
tests/test_classes.py
Python
test_channel_data
test_channel_data
323
326
323
323
bc07e1afd8f0646e4284786760d2b2373854036f
bigcode/the-stack
train
30ae06b7bbc197d3cad29d9c
train
function
@pytest.fixture def root_node_id(channel, root_content_id): return uuid.uuid5(channel.id, root_content_id.hex)
@pytest.fixture def root_node_id(channel, root_content_id):
return uuid.uuid5(channel.id, root_content_id.hex)
"thumbnail" : channel.thumbnail, "has_changed" : True, "description" : channel.description, } @pytest.fixture def root_content_id(channel, channel_internal_domain): return uuid.uuid5(channel_internal_domain, channel.id.hex) @pytest.fixture def root_node_id(channel, root_content_id):
64
64
25
13
51
radinamatic/ricecooker
tests/test_classes.py
Python
root_node_id
root_node_id
56
58
56
57
58269db52f656be2dd2fe64e7ddea30812d337fc
bigcode/the-stack
train
21c03d16878bbee6b53f1aa4
train
function
def test_channel_created(channel): assert channel is not None
def test_channel_created(channel):
assert channel is not None
, "content_id": exercise_content_id.hex, "author": "", "children": [], "files": [], "kind": constants.CK_EXERCISE, "license": exercise_data['license'], } """ *********** CHANNEL TESTS *********** """ def test_channel_created(channel):
64
64
12
6
58
radinamatic/ricecooker
tests/test_classes.py
Python
test_channel_created
test_channel_created
320
321
320
320
5a87ccc842d8ba13e90cb1c8a06ab62513316b13
bigcode/the-stack
train
2600327d088df6d74652004f
train
function
@pytest.fixture def topic_json(topic_data, topic_content_id, topic_node_id): return { "id" : topic_data['id'], "title": topic_data['title'], "description": "", "node_id": topic_node_id.hex, "content_id": topic_content_id.hex, "author": "", "files": [], ...
@pytest.fixture def topic_json(topic_data, topic_content_id, topic_node_id):
return { "id" : topic_data['id'], "title": topic_data['title'], "description": "", "node_id": topic_node_id.hex, "content_id": topic_content_id.hex, "author": "", "files": [], "kind": constants.CK_TOPIC, "license": None, }
topic_data['id'], description=topic_data['description'], title=topic_data['title'], author=topic_data['author'] ) node.set_ids(channel_internal_domain, root_node_id) return node @pytest.fixture def topic_json(topic_data, topic_content_id, topic_node_id):
64
64
91
17
46
radinamatic/ricecooker
tests/test_classes.py
Python
topic_json
topic_json
95
107
95
96
b11f0037b98c68de8573ce070e34aaba95cf4b77
bigcode/the-stack
train
13681e608a0e7becf4a8b3b8
train
function
@pytest.fixture def video(video_data, channel_internal_domain, topic_node_id): node = Video( id=video_data['id'], description=video_data['description'], title=video_data['title'], author=video_data['author'], transcode_to_lower_resolutions=True, derive_thumbnail=True, license=video_data['license'], )...
@pytest.fixture def video(video_data, channel_internal_domain, topic_node_id):
node = Video( id=video_data['id'], description=video_data['description'], title=video_data['title'], author=video_data['author'], transcode_to_lower_resolutions=True, derive_thumbnail=True, license=video_data['license'], ) node.set_ids(channel_internal_domain, topic_node_id) return node
def video_data(video_id): return { "title": "video node test", "description": None, "id" : video_id, "author": None, "license": constants.L_PD, } @pytest.fixture def video(video_data, channel_internal_domain, topic_node_id):
64
64
96
16
48
radinamatic/ricecooker
tests/test_classes.py
Python
video
video
132
144
132
133
492f4cbe0fd157cf9ed538c2f4a53692b7da434c
bigcode/the-stack
train
910839f729c11152c2347e45
train
function
def test_video_default_preset(video): assert video.default_preset == constants.FP_VIDEO_HIGH_RES
def test_video_default_preset(video):
assert video.default_preset == constants.FP_VIDEO_HIGH_RES
): assert video.id == video_data['id'] assert video.title == video_data['title'] assert video.description == video_data['description'] assert video.author == video_data['author'] assert video.license == video_data['license'] assert video.kind == constants.CK_VIDEO def test_video_default_preset(video):
64
64
21
8
55
radinamatic/ricecooker
tests/test_classes.py
Python
test_video_default_preset
test_video_default_preset
376
377
376
376
105f029a33a204d38a6962ff3d5d03316a694d3f
bigcode/the-stack
train
a18086cc7a0f86a709f1a68a
train
function
@pytest.fixture def audio(audio_data, channel_internal_domain, topic_node_id): node = Audio( id=audio_data['id'], description=audio_data['description'], title=audio_data['title'], author=audio_data['author'], license=audio_data['license'], ) node.set_ids(channel_internal_domain, topic_node_id) re...
@pytest.fixture def audio(audio_data, channel_internal_domain, topic_node_id):
node = Audio( id=audio_data['id'], description=audio_data['description'], title=audio_data['title'], author=audio_data['author'], license=audio_data['license'], ) node.set_ids(channel_internal_domain, topic_node_id) return node
def audio_data(audio_id): return { "title": "audio node test", "description": None, "id" : audio_id, "author": None, "license": constants.L_PD, } @pytest.fixture def audio(audio_data, channel_internal_domain, topic_node_id):
64
64
81
16
48
radinamatic/ricecooker
tests/test_classes.py
Python
audio
audio
186
196
186
187
7b3fcf4735ae34ed25ea5a98115a2c355f662ed8
bigcode/the-stack
train
2dda11cb33d5c2846706f31b
train
function
def test_topic_ids(topic, topic_content_id, topic_node_id): assert topic.content_id == topic_content_id assert topic.node_id == topic_node_id
def test_topic_ids(topic, topic_content_id, topic_node_id):
assert topic.content_id == topic_content_id assert topic.node_id == topic_node_id
(topic, topic_data): assert topic.id == topic_data['id'] assert topic.title == topic_data['title'] assert topic.description == topic_data['description'] assert topic.author == topic_data['author'] assert topic.kind == constants.CK_TOPIC def test_topic_ids(topic, topic_content_id, topic_node_id):
64
64
32
14
49
radinamatic/ricecooker
tests/test_classes.py
Python
test_topic_ids
test_topic_ids
347
349
347
347
050f16d7baf15e87b28c8b5f0885570a9e4fa139
bigcode/the-stack
train
8dfb90528bbca5aee225f848
train
function
def test_exercise_ids(exercise, exercise_content_id, exercise_node_id): assert exercise.content_id == exercise_content_id assert exercise.node_id == exercise_node_id
def test_exercise_ids(exercise, exercise_content_id, exercise_node_id):
assert exercise.content_id == exercise_content_id assert exercise.node_id == exercise_node_id
author'] assert exercise.license == exercise_data['license'] assert exercise.kind == constants.CK_EXERCISE def test_exercise_default_preset(exercise): assert exercise.default_preset == constants.FP_EXERCISE def test_exercise_ids(exercise, exercise_content_id, exercise_node_id):
64
64
34
16
47
radinamatic/ricecooker
tests/test_classes.py
Python
test_exercise_ids
test_exercise_ids
457
459
457
457
cd8ba6d10d28d8efd60518c6ed2698a897cd63e5
bigcode/the-stack
train
205709b1d32491f5925667ee
train
function
@pytest.fixture def document_json(document_data, document_content_id, document_node_id): return { "id" : document_data['id'], "title": document_data['title'], "description": "", "node_id": document_node_id.hex, "content_id": document_content_id.hex, "author": "", ...
@pytest.fixture def document_json(document_data, document_content_id, document_node_id):
return { "id" : document_data['id'], "title": document_data['title'], "description": "", "node_id": document_node_id.hex, "content_id": document_content_id.hex, "author": "", "children": [], "files": [], "kind": constants.CK_DOCUMENT, "...
description=document_data['description'], title=document_data['title'], author=document_data['author'], license=document_data['license'], ) node.set_ids(channel_internal_domain, root_node_id) return node @pytest.fixture def document_json(document_data, document_content_id, document_node_id):
64
64
99
17
46
radinamatic/ricecooker
tests/test_classes.py
Python
document_json
document_json
250
263
250
251
07d1d115e3819ab1fcacdcb959cd72a2efd3d9f5
bigcode/the-stack
train
9f42d38e8f4b8f2d77a83674
train
function
def test_video_ids(video, video_content_id, video_node_id): assert video.content_id == video_content_id assert video.node_id == video_node_id
def test_video_ids(video, video_content_id, video_node_id):
assert video.content_id == video_content_id assert video.node_id == video_node_id
constants.CK_VIDEO def test_video_default_preset(video): assert video.default_preset == constants.FP_VIDEO_HIGH_RES def test_video_derive_thumbnail(video): assert True def test_video_transcode_to_lower_resolution(video): assert True def test_video_ids(video, video_content_id, video_node_id):
64
64
32
14
49
radinamatic/ricecooker
tests/test_classes.py
Python
test_video_ids
test_video_ids
385
387
385
385
40b11ae790498c5f8ec051d1ba2f07eabd317ad8
bigcode/the-stack
train
94107c8a96902c420d8ef6d5
train
function
@pytest.fixture def topic(topic_data, channel_internal_domain, root_node_id): node = Topic( id=topic_data['id'], description=topic_data['description'], title=topic_data['title'], author=topic_data['author'] ) node.set_ids(channel_internal_domain, root_node_id) return node...
@pytest.fixture def topic(topic_data, channel_internal_domain, root_node_id):
node = Topic( id=topic_data['id'], description=topic_data['description'], title=topic_data['title'], author=topic_data['author'] ) node.set_ids(channel_internal_domain, root_node_id) return node
topic_content_id.hex) @pytest.fixture def topic_data(topic_id): return { "title": "topic node test", "description": None, "id" : topic_id, "author": None, } @pytest.fixture def topic(topic_data, channel_internal_domain, root_node_id):
64
64
71
16
48
radinamatic/ricecooker
tests/test_classes.py
Python
topic
topic
84
93
84
85
c337cb4ef27e5719897250a536df5b1c83f3f1b1
bigcode/the-stack
train
53cd0604ec0d9767b959bbaf
train
function
def main(): # Example adapted from http://lxml.de/validation.html#id2 # Schema f = io.StringIO('''\ <schema xmlns="http://purl.oclc.org/dsdl/schematron" > <pattern id="sum_equals_100_percent"> <title>Sum equals 100%.</title> <rule context="Total"> <assert test="sum(//Percent)=100">Sum i...
def main(): # Example adapted from http://lxml.de/validation.html#id2 # Schema
f = io.StringIO('''\ <schema xmlns="http://purl.oclc.org/dsdl/schematron" > <pattern id="sum_equals_100_percent"> <title>Sum equals 100%.</title> <rule context="Total"> <assert test="sum(//Percent)=100">Sum is not 100%.</assert> </rule> </pattern> </schema> ''') # Parse sche...
be placed into the sub-folder called documentation within the Information Package folder and/or the representation folder # #CSIP17: Implementers CAN add any other folders either into the Information Package folder or the representation folder import io from lxml import isoschematron from lxml import etree def main()...
86
86
288
24
61
DILCISBoard/py-ip-validator
metsvalidator/MetsValidator.py
Python
main
main
51
90
51
54
375d2088d8f3b1f0499e74f85e9a27dc02f697af
bigcode/the-stack
train
fbb6d1342f964f8a2a466196
train
class
class TestTapeDriveDevice(unittest.TestCase): """TapeDriveDevice unit test stubs""" def setUp(self): pass def tearDown(self): pass def testTapeDriveDevice(self): """Test TapeDriveDevice""" # FIXME: construct object with mandatory attributes with example values ...
class TestTapeDriveDevice(unittest.TestCase):
"""TapeDriveDevice unit test stubs""" def setUp(self): pass def tearDown(self): pass def testTapeDriveDevice(self): """Test TapeDriveDevice""" # FIXME: construct object with mandatory attributes with example values # model = nodeum_sdk.models.tape_drive_device....
by: https://openapi-generator.tech """ from __future__ import absolute_import import unittest import nodeum_sdk from nodeum_sdk.models.tape_drive_device import TapeDriveDevice # noqa: E501 from nodeum_sdk.rest import ApiException class TestTapeDriveDevice(unittest.TestCase):
64
64
92
9
54
nodeum-io/nodeum-sdk-python
test/test_tape_drive_device.py
Python
TestTapeDriveDevice
TestTapeDriveDevice
22
35
22
22
76ed2a5fe628e6b0fbe1d92d13ea6bc5d4cbc0d7
bigcode/the-stack
train
c9c307c581535c0f2b08fcf3
train
class
class ContractParty(FhirBackboneElementBase): """ Contract.Party Legally enforceable, formally recorded unilateral or bilateral directive i.e., a policy or agreement. """ # noinspection PyPep8Naming def __init__( self, *, id_: Optional[FhirString] = None, ext...
class ContractParty(FhirBackboneElementBase):
""" Contract.Party Legally enforceable, formally recorded unilateral or bilateral directive i.e., a policy or agreement. """ # noinspection PyPep8Naming def __init__( self, *, id_: Optional[FhirString] = None, extension: Optional[FhirList[ExtensionBase]] = No...
from spark_auto_mapper_fhir.resources.device import Device from spark_auto_mapper_fhir.resources.group import Group from spark_auto_mapper_fhir.resources.organization import Organization # role (CodeableConcept) from spark_auto_mapper_fhir.complex_types.codeable_concept import CodeableConcept # E...
151
151
504
10
140
icanbwell/SparkAutoMapper.FHIR
spark_auto_mapper_fhir/backbone_elements/contract_party.py
Python
ContractParty
ContractParty
43
103
43
43
0e95594d5263b3df249067e71e9c321a83446baa
bigcode/the-stack
train
15425e6ee25b7d6427eff73d
train
class
class TestAPIShim(WithCreateBarData, WithMakeAlgo, ZiplineTestCase): START_DATE = pd.Timestamp("2016-01-05", tz='UTC') END_DATE = pd.Timestamp("2016-01-28", tz='UTC') SIM_PARAMS_DATA_FREQUENCY = 'minute' sids = ASSET_FINDER_EQUITY_SIDS = 1, 2, 3 @classmethod ...
class TestAPIShim(WithCreateBarData, WithMakeAlgo, ZiplineTestCase):
START_DATE = pd.Timestamp("2016-01-05", tz='UTC') END_DATE = pd.Timestamp("2016-01-28", tz='UTC') SIM_PARAMS_DATA_FREQUENCY = 'minute' sids = ASSET_FINDER_EQUITY_SIDS = 1, 2, 3 @classmethod def make_equity_minute_bar_data(cls): for sid in cls.sids: yield sid, create_minute_...
handle_data(context, data): assert len(data) == 2 assert len(data.keys()) == 2 assert context.asset1 in data.keys() assert context.asset2 in data.keys() """ sid_accessor_algo = """ from zipline.api import sid def initialize(context): context.asset1 = sid(1) def handle_data(context,data): ass...
256
256
3,405
21
235
leonarduschen/zipline
tests/test_api_shim.py
Python
TestAPIShim
TestAPIShim
131
564
131
134
b6a10a67b4e0b9c8f87216379c500f7022e98e61
bigcode/the-stack
train
d85d296f885efa876e90e3f5
train
function
@dp.message_handler(commands=["lang"]) async def cmd_lang(message: Message) -> None: """Handles the "/lang" command from a Telegram user. Allows the user to change the locale from the chosen one. Outputs the message in the language that was initially chosen by the user. Args: message (Messag...
@dp.message_handler(commands=["lang"]) async def cmd_lang(message: Message) -> None:
"""Handles the "/lang" command from a Telegram user. Allows the user to change the locale from the chosen one. Outputs the message in the language that was initially chosen by the user. Args: message (Message): User's Telegram message that is sent to the bot. """ query = "SELECT lo...
�🇺 Русский", callback_data="lang_ru") inline_kb = InlineKeyboardMarkup().add(btn_en, btn_ru) await bot.send_message(message.chat.id, str_greet, reply_markup=inline_kb) logger.info("User {} called /start", message.from_user.id) @dp.message_handler(commands=["lang"]) async def cmd_lang(message: Message...
83
83
279
20
63
gevartrix/qr-notify-bot
handlers/general.py
Python
cmd_lang
cmd_lang
33
59
33
34
dcb345055ce064d21965a90788650eb0e530350e
bigcode/the-stack
train
3aa28db1e2205c4944a55a81
train
function
@dp.callback_query_handler(lambda c: c.data.startswith("lang")) async def set_lang(cb_query: CallbackQuery) -> None: """Handles the callback that sets the user preferred locale. Updates the locale in the table. Args: cb_query (CallbackQuery): User's Telegram callback query that is sent to the bot...
@dp.callback_query_handler(lambda c: c.data.startswith("lang")) async def set_lang(cb_query: CallbackQuery) -> None:
"""Handles the callback that sets the user preferred locale. Updates the locale in the table. Args: cb_query (CallbackQuery): User's Telegram callback query that is sent to the bot. """ lang = "en_US" if cb_query.data.endswith("en") else "ru_RU" info = "Setting your language..." if...
KeyboardButton("🇷🇺 Русский", callback_data="lang_ru") inline_kb = InlineKeyboardMarkup().add(btn_en, btn_ru) await bot.send_message(message.chat.id, str_lang, reply_markup=inline_kb) logger.info("User {} called /lang", message.from_user.id) @dp.callback_query_handler(lambda c: c.data.startswith("lang...
93
93
311
27
66
gevartrix/qr-notify-bot
handlers/general.py
Python
set_lang
set_lang
62
99
62
63
b54d32665ae5a821dad5c560c5fcce3f5fd95aab
bigcode/the-stack
train
916276399ebd853c8b971188
train
function
@dp.message_handler(commands=["start"]) async def cmd_start(message: Message) -> None: """Handles the "/start" command from a Telegram user. Runs when the user first starts the bot. Greets the user by his/her full name and allows to choose the interface language. Args: message (Message): Use...
@dp.message_handler(commands=["start"]) async def cmd_start(message: Message) -> None:
"""Handles the "/start" command from a Telegram user. Runs when the user first starts the bot. Greets the user by his/her full name and allows to choose the interface language. Args: message (Message): User's Telegram message that is sent to the bot. """ str_greet = constants.MSG_S...
Query, InlineKeyboardButton, InlineKeyboardMarkup, Message, ) from loguru import logger from . import constants from core import config from core.misc import bot, conn, curs, dp @dp.message_handler(commands=["start"]) async def cmd_start(message: Message) -> None:
64
64
192
20
43
gevartrix/qr-notify-bot
handlers/general.py
Python
cmd_start
cmd_start
15
30
15
16
0a5620c41802e33f5132ff14ea8041a58ad93b06
bigcode/the-stack
train
176f8c25ee8a9f63d898f07c
train
function
def start(): global video global salida def seleccionar_video(): global video a = serialEntry.get() video = a print(video) def guardar_video(): global salida a = serialEntry2.get() salida = a print(salida) def iniciar(): virtua...
def start():
global video global salida def seleccionar_video(): global video a = serialEntry.get() video = a print(video) def guardar_video(): global salida a = serialEntry2.get() salida = a print(salida) def iniciar(): virtual_session = o...
"" root.title("VisionRex") root.geometry("650x400") #"#32afb5" root.configure(bg="white") imagen = Image.open("./data/logo-visionrex.png") imagen = imagen.resize((200,100)) #imagen.save("ProyectosconPython_resize.png") img = ImageTk.PhotoImage(imagen) label1 = tk.Label(root, image=img) label1.place(x=240, y=0) def sta...
93
93
312
3
90
rodrigo203203/person_track_yolo_detection
interfaz.py
Python
start
start
17
48
17
17
b351279ebf5c21a7806b2c35258a6ea680922acb
bigcode/the-stack
train
4940767045ef6140b860aced
train
class
class RaspberryPiPinFactory: def __init__(self): GPIO.setmode(GPIO.BOARD) def close(self): GPIO.cleanup() def create_input(self, pin): return RaspberryPiInputPin(pin) def create_output(self, pin): return RaspberryPiOutputPin(pin)
class RaspberryPiPinFactory:
def __init__(self): GPIO.setmode(GPIO.BOARD) def close(self): GPIO.cleanup() def create_input(self, pin): return RaspberryPiInputPin(pin) def create_output(self, pin): return RaspberryPiOutputPin(pin)
0 and value != 1: raise ValueError( 'Pin value must be 0 or 1 but got {0}'.format(value)) gpio_value = GPIO.LOW if value == 0 else GPIO.HIGH GPIO.output(self.pin, gpio_value) class RaspberryPiPinFactory:
64
64
63
6
58
daoo/autodesk
autodesk/hardware/raspberrypi.py
Python
RaspberryPiPinFactory
RaspberryPiPinFactory
28
39
28
28
bc17aac84947d0e7778b3950925e9cf8b3853a6f
bigcode/the-stack
train
3a3bec47925ae77f8da8b592
train
class
class RaspberryPiOutputPin: def __init__(self, pin): self.pin = pin GPIO.setup(self.pin, GPIO.OUT) def write(self, value): if value != 0 and value != 1: raise ValueError( 'Pin value must be 0 or 1 but got {0}'.format(value)) gpio_value = GPIO.LOW if v...
class RaspberryPiOutputPin:
def __init__(self, pin): self.pin = pin GPIO.setup(self.pin, GPIO.OUT) def write(self, value): if value != 0 and value != 1: raise ValueError( 'Pin value must be 0 or 1 but got {0}'.format(value)) gpio_value = GPIO.LOW if value == 0 else GPIO.HIGH ...
def __init__(self, pin): self.pin = pin GPIO.setup(self.pin, GPIO.IN) def read(self): gpio_value = GPIO.input(self.pin) value = 1 if gpio_value == GPIO.HIGH else 0 return value class RaspberryPiOutputPin:
64
64
99
6
57
daoo/autodesk
autodesk/hardware/raspberrypi.py
Python
RaspberryPiOutputPin
RaspberryPiOutputPin
15
25
15
15
9d438e9c14670132050b825b792c0c0d3460523f
bigcode/the-stack
train
bb78dfed75cf53cbd1b89657
train
class
class RaspberryPiInputPin: def __init__(self, pin): self.pin = pin GPIO.setup(self.pin, GPIO.IN) def read(self): gpio_value = GPIO.input(self.pin) value = 1 if gpio_value == GPIO.HIGH else 0 return value
class RaspberryPiInputPin:
def __init__(self, pin): self.pin = pin GPIO.setup(self.pin, GPIO.IN) def read(self): gpio_value = GPIO.input(self.pin) value = 1 if gpio_value == GPIO.HIGH else 0 return value
import RPi.GPIO as GPIO class RaspberryPiInputPin:
13
64
64
6
6
daoo/autodesk
autodesk/hardware/raspberrypi.py
Python
RaspberryPiInputPin
RaspberryPiInputPin
4
12
4
4
9808cffedd9b0779a605764adf1fcf61e67833ed
bigcode/the-stack
train
3d4363d9c074e412d9917c05
train
function
def create_makefile(choice_dict): f = open(f"{cwd}/makefile",'w') f.write(".PHONY = help setup test run clean environment\n\n") f.write(".DEFAULT_GOAL = setup\n") f.write("setup:\n") for batch_size in [64, 128, 1024, 4096]: for lr_choices in choice_dict['learning_rate']: f.write...
def create_makefile(choice_dict):
f = open(f"{cwd}/makefile",'w') f.write(".PHONY = help setup test run clean environment\n\n") f.write(".DEFAULT_GOAL = setup\n") f.write("setup:\n") for batch_size in [64, 128, 1024, 4096]: for lr_choices in choice_dict['learning_rate']: f.write(f"\t@python main_synthetic.py --l...
import os import numpy as np cwd = os.getcwd() # get the current working directory def create_makefile(choice_dict):
28
64
116
7
20
PierBeneventano/test_pytorch
make_makefile_3b.py
Python
create_makefile
create_makefile
5
13
5
5
d464073d28fd0331053ae0dbfaa9eddbef1b98de
bigcode/the-stack
train
02967a8b0bf74d16794e18ff
train
function
def forbidden_response(): """Creates a simple forbidden status response.""" return Response(status=403)
def forbidden_response():
"""Creates a simple forbidden status response.""" return Response(status=403)
image.""" data = bwr_bytes(image) buffer = BytesIO(data) return send_file(buffer, mimetype='application/octet-stream', cache_timeout=0) def text_response(text): """Creates a Flask text response.""" return Response(text, mimetype='text/plain') def forbidden_response():
64
64
20
4
60
NeilBetham/accent
server/response.py
Python
forbidden_response
forbidden_response
61
64
61
61
8f739fb8ed960a96a46439da671942153468b7a7
bigcode/the-stack
train
0205b55f27a0b1a39ab19b6e
train
function
def settings_response(key, image_func, width, height): """Creates an image response to start the new user flow.""" # Draw the image with the link text and a computer. image = Image.new(mode='RGB', size=(width, height), color=BACKGROUND_COLOR) draw_text(settings_url(key), font_spec=SUBVARI...
def settings_response(key, image_func, width, height):
"""Creates an image response to start the new user flow.""" # Draw the image with the link text and a computer. image = Image.new(mode='RGB', size=(width, height), color=BACKGROUND_COLOR) draw_text(settings_url(key), font_spec=SUBVARIO_CONDENSED_MEDIUM, text_color=TEXT_COLOR...
') def forbidden_response(): """Creates a simple forbidden status response.""" return Response(status=403) def settings_url(key): """Creates the URL for user data settings.""" return url_for('hello_get', key=key, _external=True) def settings_response(key, image_func, width, height):
64
64
159
12
52
NeilBetham/accent
server/response.py
Python
settings_response
settings_response
73
88
73
73
74b79a5f94f987cf21c01bdf36bd06e43540f38d
bigcode/the-stack
train
24901651ebbcfade9dd53a3e
train
function
def display_size(request): """Extracts the display size from the request or uses defaults.""" width = request.args.get('width', default=DEFAULT_DISPLAY_WIDTH) height = request.args.get('height', default=DEFAULT_DISPLAY_HEIGHT) try: return int(width), int(height) except ValueError as e: ...
def display_size(request):
"""Extracts the display size from the request or uses defaults.""" width = request.args.get('width', default=DEFAULT_DISPLAY_WIDTH) height = request.args.get('height', default=DEFAULT_DISPLAY_HEIGHT) try: return int(width), int(height) except ValueError as e: warning('Malformed dis...
content.image(user, width, height) return image_response(image) except ContentError as e: exception('Failed to create %s content: %s' % ( content.__class__.__name__, e)) return settings_response(user.id, image_response, width, height) def display_size(request):
64
64
94
5
59
NeilBetham/accent
server/response.py
Python
display_size
display_size
103
113
103
103
a5ad23d8c290c259d1e81d21914f9f1441d99b74
bigcode/the-stack
train
e72e1d694a6d11876f961504
train
function
def epd_response(image): """Creates a Flask e-paper display response from the specified image.""" data = bwr_bytes(image) buffer = BytesIO(data) return send_file(buffer, mimetype='application/octet-stream', cache_timeout=0)
def epd_response(image):
"""Creates a Flask e-paper display response from the specified image.""" data = bwr_bytes(image) buffer = BytesIO(data) return send_file(buffer, mimetype='application/octet-stream', cache_timeout=0)
"""Creates a Flask GIF response from the specified image.""" buffer = BytesIO() image = bwr_image(image) image.save(buffer, format='gif') buffer.seek(0) return send_file(buffer, mimetype='image/gif', cache_timeout=0) def epd_response(image):
64
64
54
6
58
NeilBetham/accent
server/response.py
Python
epd_response
epd_response
45
52
45
45
024332869539cd35dbf477b43beb2224ca6ee48e
bigcode/the-stack
train
8903146818d8256df109f2b6
train
function
def content_response(content, image_response, user, width, height): """Creates an image response and handles the error case flow.""" try: image = content.image(user, width, height) return image_response(image) except ContentError as e: exception('Failed to create %s content: %s' % (...
def content_response(content, image_response, user, width, height):
"""Creates an image response and handles the error case flow.""" try: image = content.image(user, width, height) return image_response(image) except ContentError as e: exception('Failed to create %s content: %s' % ( content.__class__.__name__, e)) return settings...
=image) computer = Image.open(COMPUTER_FILE).convert(mode='RGBA') image.paste(computer, box=adjust_xy(*COMPUTER_XY, width, height), mask=computer) return image_func(image) def content_response(content, image_response, user, width, height):
64
64
92
14
50
NeilBetham/accent
server/response.py
Python
content_response
content_response
91
100
91
91
fb83dacfe297e4b0f7465ff3b354b36526461db1
bigcode/the-stack
train
5518ed78526df4ce67cb5637
train
function
def gif_response(image): """Creates a Flask GIF response from the specified image.""" buffer = BytesIO() image = bwr_image(image) image.save(buffer, format='gif') buffer.seek(0) return send_file(buffer, mimetype='image/gif', cache_timeout=0)
def gif_response(image):
"""Creates a Flask GIF response from the specified image.""" buffer = BytesIO() image = bwr_image(image) image.save(buffer, format='gif') buffer.seek(0) return send_file(buffer, mimetype='image/gif', cache_timeout=0)
image. COMPUTER_FILE = 'assets/computer.gif' # The position of the computer in the settings image. COMPUTER_XY = (296, 145) # The position of the link text in the settings image. LINK_TEXT_XY = (0, 228) def gif_response(image):
64
64
64
5
59
NeilBetham/accent
server/response.py
Python
gif_response
gif_response
34
42
34
34
34edef729cc879aaf7ae40895daa0a249319aaf3
bigcode/the-stack
train
cdd057c1fb625563c6e1c307
train
function
def text_response(text): """Creates a Flask text response.""" return Response(text, mimetype='text/plain')
def text_response(text):
"""Creates a Flask text response.""" return Response(text, mimetype='text/plain')
cache_timeout=0) def epd_response(image): """Creates a Flask e-paper display response from the specified image.""" data = bwr_bytes(image) buffer = BytesIO(data) return send_file(buffer, mimetype='application/octet-stream', cache_timeout=0) def text_response(text):
64
64
24
5
59
NeilBetham/accent
server/response.py
Python
text_response
text_response
55
58
55
55
95a6b911dd80e09f422308a78fbbc74f9374fc94
bigcode/the-stack
train
9b3678480572999d15167d3d
train
function
def settings_url(key): """Creates the URL for user data settings.""" return url_for('hello_get', key=key, _external=True)
def settings_url(key):
"""Creates the URL for user data settings.""" return url_for('hello_get', key=key, _external=True)
(buffer, mimetype='application/octet-stream', cache_timeout=0) def text_response(text): """Creates a Flask text response.""" return Response(text, mimetype='text/plain') def forbidden_response(): """Creates a simple forbidden status response.""" return Response(status=403) def...
64
64
31
5
59
NeilBetham/accent
server/response.py
Python
settings_url
settings_url
67
70
67
67
635f9a2a20c11179e6ad2358b02804ac086f62f2
bigcode/the-stack
train
39b6fe45cd670176a64f21a3
train
class
class Migration(migrations.Migration): dependencies = [ ('logapp', '0001_initial'), ] operations = [ migrations.CreateModel( name='Visitor', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ...
class Migration(migrations.Migration):
dependencies = [ ('logapp', '0001_initial'), ] operations = [ migrations.CreateModel( name='Visitor', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('first_name', models.Cha...
# Generated by Django 2.1.7 on 2019-02-20 16:09 from django.db import migrations, models class Migration(migrations.Migration):
38
64
119
7
30
rahmangate/log
logapp/migrations/0002_visitor.py
Python
Migration
Migration
6
23
6
7
b80a2b6a4951354d025330d463f98e3b293641bc
bigcode/the-stack
train
3e5572f9e3255a51a0ad1fbb
train
class
class TodoCreateView(LoginRequiredMixin, FormView): form_class = TodoCreateForm success_url = reverse_lazy("todos:active_list") def form_valid(self, form): form.instance.user = self.request.user form.save() return super(TodoCreateView, self).form_valid(form)
class TodoCreateView(LoginRequiredMixin, FormView):
form_class = TodoCreateForm success_url = reverse_lazy("todos:active_list") def form_valid(self, form): form.instance.user = self.request.user form.save() return super(TodoCreateView, self).form_valid(form)
.html" tab_name = "completed" def get_context_data(self, **kwargs): kwargs["todos"] = Todo.objects.filter(user=self.request.user, done=True) return super(TodoCompletedListView, self).get_context_data(**kwargs) class TodoCreateView(LoginRequiredMixin, FormView):
64
64
66
11
53
erdem/django-selenium-example
todoapp/todos/views.py
Python
TodoCreateView
TodoCreateView
27
34
27
27
7c59964a84cd2aca47763e0d34f934b04310709a
bigcode/the-stack
train
58aa81473fd087fb23cf1b7b
train
class
class TodoToggleCompleteAjaxView(View): def post(self, request, *args, **kwargs): todo_id = request.POST.get("todo-id", -1) try: todo = Todo.objects.get(id=todo_id) except Todo.DoesNotExist: return HttpResponse(status=404) todo.done = not todo.done t...
class TodoToggleCompleteAjaxView(View):
def post(self, request, *args, **kwargs): todo_id = request.POST.get("todo-id", -1) try: todo = Todo.objects.get(id=todo_id) except Todo.DoesNotExist: return HttpResponse(status=404) todo.done = not todo.done todo.save() return HttpResponse(st...
): form_class = TodoCreateForm success_url = reverse_lazy("todos:active_list") def form_valid(self, form): form.instance.user = self.request.user form.save() return super(TodoCreateView, self).form_valid(form) class TodoToggleCompleteAjaxView(View):
64
64
84
8
56
erdem/django-selenium-example
todoapp/todos/views.py
Python
TodoToggleCompleteAjaxView
TodoToggleCompleteAjaxView
37
48
37
38
ca658a9ab47847e9623fc3b6f14fbe49cddeaf9d
bigcode/the-stack
train
4dd801ff846a4fb1edd80ee2
train
class
class TodoCompletedListView(LoginRequiredMixin, TemplateView): template_name = "todos/completed_list.html" tab_name = "completed" def get_context_data(self, **kwargs): kwargs["todos"] = Todo.objects.filter(user=self.request.user, done=True) return super(TodoCompletedListView, self).get_cont...
class TodoCompletedListView(LoginRequiredMixin, TemplateView):
template_name = "todos/completed_list.html" tab_name = "completed" def get_context_data(self, **kwargs): kwargs["todos"] = Todo.objects.filter(user=self.request.user, done=True) return super(TodoCompletedListView, self).get_context_data(**kwargs)
" tab_name = "active" def get_context_data(self, **kwargs): kwargs["todos"] = Todo.objects.filter(user=self.request.user, done=False) return super(TodoActiveListView, self).get_context_data(**kwargs) class TodoCompletedListView(LoginRequiredMixin, TemplateView):
64
64
74
12
52
erdem/django-selenium-example
todoapp/todos/views.py
Python
TodoCompletedListView
TodoCompletedListView
18
24
18
18
9468c5416da9ecea36df145c5df4418498e3febe
bigcode/the-stack
train
c55d1e68fecc494afae54402
train
class
class TodoActiveListView(LoginRequiredMixin, TemplateView): template_name = "todos/active_list.html" tab_name = "active" def get_context_data(self, **kwargs): kwargs["todos"] = Todo.objects.filter(user=self.request.user, done=False) return super(TodoActiveListView, self).get_context_data(**...
class TodoActiveListView(LoginRequiredMixin, TemplateView):
template_name = "todos/active_list.html" tab_name = "active" def get_context_data(self, **kwargs): kwargs["todos"] = Todo.objects.filter(user=self.request.user, done=False) return super(TodoActiveListView, self).get_context_data(**kwargs)
.auth.mixins import LoginRequiredMixin from django.core.urlresolvers import reverse_lazy from django.http import HttpResponse from django.views.generic import TemplateView, FormView, View from todos.forms import TodoCreateForm from todos.models import Todo class TodoActiveListView(LoginRequiredMixin, TemplateView):
64
64
74
12
51
erdem/django-selenium-example
todoapp/todos/views.py
Python
TodoActiveListView
TodoActiveListView
9
15
9
9
1c301d4d187d38f34e24aea7af4cae0a752de56f
bigcode/the-stack
train
1d1d3b0f01042754e7550e93
train
class
class Plugin(indigo.PluginBase): ######################################## # Main Plugin methods ######################################## def __init__(self, pluginId, pluginDisplayName, pluginVersion, pluginPrefs): indigo.PluginBase.__init__(self, pluginId, pluginDisplayName, pluginVersion, plug...
class Plugin(indigo.PluginBase): ######################################## # Main Plugin methods ########################################
def __init__(self, pluginId, pluginDisplayName, pluginVersion, pluginPrefs): indigo.PluginBase.__init__(self, pluginId, pluginDisplayName, pluginVersion, pluginPrefs) pfmt = logging.Formatter('%(asctime)s.%(msecs)03d\t[%(levelname)8s] %(name)20s.%(funcName)-25s%(msg)s', datefmt='%Y-%m-%d %H:%M:%S')...
#! /usr/bin/env python # -*- coding: utf-8 -*- #################### import time import requests import logging import json import aqi ################################################################################ class Plugin(indigo.PluginBase): ######################################## # Main Plugin method...
57
256
1,540
21
35
FlyingDiver/Indigo-miniPurple
miniPurple.indigoPlugin/Contents/Server Plugin/plugin.py
Python
Plugin
Plugin
12
134
12
16
3c9dd9befa502e1bcd0d9f6eb3f0309c2c60b42c
bigcode/the-stack
train
fbe862deccf793180dab8f57
train
class
class SWATestCNN(torch.nn.Module): def __init__(self, input_channels): super(SWATestCNN, self).__init__() self.n_features = 10 self.conv1 = torch.nn.Conv2d(input_channels, self.n_features, kernel_size=3, padding=1) self.bn = torch.nn.BatchNorm2d(self.n_features, momentum=0.3) de...
class SWATestCNN(torch.nn.Module):
def __init__(self, input_channels): super(SWATestCNN, self).__init__() self.n_features = 10 self.conv1 = torch.nn.Conv2d(input_channels, self.n_features, kernel_size=3, padding=1) self.bn = torch.nn.BatchNorm2d(self.n_features, momentum=0.3) def compute_preactivation(self, x): ...
.bn = torch.nn.BatchNorm1d(self.n_features) def compute_preactivation(self, x): return self.fc1(x) def forward(self, x): x = self.fc1(x) x = self.bn(x) return x class SWATestCNN(torch.nn.Module):
64
64
128
9
54
felixdivo/pytorch
test/test_optim.py
Python
SWATestCNN
SWATestCNN
2,363
2,376
2,363
2,363
44881428b3891e9c7f30ecc299150ba60fc91179
bigcode/the-stack
train
071d26f2714458b6f19d506f
train
class
class TestSWAUtils(TestCase): def _test_averaged_model(self, net_device, swa_device): dnn = torch.nn.Sequential( torch.nn.Conv2d(1, 5, kernel_size=3), torch.nn.ReLU(), torch.nn.MaxPool2d(kernel_size=2), torch.nn.BatchNorm2d(5, momentum=0.3), torch...
class TestSWAUtils(TestCase):
def _test_averaged_model(self, net_device, swa_device): dnn = torch.nn.Sequential( torch.nn.Conv2d(1, 5, kernel_size=3), torch.nn.ReLU(), torch.nn.MaxPool2d(kernel_size=2), torch.nn.BatchNorm2d(5, momentum=0.3), torch.nn.Conv2d(5, 2, kernel_size=3)...
Equal(last_lr, max_lr) class SWATestDNN(torch.nn.Module): def __init__(self, input_features): super(SWATestDNN, self).__init__() self.n_features = 100 self.fc1 = torch.nn.Linear(input_features, self.n_features) self.bn = torch.nn.BatchNorm1d(self.n_features) def compute_preact...
256
256
2,502
8
247
felixdivo/pytorch
test/test_optim.py
Python
TestSWAUtils
TestSWAUtils
2,379
2,620
2,379
2,380
c13646735cfb2ea87ff2d076cea1cb19331c75fc
bigcode/the-stack
train
f6b705fb55230dead94a3b5f
train
class
class TestLRScheduler(TestCase): exact_dtype = True def setUp(self): super(TestLRScheduler, self).setUp() self.net = SchedulerTestNet() self.opt = SGD( [{'params': self.net.conv1.parameters()}, {'params': self.net.conv2.parameters(), 'lr': 0.5}], lr=0.05) de...
class TestLRScheduler(TestCase):
exact_dtype = True def setUp(self): super(TestLRScheduler, self).setUp() self.net = SchedulerTestNet() self.opt = SGD( [{'params': self.net.conv1.parameters()}, {'params': self.net.conv2.parameters(), 'lr': 0.5}], lr=0.05) def _check_warning_is_epoch_depreca...
, optim.AdamW, optim.Adam, optim.Adagrad, optim.Adamax, optim.RMSprop, optim.SGD, optim.SparseAdam, optim.ASGD, ] for optim_ctr in optimizer_list: opt = optim_ctr(params, lr=0.1) # mak...
256
256
20,157
8
247
felixdivo/pytorch
test/test_optim.py
Python
TestLRScheduler
TestLRScheduler
918
2,344
918
918
fdf9964b25e40b5bf955f1585dc8df74397de38b
bigcode/the-stack
train
f7091e42e457ec605696f7ed
train
class
class TestOptim(TestCase): exact_dtype = True def _test_rosenbrock_sparse(self, constructor, scheduler_constructors=None, sparse_only=False): if scheduler_constructors is None: scheduler_constructors = [] params_t = torch.tensor([1.5, 1.5]) p...
class TestOptim(TestCase):
exact_dtype = True def _test_rosenbrock_sparse(self, constructor, scheduler_constructors=None, sparse_only=False): if scheduler_constructors is None: scheduler_constructors = [] params_t = torch.tensor([1.5, 1.5]) params = Variable(params_t, ...
, SequentialLR, StepLR, \ MultiStepLR, ConstantLR, LinearLR, ExponentialLR, CosineAnnealingLR, ReduceLROnPlateau, \ _LRScheduler, CyclicLR, CosineAnnealingWarmRestarts, OneCycleLR, ChainedScheduler, \ EPOCH_DEPRECATION_WARNING from torch.optim.swa_utils import AveragedModel, SWALR, update_bn from torch.test...
255
256
8,707
6
249
felixdivo/pytorch
test/test_optim.py
Python
TestOptim
TestOptim
40
891
40
40
b445e69f612502d7bc185d28b6b1014782fb3135
bigcode/the-stack
train
f35737783c2d4465aa71d900
train
class
class LambdaLRTestObject: def __init__(self, value): self.value = value def __call__(self, epoch): return self.value * epoch def __eq__(self, other): if isinstance(other, self.__class__): return self.__dict__ == other.__dict__ else: return False
class LambdaLRTestObject:
def __init__(self, value): self.value = value def __call__(self, epoch): return self.value * epoch def __eq__(self, other): if isinstance(other, self.__class__): return self.__dict__ == other.__dict__ else: return False
self.conv1 = torch.nn.Conv2d(1, 1, 1) self.conv2 = torch.nn.Conv2d(1, 1, 1) def forward(self, x): return self.conv2(F.relu(self.conv1(x))) class LambdaLRTestObject:
63
64
74
6
57
felixdivo/pytorch
test/test_optim.py
Python
LambdaLRTestObject
LambdaLRTestObject
904
915
904
904
dcf703a3994d6158aa8bc3cb3558b07c8400e216
bigcode/the-stack
train
183094876f7586e0074fbe93
train
class
class SchedulerTestNet(torch.nn.Module): def __init__(self): super(SchedulerTestNet, self).__init__() self.conv1 = torch.nn.Conv2d(1, 1, 1) self.conv2 = torch.nn.Conv2d(1, 1, 1) def forward(self, x): return self.conv2(F.relu(self.conv1(x)))
class SchedulerTestNet(torch.nn.Module):
def __init__(self): super(SchedulerTestNet, self).__init__() self.conv1 = torch.nn.Conv2d(1, 1, 1) self.conv2 = torch.nn.Conv2d(1, 1, 1) def forward(self, x): return self.conv2(F.relu(self.conv1(x)))
.SparseAdam, optim.ASGD, ] for optim_ctr in optimizer_list: opt = optim_ctr(params, lr=0.1) # make sure step can still run even if # all params have no grad opt.step() class SchedulerTestNet(torch.nn.Module):
64
64
83
8
56
felixdivo/pytorch
test/test_optim.py
Python
SchedulerTestNet
SchedulerTestNet
894
901
894
894
8ea2222797dd52f2025c0a02e3252299e619ea02
bigcode/the-stack
train
60d5fca6aaf72e8add3fd922
train
function
def drosenbrock(tensor): x, y = tensor return torch.tensor((-400 * x * (y - x ** 2) - 2 * (1 - x), 200 * (y - x ** 2)))
def drosenbrock(tensor):
x, y = tensor return torch.tensor((-400 * x * (y - x ** 2) - 2 * (1 - x), 200 * (y - x ** 2)))
. This line silences flake warnings load_tests = load_tests def rosenbrock(tensor): x, y = tensor return (1 - x) ** 2 + 100 * (y - x ** 2) ** 2 def drosenbrock(tensor):
64
64
52
8
55
felixdivo/pytorch
test/test_optim.py
Python
drosenbrock
drosenbrock
35
37
35
35
fc2261ce6079c409ea58133b859d3bbd33e0abea
bigcode/the-stack
train
3c31c76c231dc608de979867
train
class
class SWATestDNN(torch.nn.Module): def __init__(self, input_features): super(SWATestDNN, self).__init__() self.n_features = 100 self.fc1 = torch.nn.Linear(input_features, self.n_features) self.bn = torch.nn.BatchNorm1d(self.n_features) def compute_preactivation(self, x): ...
class SWATestDNN(torch.nn.Module):
def __init__(self, input_features): super(SWATestDNN, self).__init__() self.n_features = 100 self.fc1 = torch.nn.Linear(input_features, self.n_features) self.bn = torch.nn.BatchNorm1d(self.n_features) def compute_preactivation(self, x): return self.fc1(x) def forwar...
optimizer.step() if i <= lr_scheduler_1.T_max: lr_scheduler_1.step() else: lr_scheduler_2.step() last_lr = optimizer.param_groups[0]["lr"] self.assertLessEqual(last_lr, max_lr) class SWATestDNN(torch.nn.Module):
64
64
113
10
54
felixdivo/pytorch
test/test_optim.py
Python
SWATestDNN
SWATestDNN
2,347
2,360
2,347
2,347
0271c8b82e7725f2395d94437e8b05dccd2b9343
bigcode/the-stack
train
40fdfb3c2924dca71095dae5
train
function
def rosenbrock(tensor): x, y = tensor return (1 - x) ** 2 + 100 * (y - x ** 2) ** 2
def rosenbrock(tensor):
x, y = tensor return (1 - x) ** 2 + 100 * (y - x ** 2) ** 2
, run_tests, TEST_WITH_UBSAN, load_tests, \ skipIfRocm # load_tests from common_utils is used to automatically filter tests for # sharding on sandcastle. This line silences flake warnings load_tests = load_tests def rosenbrock(tensor):
64
64
41
8
55
felixdivo/pytorch
test/test_optim.py
Python
rosenbrock
rosenbrock
30
32
30
30
e4ab9568eae88a767ed1dc00d5a045bbb52a636b
bigcode/the-stack
train
12e653efa73330a9aa856d3d
train
class
class Solution: def reverse(self, x: int) -> int: if x == 0: return 0 res = "" sign = -1 if x < 0 else 1 x = abs(x) while x > 0: res = res + str(x%10) x = x // 10 res_i = int("".join(res)) if res_i > (2 ** 31 - 1) or res_i <...
class Solution:
def reverse(self, x: int) -> int: if x == 0: return 0 res = "" sign = -1 if x < 0 else 1 x = abs(x) while x > 0: res = res + str(x%10) x = x // 10 res_i = int("".join(res)) if res_i > (2 ** 31 - 1) or res_i < (-2 ** 31): ...
class Solution:
3
64
125
3
0
iamsuman/iv
iv/Leetcode/easy/e007_reverse_integer.py
Python
Solution
Solution
1
15
1
1
444d31573900bf3dcab8813035526da37372760a
bigcode/the-stack
train
7d9664a3ca0f5efbcd4ee6c3
train
class
class RoundRobinStrategyTest(parameterized.TestCase, tf.test.TestCase): # pylint: disable=g-complex-comprehension @parameterized.named_parameters( itertools.chain(*[[ { "testcase_name": _testcase_name("one_worker_one_subnetwork", drop_remainder), "num_w...
class RoundRobinStrategyTest(parameterized.TestCase, tf.test.TestCase): # pylint: disable=g-complex-comprehension @parameterized.named_parameters( itertools.chain(*[[ { "testcase_name": _testcase_name("one_worker_one_subnetwork", drop_remainder), "num_w...
def test_methods(self, num_workers, num_subnetworks, drop_remainder, want_should_build_ensemble, want_should_build_subnetwork, want_should_train_subnetworks): should_build_ensemble = [] should_build_subnetwork = [] should_train_subnetworks = [] for worker_index in...
class RoundRobinStrategyTest(parameterized.TestCase, tf.test.TestCase): # pylint: disable=g-complex-comprehension @parameterized.named_parameters( itertools.chain(*[[ { "testcase_name": _testcase_name("one_worker_one_subnetwork", drop_remainder), "num_w...
1,567
256
1,790
1,567
0
SmallyolkLiu/adanet
adanet/core/distributed/placement_test.py
Python
RoundRobinStrategyTest
RoundRobinStrategyTest
52
285
52
265
5ed3c9b43613b579f33784450546a7aec03a6d4c
bigcode/the-stack
train
cea51f243fc14f2db71ff1c9
train
class
class ReplicationStrategyTest(tf.test.TestCase): def test_strategy(self): strategy = ReplicationStrategy() num_subnetworks = 3 subnetwork_index = 1 self.assertTrue(strategy.should_build_ensemble(num_subnetworks)) self.assertTrue( strategy.should_build_subnetwork(num_subnetworks, subnetwor...
class ReplicationStrategyTest(tf.test.TestCase):
def test_strategy(self): strategy = ReplicationStrategy() num_subnetworks = 3 subnetwork_index = 1 self.assertTrue(strategy.should_build_ensemble(num_subnetworks)) self.assertTrue( strategy.should_build_subnetwork(num_subnetworks, subnetwork_index)) self.assertTrue(strategy.should_trai...
__ import division from __future__ import print_function import itertools from absl.testing import parameterized from adanet.core.distributed.placement import ReplicationStrategy from adanet.core.distributed.placement import RoundRobinStrategy import tensorflow as tf class ReplicationStrategyTest(tf.test.TestCase): ...
64
64
89
10
53
SmallyolkLiu/adanet
adanet/core/distributed/placement_test.py
Python
ReplicationStrategyTest
ReplicationStrategyTest
29
38
29
30
4a11485da630bc02a45e55ca902012ed5bc9d7eb
bigcode/the-stack
train
f0f3b7cfe8ba17d0f1de123a
train
function
def _testcase_name(name, drop_remainder): return "{}{}".format(name, "_drop_remainder" if drop_remainder else "")
def _testcase_name(name, drop_remainder):
return "{}{}".format(name, "_drop_remainder" if drop_remainder else "")
(num_subnetworks)) class Config(object): def __init__(self, num_worker_replicas, global_id_in_cluster): self.num_worker_replicas = num_worker_replicas self.global_id_in_cluster = global_id_in_cluster def _testcase_name(name, drop_remainder):
64
64
29
11
52
SmallyolkLiu/adanet
adanet/core/distributed/placement_test.py
Python
_testcase_name
_testcase_name
48
49
48
48
c024f66d2adfa9fa0b819cb703fdf9410d588c19
bigcode/the-stack
train
a3d290ed86112b59e7f63ab7
train
class
class Config(object): def __init__(self, num_worker_replicas, global_id_in_cluster): self.num_worker_replicas = num_worker_replicas self.global_id_in_cluster = global_id_in_cluster
class Config(object):
def __init__(self, num_worker_replicas, global_id_in_cluster): self.num_worker_replicas = num_worker_replicas self.global_id_in_cluster = global_id_in_cluster
3 subnetwork_index = 1 self.assertTrue(strategy.should_build_ensemble(num_subnetworks)) self.assertTrue( strategy.should_build_subnetwork(num_subnetworks, subnetwork_index)) self.assertTrue(strategy.should_train_subnetworks(num_subnetworks)) class Config(object):
64
64
48
4
60
SmallyolkLiu/adanet
adanet/core/distributed/placement_test.py
Python
Config
Config
41
45
41
42
ad3236d670823ec929d99b1a239e7955977618a3
bigcode/the-stack
train
865b560c438ce969f3826fe1
train
function
async def _async_reproduce_state( hass: HomeAssistantType, state: State, *, context: Context | None = None, reproduce_options: dict[str, Any] | None = None, ) -> None: """Reproduce a single state.""" cur_state = hass.states.get(state.entity_id) if cur_state is None: _LOGGER.warn...
async def _async_reproduce_state( hass: HomeAssistantType, state: State, *, context: Context | None = None, reproduce_options: dict[str, Any] | None = None, ) -> None:
"""Reproduce a single state.""" cur_state = hass.states.get(state.entity_id) if cur_state is None: _LOGGER.warning("Unable to find entity %s", state.entity_id) return if state.state not in VALID_STATES: _LOGGER.warning( "Invalid state specified for %s: %s", state.en...
= logging.getLogger(__name__) VALID_STATES = {STATE_ON, STATE_OFF} async def _async_reproduce_state( hass: HomeAssistantType, state: State, *, context: Context | None = None, reproduce_options: dict[str, Any] | None = None, ) -> None:
67
67
225
49
18
bg1000/core
homeassistant/components/alert/reproduce_state.py
Python
_async_reproduce_state
_async_reproduce_state
25
59
25
31
6d58f03e61c62dbc6fe5b5dfef7c182b03089291
bigcode/the-stack
train
d84a8f365cd8f6f29017fcf2
train
function
async def async_reproduce_states( hass: HomeAssistantType, states: Iterable[State], *, context: Context | None = None, reproduce_options: dict[str, Any] | None = None, ) -> None: """Reproduce Alert states.""" # Reproduce states in parallel. await asyncio.gather( *( _a...
async def async_reproduce_states( hass: HomeAssistantType, states: Iterable[State], *, context: Context | None = None, reproduce_options: dict[str, Any] | None = None, ) -> None:
"""Reproduce Alert states.""" # Reproduce states in parallel. await asyncio.gather( *( _async_reproduce_state( hass, state, context=context, reproduce_options=reproduce_options ) for state in states ) )
, service, service_data, context=context, blocking=True ) async def async_reproduce_states( hass: HomeAssistantType, states: Iterable[State], *, context: Context | None = None, reproduce_options: dict[str, Any] | None = None, ) -> None:
64
64
107
50
14
bg1000/core
homeassistant/components/alert/reproduce_state.py
Python
async_reproduce_states
async_reproduce_states
62
78
62
68
404b3904b12ecdbcf307df365b8098fd88782923
bigcode/the-stack
train
243488890677dd9fb868b36c
train
function
def test_merge_equivalent_to_single_run(): vals1 = [1, 2, 3, 1, 2, 3] vals2 = [1, 2, 3, 4, 5] all_vals = vals1 + vals2 hll1 = hllsketch.HllSketch() for v in vals1: hll1.update(v) hll2 = hllsketch.HllSketch() for v in vals2: hll2.update(v) hll3 = hllsketch.HllSketch() ...
def test_merge_equivalent_to_single_run():
vals1 = [1, 2, 3, 1, 2, 3] vals2 = [1, 2, 3, 4, 5] all_vals = vals1 + vals2 hll1 = hllsketch.HllSketch() for v in vals1: hll1.update(v) hll2 = hllsketch.HllSketch() for v in vals2: hll2.update(v) hll3 = hllsketch.HllSketch() for v in all_vals: hll3.update(v...
, 2, 3] * 2 for v in vals: hll.update(v) assert hll.get_estimate() == pytest.approx(3, 1e-5) assert hll.get_upper_bound() == pytest.approx(3, 1e-3) assert hll.get_lower_bound() == pytest.approx(3, 1e-3) def test_merge_equivalent_to_single_run():
95
95
318
9
86
DialMforMara/whylogs-python
tests/unit/core/statistics/test_hllsketch.py
Python
test_merge_equivalent_to_single_run
test_merge_equivalent_to_single_run
123
150
123
123
57bc85fee1e3d18c8f571d1ad83f03c4a88938b7
bigcode/the-stack
train
bba42d9f381e689753150788
train
function
def test_update(): hll = hllsketch.HllSketch() vals = [1, 2, 3] * 2 for v in vals: hll.update(v) assert hll.get_estimate() == pytest.approx(3, 1e-5) assert hll.get_upper_bound() == pytest.approx(3, 1e-3) assert hll.get_lower_bound() == pytest.approx(3, 1e-3)
def test_update():
hll = hllsketch.HllSketch() vals = [1, 2, 3] * 2 for v in vals: hll.update(v) assert hll.get_estimate() == pytest.approx(3, 1e-5) assert hll.get_upper_bound() == pytest.approx(3, 1e-3) assert hll.get_lower_bound() == pytest.approx(3, 1e-3)
0, 3.0] * 2 hll = hllsketch.HllSketch() for v in int_vals + float_vals: hll.update(v) assert hll.get_estimate() == pytest.approx(6, 1e-5) def test_update():
64
64
107
4
60
DialMforMara/whylogs-python
tests/unit/core/statistics/test_hllsketch.py
Python
test_update
test_update
112
120
112
112
9eae7add1869962831d3f5980ac9bf6c718dbe2d
bigcode/the-stack
train
2e9ef2a773c55bc613d97556
train
function
def test_protobuf_roundtrip(): hll1 = hllsketch.HllSketch() vals = [1, 2, 3, 1, 2, 3, "a", "a", "b", 2.0, 8.0, 9.0] for v in vals: hll1.update(v) msg = hll1.to_protobuf() hll2 = hllsketch.HllSketch.from_protobuf(msg) assert hll1.get_estimate() == hll2.get_estimate() assert hll1.get...
def test_protobuf_roundtrip():
hll1 = hllsketch.HllSketch() vals = [1, 2, 3, 1, 2, 3, "a", "a", "b", 2.0, 8.0, 9.0] for v in vals: hll1.update(v) msg = hll1.to_protobuf() hll2 = hllsketch.HllSketch.from_protobuf(msg) assert hll1.get_estimate() == hll2.get_estimate() assert hll1.get_upper_bound() == hll2.get_uppe...
.get_lower_bound(1) assert merged_1_into_2.get_upper_bound(1) == merged_2_into_1.get_upper_bound(1) assert merged_1_into_2.get_upper_bound(1) == hll3.get_upper_bound(1) def test_protobuf_roundtrip():
64
64
156
7
57
DialMforMara/whylogs-python
tests/unit/core/statistics/test_hllsketch.py
Python
test_protobuf_roundtrip
test_protobuf_roundtrip
153
164
153
153
52edad72a42e0fcd9fa3c2cb5be844b2d039fca6
bigcode/the-stack
train
b420da318ed48f2c2378ce6c
train
function
def test_enum_tracking(): class X(Enum): A = 1 B = 2 C = 3 D = 4 vals = [X.A, X.B, X.C, X.D] + [1, 2, 3, 4] hll = hllsketch.HllSketch() for v in vals: hll.update(v) assert hll.get_estimate() == pytest.approx(4, 1e-5)
def test_enum_tracking():
class X(Enum): A = 1 B = 2 C = 3 D = 4 vals = [X.A, X.B, X.C, X.D] + [1, 2, 3, 4] hll = hllsketch.HllSketch() for v in vals: hll.update(v) assert hll.get_estimate() == pytest.approx(4, 1e-5)
datetime(2020, 2, 3, 21, 28, 31), datetime.utcnow(), ] for v in vals: hll.update(v) assert hll.get_estimate() == pytest.approx(4, 1e-5) def test_enum_tracking():
64
64
108
5
59
DialMforMara/whylogs-python
tests/unit/core/statistics/test_hllsketch.py
Python
test_enum_tracking
test_enum_tracking
87
99
87
87
67c20fc66e0c1c737f7c8166f7c4ab2786c6fc64
bigcode/the-stack
train
c148d3d917d1a23c9a1fe749
train
function
def test_datetime_tracking(): hll = hllsketch.HllSketch() vals = [ datetime(2020, 2, 3), datetime(2020, 2, 3), datetime(2020, 2, 3, tzinfo=pytz.UTC), datetime(2020, 2, 3, 21, 28, 31), datetime.utcnow(), ] for v in vals: hll.update(v) assert hll.get_es...
def test_datetime_tracking():
hll = hllsketch.HllSketch() vals = [ datetime(2020, 2, 3), datetime(2020, 2, 3), datetime(2020, 2, 3, tzinfo=pytz.UTC), datetime(2020, 2, 3, 21, 28, 31), datetime.utcnow(), ] for v in vals: hll.update(v) assert hll.get_estimate() == pytest.approx(4, 1...
_protobuf_then_merge(): hll = hllsketch.HllSketch() vals = [1, 2, 3] hll2 = hllsketch.HllSketch.from_protobuf(hll.to_protobuf()) hll2.merge(hll2) def test_datetime_tracking():
64
64
124
5
59
DialMforMara/whylogs-python
tests/unit/core/statistics/test_hllsketch.py
Python
test_datetime_tracking
test_datetime_tracking
72
84
72
72
c4f813e4dd0a7b0a93c78d64f0eb74e8475b1ae4
bigcode/the-stack
train
e26cd983afc39dd42459e954
train
function
def test_floats_ints_different(): int_vals = [1, 2, 3] * 2 float_vals = [1.0, 2.0, 3.0] * 2 hll = hllsketch.HllSketch() for v in int_vals + float_vals: hll.update(v) assert hll.get_estimate() == pytest.approx(6, 1e-5)
def test_floats_ints_different():
int_vals = [1, 2, 3] * 2 float_vals = [1.0, 2.0, 3.0] * 2 hll = hllsketch.HllSketch() for v in int_vals + float_vals: hll.update(v) assert hll.get_estimate() == pytest.approx(6, 1e-5)
2, 3, 4] hll = hllsketch.HllSketch() for v in vals: hll.update(v) assert hll.get_estimate() == pytest.approx(4, 1e-5) def test_floats_ints_different():
64
64
99
10
54
DialMforMara/whylogs-python
tests/unit/core/statistics/test_hllsketch.py
Python
test_floats_ints_different
test_floats_ints_different
102
109
102
102
79957f34a4870fd955d90cdca24521d71f43e0f6
bigcode/the-stack
train
411ce24d3780e0a7501e980b
train
function
def test_empty_sketch_summary_returns_none(): sketch = hllsketch.HllSketch() assert sketch.to_summary() is None
def test_empty_sketch_summary_returns_none():
sketch = hllsketch.HllSketch() assert sketch.to_summary() is None
= hll.to_summary() assert summary.estimate == pytest.approx(n, 1e-5) assert summary.upper == pytest.approx(n, 1e-4) assert summary.lower == pytest.approx(n, 1e-4) def test_empty_sketch_summary_returns_none():
64
64
29
9
55
DialMforMara/whylogs-python
tests/unit/core/statistics/test_hllsketch.py
Python
test_empty_sketch_summary_returns_none
test_empty_sketch_summary_returns_none
180
182
180
180
5f824504bc242798eb0673c7e2be3f329671c608
bigcode/the-stack
train
56cbaff4967f520c9e6cc920
train
function
def test_summary(): hll = hllsketch.HllSketch() vals = 3 * [1, 2, 3] + [4.0, 6.0, 9.0, 9.0] + ["a", "a", "dkfjadlf", "c"] for v in vals: hll.update(v) n = 3 + 3 + 3 summary = hll.to_summary() assert summary.estimate == pytest.approx(n, 1e-5) assert summary.upper == pytest.approx(n, ...
def test_summary():
hll = hllsketch.HllSketch() vals = 3 * [1, 2, 3] + [4.0, 6.0, 9.0, 9.0] + ["a", "a", "dkfjadlf", "c"] for v in vals: hll.update(v) n = 3 + 3 + 3 summary = hll.to_summary() assert summary.estimate == pytest.approx(n, 1e-5) assert summary.upper == pytest.approx(n, 1e-4) assert sum...
etch.HllSketch.from_protobuf(msg) assert hll1.get_estimate() == hll2.get_estimate() assert hll1.get_upper_bound() == hll2.get_upper_bound() assert hll1.get_lower_bound() == hll2.get_lower_bound() def test_summary():
64
64
149
4
60
DialMforMara/whylogs-python
tests/unit/core/statistics/test_hllsketch.py
Python
test_summary
test_summary
167
177
167
167
e6cdbd99d90d597c4bc9a91cef222e6a6a9a6ebd
bigcode/the-stack
train
5a57ec23ad6e10fa8985fb22
train
function
def test_protobuf_then_merge(): hll = hllsketch.HllSketch() vals = [1, 2, 3] hll2 = hllsketch.HllSketch.from_protobuf(hll.to_protobuf()) hll2.merge(hll2)
def test_protobuf_then_merge():
hll = hllsketch.HllSketch() vals = [1, 2, 3] hll2 = hllsketch.HllSketch.from_protobuf(hll.to_protobuf()) hll2.merge(hll2)
.to_protobuf() msg_str = msg.SerializeToString() msg1 = hllsketch.HllSketchMessage.FromString(msg_str) hll2 = hllsketch.HllSketch.from_protobuf(msg1) hll2.merge(hll2) def test_protobuf_then_merge():
64
64
61
7
57
DialMforMara/whylogs-python
tests/unit/core/statistics/test_hllsketch.py
Python
test_protobuf_then_merge
test_protobuf_then_merge
65
69
65
65
83b478a7032733def1d883bff066cc5d91f61b31
bigcode/the-stack
train
c3394092fd23976426ec97de
train
function
def test_serialize_then_merge_does_not_fail(): """ There is a bizarre circumstance when serializing a dataksetches HLL sketch using sketch.serialize_updatable() which results in an occasional RuntimeError after deserialization and trying to update a union with that sketch. This bug does not _al...
def test_serialize_then_merge_does_not_fail():
""" There is a bizarre circumstance when serializing a dataksetches HLL sketch using sketch.serialize_updatable() which results in an occasional RuntimeError after deserialization and trying to update a union with that sketch. This bug does not _always_ creep up, therefore this test must be run...
from datetime import datetime from enum import Enum import pytest import pytz from whylogs.core.statistics import hllsketch def test_serialize_then_merge_does_not_fail():
39
113
379
11
27
DialMforMara/whylogs-python
tests/unit/core/statistics/test_hllsketch.py
Python
test_serialize_then_merge_does_not_fail
test_serialize_then_merge_does_not_fail
10
62
10
10
3b48a4cab142011d31e3e9dbbe4649dab8ef8727
bigcode/the-stack
train
84a744a004f03c577488d909
train
function
def _key_to_index(key, bin_factor, max_index): """Get hash index for a given key.""" # Get key as a single integer index = sum(int(val) * int(bin_factor)**i for (i, val) in enumerate(key)) # Randomise by magic constant and modulo to maximum index return (index * _MAGIC_RAND) % max_index
def _key_to_index(key, bin_factor, max_index):
"""Get hash index for a given key.""" # Get key as a single integer index = sum(int(val) * int(bin_factor)**i for (i, val) in enumerate(key)) # Randomise by magic constant and modulo to maximum index return (index * _MAGIC_RAND) % max_index
[] for c in itertools.count(): i = (index + c**2) % max_ind if all(table[i, :] == 0): return found else: found.append(table[i, :].squeeze()) def _key_to_index(key, bin_factor, max_index):
64
64
83
13
51
adambaskerville/AstroPitography
tetra3/tetra3.py
Python
_key_to_index
_key_to_index
112
117
112
112
1dabbb6a072960b1bf8a74ae69349b32c90fd795
bigcode/the-stack
train
e5fa30adbd445d9ddfa918b2
train
function
def _get_at_index(index, table): """Gets from table with quadratic probing, returns list of all matches.""" max_ind = table.shape[0] found = [] for c in itertools.count(): i = (index + c**2) % max_ind if all(table[i, :] == 0): return found else: found.appe...
def _get_at_index(index, table):
"""Gets from table with quadratic probing, returns list of all matches.""" max_ind = table.shape[0] found = [] for c in itertools.count(): i = (index + c**2) % max_ind if all(table[i, :] == 0): return found else: found.append(table[i, :].squeeze())
quadratic probing.""" max_ind = table.shape[0] for c in itertools.count(): i = (index + c**2) % max_ind if all(table[i, :] == 0): table[i, :] = item return def _get_at_index(index, table):
64
64
87
9
54
adambaskerville/AstroPitography
tetra3/tetra3.py
Python
_get_at_index
_get_at_index
100
109
100
100
8bdf45919a41c62389daa92576b96c1eef9ba1c3
bigcode/the-stack
train
cd192e85212037eda9fcd9d5
train
function
def crop_and_downsample_image(image, crop=None, downsample=None, sum_when_downsample=True, return_offsets=False): """Crop and/or downsample an image. Cropping is applied before downsampling. Args: image (numpy.ndarray): The image to crop and downsample. Must be 2D. ...
def crop_and_downsample_image(image, crop=None, downsample=None, sum_when_downsample=True, return_offsets=False):
"""Crop and/or downsample an image. Cropping is applied before downsampling. Args: image (numpy.ndarray): The image to crop and downsample. Must be 2D. crop (int or tuple, optional): Desired cropping of the image. May be defined in three ways: - Scalar: Image is cropped to given fr...
img_sum extracted[i, 1:3] = np.array([yc, xc]) + [offs_y, offs_x] # 10. Revert effects of crop and downsample if downsample: extracted[:, 1:3] = extracted[:, 1:3] * downsample # Scale centroid if crop: extracted[:, 1:3] = extracted[:, 1:3] + np.array([offs_h, offs_w]) # Offset...
256
256
1,349
26
230
adambaskerville/AstroPitography
tetra3/tetra3.py
Python
crop_and_downsample_image
crop_and_downsample_image
1,158
1,272
1,158
1,159
a63774fa53e6830697069d4dd8cdc8daafc6138e
bigcode/the-stack
train
4c1efaec001746a573f5d992
train
class
class Tetra3(): """Solve star patterns and manage databases. To find the direction in the sky an image is showing this class calculates a "fingerprint" of the stars seen in the image and looks for matching fingerprints in a pattern catalogue loaded into memory. Subsequently, all stars that should be vi...
class Tetra3():
"""Solve star patterns and manage databases. To find the direction in the sky an image is showing this class calculates a "fingerprint" of the stars seen in the image and looks for matching fingerprints in a pattern catalogue loaded into memory. Subsequently, all stars that should be visible in the ima...
respectively pattern_indices = [-1] + list(range(pattern_size)) + [len(star_centroids)] # output the very brightest centroids before doing anything else yield star_centroids[pattern_indices[1:-1]] # iterate until the very dimmest centroids have been output # which occurs when the first pattern inde...
255
256
8,293
5
250
adambaskerville/AstroPitography
tetra3/tetra3.py
Python
Tetra3
Tetra3
149
839
149
149
0744364489f5f172937a2bba75affc21b746b8af
bigcode/the-stack
train
fc6c906735d46e1420a42965
train
function
def _generate_patterns_from_centroids(star_centroids, pattern_size): """Iterate over centroids in order of brightness.""" # break if there aren't enough centroids to make even one pattern if len(star_centroids) < pattern_size: return star_centroids = np.array(star_centroids) # create a list ...
def _generate_patterns_from_centroids(star_centroids, pattern_size):
"""Iterate over centroids in order of brightness.""" # break if there aren't enough centroids to make even one pattern if len(star_centroids) < pattern_size: return star_centroids = np.array(star_centroids) # create a list of the pattern's centroid indices # add the lower and upper index...
[i, :].squeeze()) def _key_to_index(key, bin_factor, max_index): """Get hash index for a given key.""" # Get key as a single integer index = sum(int(val) * int(bin_factor)**i for (i, val) in enumerate(key)) # Randomise by magic constant and modulo to maximum index return (index * _MAGIC_RAND) % ma...
105
105
350
15
89
adambaskerville/AstroPitography
tetra3/tetra3.py
Python
_generate_patterns_from_centroids
_generate_patterns_from_centroids
120
146
120
120
dec10a172ae1bff2976be6d86a9e549b7076ad18
bigcode/the-stack
train
ee4018d32c11f9cb63c2c888
train
function
def _insert_at_index(item, index, table): """Inserts to table with quadratic probing.""" max_ind = table.shape[0] for c in itertools.count(): i = (index + c**2) % max_ind if all(table[i, :] == 0): table[i, :] = item return
def _insert_at_index(item, index, table):
"""Inserts to table with quadratic probing.""" max_ind = table.shape[0] for c in itertools.count(): i = (index + c**2) % max_ind if all(table[i, :] == 0): table[i, :] = item return
from time import perf_counter as precision_timestamp from datetime import datetime # External imports: import numpy as np from numpy.linalg import norm import scipy.ndimage import scipy.optimize import scipy.stats _MAGIC_RAND = 2654435761 def _insert_at_index(item, index, table):
64
64
73
11
52
adambaskerville/AstroPitography
tetra3/tetra3.py
Python
_insert_at_index
_insert_at_index
90
97
90
90
759d9d418598efbde5b7c2bc8567fd19fc76b563
bigcode/the-stack
train
75646c85f6449f82fdf04cda
train
function
def get_centroids_from_image(image, sigma=3, image_th=None, crop=None, downsample=None, filtsize=7, bg_sub_mode='local_median', sigma_mode='local_median_abs', binary_open=True, centroid_window=None, max_area=None, min_area=3, max_sum...
def get_centroids_from_image(image, sigma=3, image_th=None, crop=None, downsample=None, filtsize=7, bg_sub_mode='local_median', sigma_mode='local_median_abs', binary_open=True, centroid_window=None, max_area=None, min_area=3, max_sum...
"""Extract spot centroids from an image and calculate statistics. This is a versatile function for finding spots (e.g. stars or satellites) in an image and calculating/filtering their positions (centroids) and statistics (e.g. sum, area, shape). The coordinates start at the top/left edge of the pixel,...
t_solve = (precision_timestamp() - t0_solve) * 1000 self._logger.debug('FAIL: Did not find a match to the stars! It took ' + str(round(t_solve)) + ' ms.') return {'RA': None, 'Dec': None, 'Roll': None, 'FOV': None, 'RMSE': None, 'Matches': None, 'Prob':...
256
256
4,285
94
162
adambaskerville/AstroPitography
tetra3/tetra3.py
Python
get_centroids_from_image
get_centroids_from_image
842
1,155
842
846
4393fa89bdfd22e106b03251b24e76e6ad319630
bigcode/the-stack
train
8d08d8c54bf093eb626af0d0
train
function
def toBbox(rleObjs): if type(rleObjs) == list: return _mask.toBbox(rleObjs) else: return _mask.toBbox([rleObjs])[0]
def toBbox(rleObjs):
if type(rleObjs) == list: return _mask.toBbox(rleObjs) else: return _mask.toBbox([rleObjs])[0]
else: return _mask.decode([rleObjs])[:,:,0] def area(rleObjs): if type(rleObjs) == list: return _mask.area(rleObjs) else: return _mask.area([rleObjs])[0] def toBbox(rleObjs):
64
64
46
8
56
Dumpkin1996/clipper
applications/fatigue_bigball/container/container3/app/cocoapi-master/PythonAPI/pycocotools/mask.py
Python
toBbox
toBbox
99
103
99
99
071cfc476709bb83ea6b2ec96698b9c12b29ec71
bigcode/the-stack
train
f2aea21d417ca6cfaf98a536
train
function
def encode(bimask): if len(bimask.shape) == 3: return _mask.encode(bimask) elif len(bimask.shape) == 2: h, w = bimask.shape return _mask.encode(bimask.reshape((h, w, 1), order='F'))[0]
def encode(bimask):
if len(bimask.shape) == 3: return _mask.encode(bimask) elif len(bimask.shape) == 2: h, w = bimask.shape return _mask.encode(bimask.reshape((h, w, 1), order='F'))[0]
/ # Code written by Piotr Dollar and Tsung-Yi Lin, 2015. # Licensed under the Simplified BSD License [see coco/license.txt] iou = _mask.iou merge = _mask.merge frPyObjects = _mask.frPyObjects def encode(bimask):
64
64
72
6
57
Dumpkin1996/clipper
applications/fatigue_bigball/container/container3/app/cocoapi-master/PythonAPI/pycocotools/mask.py
Python
encode
encode
80
85
80
80
a496a795a2ebab1635a4d44d8088466618110d0a
bigcode/the-stack
train
9e057f648ea3ee6488b200f9
train
function
def decode(rleObjs): if type(rleObjs) == list: return _mask.decode(rleObjs) else: return _mask.decode([rleObjs])[:,:,0]
def decode(rleObjs):
if type(rleObjs) == list: return _mask.decode(rleObjs) else: return _mask.decode([rleObjs])[:,:,0]
== 3: return _mask.encode(bimask) elif len(bimask.shape) == 2: h, w = bimask.shape return _mask.encode(bimask.reshape((h, w, 1), order='F'))[0] def decode(rleObjs):
64
64
41
6
58
Dumpkin1996/clipper
applications/fatigue_bigball/container/container3/app/cocoapi-master/PythonAPI/pycocotools/mask.py
Python
decode
decode
87
91
87
87
a0e3052323d6bbb8b5fd7287f0dc894c215342ca
bigcode/the-stack
train
f6dacac631b4f148b199094f
train
function
def area(rleObjs): if type(rleObjs) == list: return _mask.area(rleObjs) else: return _mask.area([rleObjs])[0]
def area(rleObjs):
if type(rleObjs) == list: return _mask.area(rleObjs) else: return _mask.area([rleObjs])[0]
ask.reshape((h, w, 1), order='F'))[0] def decode(rleObjs): if type(rleObjs) == list: return _mask.decode(rleObjs) else: return _mask.decode([rleObjs])[:,:,0] def area(rleObjs):
64
64
40
6
58
Dumpkin1996/clipper
applications/fatigue_bigball/container/container3/app/cocoapi-master/PythonAPI/pycocotools/mask.py
Python
area
area
93
97
93
93
e847cdf02582d98ea5ea13850382e70023e8c228
bigcode/the-stack
train
094cbe001cae36b8d0747baa
train
function
@airtime.route('/send_airtime', methods=['POST']) def send_sms_service(): req = request.get_json(force=True) if {'phoneNo', 'currency', 'amount'} <= set(req): airtime_service = africastalking.Airtime phone_number = req['phoneNo'] currency_code = req['currency'] amount = req['amou...
@airtime.route('/send_airtime', methods=['POST']) def send_sms_service():
req = request.get_json(force=True) if {'phoneNo', 'currency', 'amount'} <= set(req): airtime_service = africastalking.Airtime phone_number = req['phoneNo'] currency_code = req['currency'] amount = req['amount'] response = airtime_service.send(phone_number=phone_number, am...
from flask import make_response, jsonify, request, Blueprint import africastalking airtime = Blueprint('airtime', __name__, url_prefix="/playpen/test") @airtime.route('/send_airtime', methods=['POST']) def send_sms_service():
53
64
132
18
35
odaridavid/AfricasTalkingPlaypen
api/airtime/airtime_service.py
Python
send_sms_service
send_sms_service
7
17
7
8
7c4e9ebfd114965490566b090a3965a3f08270f2
bigcode/the-stack
train
cf05cee3c24b520ecaa7fb51
train
class
@mock.patch.object( publishers.CUDPublisher, 'publish_update', mock.MagicMock(return_value=None)) @mock.patch.object( publishers.CUDPublisher, 'publish_create', mock.MagicMock(side_effect=mock_lv_ac_xport.MockLiveActionPublisher.publish_create)) @mock.patch.object( lv_ac_xport.LiveActionPubl...
@mock.patch.object( publishers.CUDPublisher, 'publish_update', mock.MagicMock(return_value=None)) @mock.patch.object( publishers.CUDPublisher, 'publish_create', mock.MagicMock(side_effect=mock_lv_ac_xport.MockLiveActionPublisher.publish_create)) @mock.patch.object( lv_ac_xport.LiveActionPubl...
def setUpClass(cls): super(WorkflowExecutionCancellationTest, cls).setUpClass() # Register runners. runnersregistrar.register_runners() # Register test pack(s). actions_registrar = actionsregistrar.ActionsRegistrar( use_pack_cache=False, fail_on_fail...
orquesta_tests' TEST_PACK_PATH = st2tests.fixturesloader.get_fixtures_packs_base_path() + '/' + TEST_PACK PACKS = [ TEST_PACK_PATH, st2tests.fixturesloader.get_fixtures_packs_base_path() + '/core' ] @mock.patch.object( publishers.CUDPublisher, 'publish_update', mock.MagicMock(return_value=None)) @m...
175
175
586
116
59
benmcbenben/st2
st2common/tests/unit/services/test_workflow_cancellation.py
Python
WorkflowExecutionCancellationTest
WorkflowExecutionCancellationTest
57
115
57
71
1cad0e244b02374517fd45484e0e6dfe9c02e9e2
bigcode/the-stack
train
911b983c4c84f8bef48c94f1
train
function
@log_start_end(log=logger) def load(file: str) -> pd.DataFrame: """Load custom file into dataframe. Currently will work with csv Parameters ---------- file: str Path to file Returns ------- pd.DataFrame: Dataframe with custom data """ if not Path(file).exists(): ...
@log_start_end(log=logger) def load(file: str) -> pd.DataFrame:
"""Load custom file into dataframe. Currently will work with csv Parameters ---------- file: str Path to file Returns ------- pd.DataFrame: Dataframe with custom data """ if not Path(file).exists(): return pd.DataFrame() file_type = Path(file).suffix ...
"""Custom Controller Model""" __docformat__ = "numpy" import logging from pathlib import Path import pandas as pd from gamestonk_terminal.decorators import log_start_end logger = logging.getLogger(__name__) @log_start_end(log=logger) def load(file: str) -> pd.DataFrame:
64
64
119
19
45
minhhoang1023/GamestonkTerminal
gamestonk_terminal/custom/custom_model.py
Python
load
load
14
34
14
15
bf5f894b0ec6f4dd4db35e4fd7e0dcafb3d03240
bigcode/the-stack
train
adfa90a84786a1b3d2c09d78
train
function
@click.command() @click.option('--cache-file', '-f', default='spoke.sqlite3') def update_cache(cache_file): api = get_api() cache = HubCache(api, cache_file) cache.update()
@click.command() @click.option('--cache-file', '-f', default='spoke.sqlite3') def update_cache(cache_file):
api = get_api() cache = HubCache(api, cache_file) cache.update()
import click from spoke.cache import HubCache from spoke.hubapi import get_api @click.command() @click.option('--cache-file', '-f', default='spoke.sqlite3') def update_cache(cache_file):
44
64
45
25
18
valohai/spoke
spoke/commands/cache_commands.py
Python
update_cache
update_cache
7
12
7
9
5bae0238e695172d5f1fdf9a96b461d4ff2cc06a
bigcode/the-stack
train
24c683f8b84e0f06b808e185
train
function
def random_zeropri_transaction(nodes, amount, min_fee, fee_increment, fee_variants): """ Create a random zero-priority transaction. Returns (txid, hex-encoded-transaction-data, fee) """ from_node = random.choice(nodes) to_node = random.choice(nodes) fee = min_fee + fee_increment*random.randi...
def random_zeropri_transaction(nodes, amount, min_fee, fee_increment, fee_variants):
""" Create a random zero-priority transaction. Returns (txid, hex-encoded-transaction-data, fee) """ from_node = random.choice(nodes) to_node = random.choice(nodes) fee = min_fee + fee_increment*random.randint(0,fee_variants) (txid, txhex) = send_zeropri_transaction(from_node, to_node, a...
transaction(inputs, outputs) signresult = from_node.signrawtransaction(rawtx) txid = from_node.sendrawtransaction(signresult["hex"], True) return (txid, signresult["hex"]) def random_zeropri_transaction(nodes, amount, min_fee, fee_increment, fee_variants):
64
64
117
20
44
2ovob4ehko/bandera-coin
qa/rpc-tests/util.py
Python
random_zeropri_transaction
random_zeropri_transaction
300
309
300
300
a543e6dd9cb8eeed2316ece50f9097de2615636e
bigcode/the-stack
train
ecfae826b78185650057ab42
train
function
def make_change(from_node, amount_in, amount_out, fee): """ Create change output(s), return them """ outputs = {} amount = amount_out+fee change = amount_in - amount if change > amount*2: # Create an extra change output to break up big inputs change_address = from_node.getnew...
def make_change(from_node, amount_in, amount_out, fee):
""" Create change output(s), return them """ outputs = {} amount = amount_out+fee change = amount_in - amount if change > amount*2: # Create an extra change output to break up big inputs change_address = from_node.getnewaddress() # Split change in two, being careful o...
"], "address" : t["address"] } ) if total_in < amount_needed: raise RuntimeError("Insufficient funds: need %d, have %d"%(amount_needed, total_in)) return (total_in, inputs) def make_change(from_node, amount_in, amount_out, fee):
64
64
153
14
50
2ovob4ehko/bandera-coin
qa/rpc-tests/util.py
Python
make_change
make_change
253
268
253
253
76e9d5d71273e17abe723e83c0c129e0c88bbec9
bigcode/the-stack
train
8f51a72c9522331c3d9340f9
train
function
def connect_nodes(from_connection, node_num): ip_port = "127.0.0.1:"+str(p2p_port(node_num)) from_connection.addnode(ip_port, "onetry") # poll until version handshake complete to avoid race conditions # with transaction relaying while any(peer['version'] == 0 for peer in from_connection.getpeerinfo(...
def connect_nodes(from_connection, node_num):
ip_port = "127.0.0.1:"+str(p2p_port(node_num)) from_connection.addnode(ip_port, "onetry") # poll until version handshake complete to avoid race conditions # with transaction relaying while any(peer['version'] == 0 for peer in from_connection.getpeerinfo()): time.sleep(0.1)
nodes: node.setmocktime(t) def wait_bitcoinds(): # Wait for all bitcoinds to cleanly exit for bitcoind in bitcoind_processes.values(): bitcoind.wait() bitcoind_processes.clear() def connect_nodes(from_connection, node_num):
64
64
88
9
55
2ovob4ehko/bandera-coin
qa/rpc-tests/util.py
Python
connect_nodes
connect_nodes
212
218
212
212
a0bfe427bd92988d52e47646d404e0097121a083
bigcode/the-stack
train
851cfdf0f08f8d05851dd55f
train
function
def stop_node(node, i): node.stop() bitcoind_processes[i].wait() del bitcoind_processes[i]
def stop_node(node, i):
node.stop() bitcoind_processes[i].wait() del bitcoind_processes[i]
return [ start_node(i, dirname, extra_args[i], rpchost) for i in range(num_nodes) ] def log_filename(dirname, n_node, logname): return os.path.join(dirname, "node"+str(n_node), "regtest", logname) def stop_node(node, i):
64
64
30
7
57
2ovob4ehko/bandera-coin
qa/rpc-tests/util.py
Python
stop_node
stop_node
192
195
192
192
f1719fb5f10e6b5b591cf895f17a2a5e948c7057
bigcode/the-stack
train
29a2491db1b4abc5b0ea7026
train
function
def initialize_datadir(dirname, n): datadir = os.path.join(dirname, "node"+str(n)) if not os.path.isdir(datadir): os.makedirs(datadir) with open(os.path.join(datadir, "bandera.conf"), 'w') as f: f.write("regtest=1\n"); f.write("rpcuser=rt\n"); f.write("rpcpassword=rt\n"); ...
def initialize_datadir(dirname, n):
datadir = os.path.join(dirname, "node"+str(n)) if not os.path.isdir(datadir): os.makedirs(datadir) with open(os.path.join(datadir, "bandera.conf"), 'w') as f: f.write("regtest=1\n"); f.write("rpcuser=rt\n"); f.write("rpcpassword=rt\n"); f.write("port="+str(p2p_port(n)...
(rpc_connections)): if set(rpc_connections[i].getrawmempool()) == pool: num_match = num_match+1 if num_match == len(rpc_connections): break time.sleep(1) bitcoind_processes = {} def initialize_datadir(dirname, n):
64
64
125
8
56
2ovob4ehko/bandera-coin
qa/rpc-tests/util.py
Python
initialize_datadir
initialize_datadir
66
76
66
66
a1b29dc5da36f25e22d0f176f94fe3e978b907b6
bigcode/the-stack
train
40227cdf25487e1114a7ff30
train
function
def p2p_port(n): return 11000 + n + os.getpid()%999
def p2p_port(n):
return 11000 + n + os.getpid()%999
(os.path.abspath(__file__)), "python-bitcoinrpc")) from decimal import Decimal, ROUND_DOWN import json import random import shutil import subprocess import time import re from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException from util import * def p2p_port(n):
64
64
21
7
57
2ovob4ehko/bandera-coin
qa/rpc-tests/util.py
Python
p2p_port
p2p_port
27
28
27
27
0568549ef406e524021554d76611166896c5e16b
bigcode/the-stack
train
7286ff803f73e5fa147d7462
train
function
def initialize_chain_clean(test_dir, num_nodes): """ Create an empty blockchain and num_nodes wallets. Useful if a test case wants complete control over initialization. """ for i in range(num_nodes): datadir=initialize_datadir(test_dir, i)
def initialize_chain_clean(test_dir, num_nodes):
""" Create an empty blockchain and num_nodes wallets. Useful if a test case wants complete control over initialization. """ for i in range(num_nodes): datadir=initialize_datadir(test_dir, i)
", "node"+str(i)) to_dir = os.path.join(test_dir, "node"+str(i)) shutil.copytree(from_dir, to_dir) initialize_datadir(test_dir, i) # Overwrite port/rpcport in bandera.conf def initialize_chain_clean(test_dir, num_nodes):
64
64
56
10
53
2ovob4ehko/bandera-coin
qa/rpc-tests/util.py
Python
initialize_chain_clean
initialize_chain_clean
135
141
135
135
d9129ac3762f06d2f67c3d8f7475d292b190422b
bigcode/the-stack
train
369479bd4aef161bca4c830e
train
function
def assert_equal(thing1, thing2): if thing1 != thing2: raise AssertionError("%s != %s"%(str(thing1),str(thing2)))
def assert_equal(thing1, thing2):
if thing1 != thing2: raise AssertionError("%s != %s"%(str(thing1),str(thing2)))
rawtx = from_node.createrawtransaction(inputs, outputs) signresult = from_node.signrawtransaction(rawtx) txid = from_node.sendrawtransaction(signresult["hex"], True) return (txid, signresult["hex"], fee) def assert_equal(thing1, thing2):
64
64
38
10
54
2ovob4ehko/bandera-coin
qa/rpc-tests/util.py
Python
assert_equal
assert_equal
330
332
330
330
87f63144df876e66e949ce817aad86eca6cb3abc
bigcode/the-stack
train
70bf12e0ac2350f24d4f8b26
train
function
def connect_nodes_bi(nodes, a, b): connect_nodes(nodes[a], b) connect_nodes(nodes[b], a)
def connect_nodes_bi(nodes, a, b):
connect_nodes(nodes[a], b) connect_nodes(nodes[b], a)
(ip_port, "onetry") # poll until version handshake complete to avoid race conditions # with transaction relaying while any(peer['version'] == 0 for peer in from_connection.getpeerinfo()): time.sleep(0.1) def connect_nodes_bi(nodes, a, b):
64
64
27
11
53
2ovob4ehko/bandera-coin
qa/rpc-tests/util.py
Python
connect_nodes_bi
connect_nodes_bi
220
222
220
220
3ecf5ff8315756e072936ca6f3ba584c79cb11a1
bigcode/the-stack
train
cd587c40fb77f2b10e60a21d
train
function
def check_json_precision(): """Make sure json library being used does not lose precision converting BTC values""" n = Decimal("20000000.00000003") satoshis = int(json.loads(json.dumps(float(n)))*1.0e8) if satoshis != 2000000000000003: raise RuntimeError("JSON encode/decode loses precision")
def check_json_precision():
"""Make sure json library being used does not lose precision converting BTC values""" n = Decimal("20000000.00000003") satoshis = int(json.loads(json.dumps(float(n)))*1.0e8) if satoshis != 2000000000000003: raise RuntimeError("JSON encode/decode loses precision")
from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException from util import * def p2p_port(n): return 11000 + n + os.getpid()%999 def rpc_port(n): return 12000 + n + os.getpid()%999 def check_json_precision():
64
64
80
5
58
2ovob4ehko/bandera-coin
qa/rpc-tests/util.py
Python
check_json_precision
check_json_precision
32
37
32
32
ad7e4d25a16ab6766304b8df5eaf0f8f9c5d66b1
bigcode/the-stack
train
5542bdc492c4b41f1911972f
train
function
def set_node_times(nodes, t): for node in nodes: node.setmocktime(t)
def set_node_times(nodes, t):
for node in nodes: node.setmocktime(t)
, i): node.stop() bitcoind_processes[i].wait() del bitcoind_processes[i] def stop_nodes(nodes): for node in nodes: node.stop() del nodes[:] # Emptying array closes connections as a side effect def set_node_times(nodes, t):
64
64
21
8
55
2ovob4ehko/bandera-coin
qa/rpc-tests/util.py
Python
set_node_times
set_node_times
202
204
202
202
a014aa1ded358fbdc6966d1868ab9857f44c17f8
bigcode/the-stack
train
698d7d7c1879378a880d21be
train
function
def start_nodes(num_nodes, dirname, extra_args=None, rpchost=None): """ Start multiple banderads, return RPC connections to them """ if extra_args is None: extra_args = [ None for i in range(num_nodes) ] return [ start_node(i, dirname, extra_args[i], rpchost) for i in range(num_nodes) ]
def start_nodes(num_nodes, dirname, extra_args=None, rpchost=None):
""" Start multiple banderads, return RPC connections to them """ if extra_args is None: extra_args = [ None for i in range(num_nodes) ] return [ start_node(i, dirname, extra_args[i], rpchost) for i in range(num_nodes) ]
:%d" % (rpchost or '127.0.0.1', rpc_port(i)) proxy = AuthServiceProxy(url) proxy.url = url # store URL on proxy for info return proxy def start_nodes(num_nodes, dirname, extra_args=None, rpchost=None):
64
64
79
17
46
2ovob4ehko/bandera-coin
qa/rpc-tests/util.py
Python
start_nodes
start_nodes
182
187
182
182
ee6e4addd3bf95735f0ed1fcf41e5f4a945f3864
bigcode/the-stack
train
947e3bf6181e98ab1284978f
train
function
def _rpchost_to_args(rpchost): '''Convert optional IP:port spec to rpcconnect/rpcport args''' if rpchost is None: return [] match = re.match('(\[[0-9a-fA-f:]+\]|[^:]+)(?::([0-9]+))?$', rpchost) if not match: raise ValueError('Invalid RPC host spec ' + rpchost) rpcconnect = match.gr...
def _rpchost_to_args(rpchost):
'''Convert optional IP:port spec to rpcconnect/rpcport args''' if rpchost is None: return [] match = re.match('(\[[0-9a-fA-f:]+\]|[^:]+)(?::([0-9]+))?$', rpchost) if not match: raise ValueError('Invalid RPC host spec ' + rpchost) rpcconnect = match.group(1) rpcport = match.grou...
_clean(test_dir, num_nodes): """ Create an empty blockchain and num_nodes wallets. Useful if a test case wants complete control over initialization. """ for i in range(num_nodes): datadir=initialize_datadir(test_dir, i) def _rpchost_to_args(rpchost):
64
64
171
11
53
2ovob4ehko/bandera-coin
qa/rpc-tests/util.py
Python
_rpchost_to_args
_rpchost_to_args
144
162
144
144
90ea5f2bb47c88c32719b90dcaccc98bef081be0
bigcode/the-stack
train