Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Here is a snippet: <|code_start|> files[k] = val return files def get_headers(request, hide_env=True): """Returns headers dict from request context.""" headers = dict(request.headers.items()) if hide_env and ('show_env' not in request.args): for key in ENV_HEADERS: tr...
else:
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- def test_multidict(): d = MultiDict({'a': 1, 'b': 'a'}) assert d['a'] == 1 assert d['b'] == 'a' d['a'] = 2 assert d['a'] == 2 assert d.getlist('a') == [2] d['a'] = [1, 2] assert d['a'] == ...
d['b'] = [1, 2, 3]
Based on the snippet: <|code_start|> assert parse_query_string(qs) == expect @pytest.mark.parametrize('key, expect', [ ('abc', 'Abc'), ('abc_name', 'Abc_name'), ('UserAgent', 'Useragent'), ('user-Agent', 'User-Agent'), ('x-rage', 'X-Rage'), ]) def test_to_header_key(key, expect): assert to_...
@pytest.mark.parametrize('value, expect', [
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*- def test_multidict(): d = MultiDict({'a': 1, 'b': 'a'}) assert d['a'] == 1 assert d['b'] == 'a' d['a'] = 2 assert d['a'] == 2 assert d.getlist('a') == [2] d['a'] = [1, 2] assert d['a'] == 2 <|code_end|> . Use current f...
assert d.getlist('a') == [1, 2]
Using the snippet: <|code_start|># -*- coding: utf-8 -*- def test_multidict(): d = MultiDict({'a': 1, 'b': 'a'}) assert d['a'] == 1 assert d['b'] == 'a' d['a'] = 2 assert d['a'] == 2 assert d.getlist('a') == [2] d['a'] = [1, 2] <|code_end|> , determine the next line of code. You have im...
assert d['a'] == 2
Predict the next line after this snippet: <|code_start|>@pytest.mark.parametrize('key, expect', [ ('abc', 'Abc'), ('abc_name', 'Abc_name'), ('UserAgent', 'Useragent'), ('user-Agent', 'User-Agent'), ('x-rage', 'X-Rage'), ]) def test_to_header_key(key, expect): assert to_header_key(key) == expect ...
('Basic user:passwd', None),
Here is a snippet: <|code_start|>@pytest.mark.parametrize('qs, expect', [ ('a=b', {'a': ['b']}), ('a=b&a=c', {'a': ['b', 'c']}), ('a=b&d&a=c', {'a': ['b', 'c']}), ('a=b&d=abc&a=c', {'a': ['b', 'c'], 'd': ['abc']}), ]) def test_parse_query_string(qs, expect): assert parse_query_string(qs) == expect ...
('abc', b'abc'),
Continue the code snippet: <|code_start|> @pytest.mark.parametrize('key, expect', [ ('abc', 'Abc'), ('abc_name', 'Abc_name'), ('UserAgent', 'Useragent'), ('user-Agent', 'User-Agent'), ('x-rage', 'X-Rage'), ]) def test_to_header_key(key, expect): assert to_header_key(key) == expect @pytest.mar...
('', None),
Predict the next line after this snippet: <|code_start|> @pytest.mark.parametrize('st, expect', [ (b'abc', 'abc'), ('你好'.encode('utf8'), '你好'), ]) def test_to_text(st, expect): assert to_text(st) == expect @pytest.mark.parametrize('bt, expect', [ ('abc', b'abc'), ('你好', '你好'.encode('utf8')), ]) d...
def test_parse_basic_auth_header(value, expect):
Predict the next line for this snippet: <|code_start|># You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS ...
def topic(self, (solr, result)):
Continue the code snippet: <|code_start|># http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License...
expect(topic).to_include(('hl.simple.post', '</em>'))
Predict the next line for this snippet: <|code_start|># distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # @Vows.batch c...
def mustMatch(self, topic):
Predict the next line after this snippet: <|code_start|> 'maxwl', 'maxqt', 'maxntp', 'boost', 'qf', 'count'] for v in valid_params: kwargs = {v: 'a'} q = MoreLikeThisQuery(['conten...
expect(topic).to_include(('mlt', 'true'))
Using the snippet: <|code_start|> return SpatialQuery(lat, lon, sfield).get_params() def mustIncludeFunctionTypeParameter(self, topic): expect(topic).to_include(('fq', '{!geofilt}')) def mustIncludeCorrectlyFormattedPoint(self, topic): expect(topic).to_include(('pt',...
sfield = "my_field"
Using the snippet: <|code_start|> sfield = "my_field" return SpatialQuery(lat, lon, sfield).get_params() def mustIncludeFunctionTypeParameter(self, topic): expect(topic).to_include(('fq', '{!geofilt}')) def mustIncludeCorrectlyFormattedPoint(self, topic): ...
lon = 0.0
Given snippet: <|code_start|># # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the s...
def mustIncludeDistanceParameter(self, topic):
Predict the next line after this snippet: <|code_start|> @Vows.batch class TheSimpleBoostQuery(Vows.Context): def topic(self): return BoostQuery('test:Title').get_params() def shouldContainTheBqParameter(self, topic): expect(topic).to_include(('bq', 'test:Title')) @Vows.batch class TheBoost...
expect(topic).to_include(('bf', 'test:This + $date'))
Based on the snippet: <|code_start|> @Vows.batch class TheBoostFunctionQuery(Vows.Context): class WithRequiredParams(Vows.Context): def topic(self): return BoostFunctionQuery('test:This').get_params() def shouldIncludeTheBfParameter(self, topic): expect(topic).to_include((...
def shouldNotIncludeTheExternalParam(self, topic):
Next line prediction: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writin...
def mustIncludeTheOnlyMorePopularParam(self, topic):
Based on the snippet: <|code_start|># See the License for the specific language governing permissions and # limitations under the License. # # @Vows.batch class WhenDoingJoins(Vows.Context): class WithinTheQuery(Vows.Context): def topic(self): from_field = "from_field" to_field ...
from_field = "from_field"
Predict the next line for this snippet: <|code_start|># Copyright (c) 2011 Daniel Truemper <truemped at googlemail.com> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache...
for data in test_data:
Predict the next line for this snippet: <|code_start|># # @Vows.batch class WhenGroupingResults(Vows.Context): class WithNoParametersExceptTheField(Vows.Context): def topic(self): field = "my_field" return ResultGrouping(field).get_params() def mustIncludeGroupingParame...
expect(topic).to_include(('group.query', 'field:value'))
Given the code snippet: <|code_start|> def noUnexpectedArgs(self, topic): expect(topic).to_length(2) class WithOptionalParameters(WithDefaultParams): def topic(self): valid_params = [ 'alt', 'mm', 'pf', 'ps', ...
expect(params).to_length(3)
Predict the next line for this snippet: <|code_start|> if __name__ == "__main__": app = create_qapp() database = get_database() <|code_end|> with the help of current file imports: from datetime import datetime from vnpy.trader.ui import create_qapp, QtCore from vnpy.trader.constant import Exchange, Interva...
bars = database.load_bar_data(
Based on the snippet: <|code_start|> if __name__ == "__main__": app = create_qapp() database = get_database() bars = database.load_bar_data( <|code_end|> , predict the immediate next line with the help of imports: from datetime import datetime from vnpy.trader.ui import create_qapp, QtCore from vnpy.tra...
"IF888",
Given the following code snippet before the placeholder: <|code_start|> if __name__ == "__main__": app = create_qapp() database = get_database() bars = database.load_bar_data( "IF888", Exchange.CFFEX, interval=Interval.MINUTE, start=datetime(2019, 7, 1), end=dateti...
bar = new_data.pop(0)
Given the following code snippet before the placeholder: <|code_start|> if __name__ == "__main__": app = create_qapp() database = get_database() bars = database.load_bar_data( "IF888", Exchange.CFFEX, interval=Interval.MINUTE, start=datetime(2019, 7, 1), end=dateti...
widget.add_plot("volume", maximum_height=200)
Given snippet: <|code_start|> except: exception('Error calculating subitem averages') return avg_list def CalculateArrayAverage(self, avg_array, new_array, count): if len(avg_array) == 0: return new_array try: for key in avg_array: ...
if 'SystemInfo' not in new_sample or new_sample['SystemInfo'] is None:
Given the code snippet: <|code_start|> averageSensorsDictionary[value['sensor']]['percent'] = self.CalculateAverage(averageSensorsDictionary[value['sensor']]['percent'], value['percent'], count_sensor['SensorsInfo'][value['sensor']] ) if value['type'] ...
def SaveAverages(self, data):
Based on the snippet: <|code_start|> # averageSensorsDictionary[value['sensor']]['all'] = self.CalculateArrayAverage(averageSensorsDictionary[value['sensor']]['all'], value['all'], count_sensor['SensorsInfo'][value['sensor']]) # if value['type'] == 'PiF...
count += 1
Given the following code snippet before the placeholder: <|code_start|> self.cursor.execute('INSERT INTO historical_averages VALUES (NULL,?,?,?,?,?,?,?)', (dumps(self.avg_values), self.count, self.start_time, self.end_time, History.RUNNING, History.NOT_READY, dumps(self.count_sensor))) se...
self.cursor.execute('SELECT id, data, start, end FROM historical_averages WHERE interval = ? AND send = ? ORDER BY end ASC LIMIT 1', (interval, History.READY))
Given the following code snippet before the placeholder: <|code_start|> class SystemConfigTest(unittest.TestCase): def testSystemConfig(self): config = SystemConfig.getConfig() info(config) <|code_end|> , predict the next line using imports from the current file: import unittest from myDevices.sys...
if config:
Using the snippet: <|code_start|> class SystemConfigTest(unittest.TestCase): def testSystemConfig(self): config = SystemConfig.getConfig() info(config) <|code_end|> , determine the next line of code. You have imports: import unittest from myDevices.system.systemconfig import SystemConfig from myDe...
if config:
Continue the code snippet: <|code_start|> class SystemConfigTest(unittest.TestCase): def testSystemConfig(self): config = SystemConfig.getConfig() info(config) if config: for item in ('DeviceTree', 'Serial', 'I2C', 'SPI', 'OneWire'): <|code_end|> . Use current file imports: imp...
self.assertIn(item, config)
Given the code snippet: <|code_start|> self.connection.close() except: exception('Error deleting SchedulerEngine') def load_schedule(self): """Load saved scheduler events from the database""" with self.mutex: self.cursor.execute('SELECT * FROM scheduled_ev...
if result == True:
Given snippet: <|code_start|> self.schedule_items.clear() self.remove_all_database_records() except: exception('Failed to remove scheduled events') return False return True def remove_scheduled_item_by_id(self, remove_id): """Remove a s...
with self.mutex:
Next line prediction: <|code_start|> class SchedulerEngine(Thread): """Class that creates the scheduler and launches scheduled actions""" def __init__(self, client, name): """Initialize the scheduler and start the scheduler thread client: the client running the scheduler name...
self.running = False
Next line prediction: <|code_start|> if config['unit'] == 'hour': schedule_item['job'] = schedule.every(config['interval'], config['start_date']).hours if config['unit'] == 'minute': schedule_item['job'] = schedule.every(config['inte...
config = event['config']
Using the snippet: <|code_start|> return True except KeyError: warn('Key error removing scheduled item: {}'.format(remove_id)) error('Remove id not found: {}'.format(remove_id)) return False def create_job(self, schedule_item): ...
schedule_item['job'].set_last_run(schedule_item['event']['last_run'])
Here is a snippet: <|code_start|> return False def create_job(self, schedule_item): """Create a job to run a scheduled item schedule_item: the item containing the event to be run at the scheduled time""" debug('Create job: {}'.format(schedule_item)) try: ...
return False
Predict the next line for this snippet: <|code_start|> class SystemInfoTest(unittest.TestCase): def setUp(self): setInfo() system_info = SystemInfo() self.info = {item['channel']:item for item in system_info.getSystemInformation()} info(self.info) <|code_end|> with the help of cur...
def testSystemInfo(self):
Continue the code snippet: <|code_start|> connection = None cursor = None mutex = RLock() class DbManager(Singleton): def CreateTable(tablename, columns, required_columns = None): <|code_end|> . Use current file imports: from sqlite3 import connect from myDevices.utils.logger import exception, info, warn, error, ...
try:
Using the snippet: <|code_start|> connection = None cursor = None mutex = RLock() class DbManager(Singleton): def CreateTable(tablename, columns, required_columns = None): try: with mutex: if not cursor or not connection: return False if requi...
pass
Here is a snippet: <|code_start|> cursor.execute(statement) connection.commit() return True def Delete(tablename, id): if not cursor or not connection: return False with mutex: statement = 'DELETE FROM ' + tablename + ' WHERE id = ?' ...
rowId = DbManager.Insert(tablename, idtest)
Given the following code snippet before the placeholder: <|code_start|> # Topics DATA_TOPIC = 'data/json' COMMAND_TOPIC = 'cmd' COMMAND_JSON_TOPIC = 'cmd.json' COMMAND_RESPONSE_TOPIC = 'response' JOBS_TOPIC = 'jobs.json' # Data Channels SYS_HARDWARE_MAKE = 'sys:hw:make' SYS_HARDWARE_MODEL = 'sys:hw:model' SYS_OS_NAME ...
SYS_OS_VERSION = 'sys:os:version'
Given snippet: <|code_start|> # Topics DATA_TOPIC = 'data/json' COMMAND_TOPIC = 'cmd' COMMAND_JSON_TOPIC = 'cmd.json' COMMAND_RESPONSE_TOPIC = 'response' JOBS_TOPIC = 'jobs.json' # Data Channels SYS_HARDWARE_MAKE = 'sys:hw:make' SYS_HARDWARE_MODEL = 'sys:hw:model' SYS_OS_NAME = 'sys:os:name' SYS_OS_VERSION = 'sys:os:v...
AGENT_SCHEDULER = 'agent:scheduler'
Predict the next line after this snippet: <|code_start|> # Topics DATA_TOPIC = 'data/json' COMMAND_TOPIC = 'cmd' COMMAND_JSON_TOPIC = 'cmd.json' COMMAND_RESPONSE_TOPIC = 'response' JOBS_TOPIC = 'jobs.json' # Data Channels SYS_HARDWARE_MAKE = 'sys:hw:make' SYS_HARDWARE_MODEL = 'sys:hw:model' SYS_OS_NAME = 'sys:os:name'...
SYS_SPI = 'sys:spi'
Next line prediction: <|code_start|> os.close(self.fd) self.fd = 0 self.family = family if slave != None: addr = slave.split("-") if len(addr) == 1: self.slave = "%02x-%s" % (family, slave) elif len(addr) == 2: ...
for line in lines:
Using the snippet: <|code_start|> class OneWire(Bus): def __init__(self, slave=None, family=0, extra=None): Bus.__init__(self, "ONEWIRE", "/sys/bus/w1/devices/w1_bus_master1/w1_master_slaves", os.O_RDONLY) if self.fd > 0: os.close(self.fd) self.fd = 0 self.family = f...
devices = []
Here is a snippet: <|code_start|> LOGGER.info(message) def warn(message): if checkFlood(message): return LOGGER.warn(message) def error(message, *args, **kwargs): if checkFlood(message): return LOGGER.error(message, *args, **kwargs) def exception(message): if checkFlood(message...
rotatorJson()
Given the following code snippet before the placeholder: <|code_start|> if __name__ == '__main__': # Run the code to disable a plugin in a script so it can be called via sudo setInfo() info(sys.argv) if len(sys.argv) != 3: error('Plugin not disabled, invalid arguments') <|code_end|> , predict th...
sys.exit(1)
Based on the snippet: <|code_start|> if __name__ == '__main__': # Run the code to disable a plugin in a script so it can be called via sudo setInfo() info(sys.argv) if len(sys.argv) != 3: error('Plugin not disabled, invalid arguments') sys.exit(1) filename = sys.argv[1] if filena...
if section in config.sections():
Given the code snippet: <|code_start|> if __name__ == '__main__': # Run the code to disable a plugin in a script so it can be called via sudo setInfo() info(sys.argv) if len(sys.argv) != 3: error('Plugin not disabled, invalid arguments') sys.exit(1) <|code_end|> , generate the next line ...
filename = sys.argv[1]
Continue the code snippet: <|code_start|> if __name__ == '__main__': # Run the code to disable a plugin in a script so it can be called via sudo setInfo() info(sys.argv) if len(sys.argv) != 3: error('Plugin not disabled, invalid arguments') sys.exit(1) filename = sys.argv[1] if f...
if section in config.sections():
Given snippet: <|code_start|> if __name__ == '__main__': # Run the code to disable a plugin in a script so it can be called via sudo setInfo() info(sys.argv) if len(sys.argv) != 3: error('Plugin not disabled, invalid arguments') sys.exit(1) <|code_end|> , continue by predicting the next ...
filename = sys.argv[1]
Using the snippet: <|code_start|> speed = getattr(termios, aname) # input speed options[4] = speed # output speed options[5] = speed termios.tcsetattr(self.fd, termios.TCSADRAIN, options) def __str__(self): return "Serial(%s, %dbps)" % (self.d...
self.write(data)
Given snippet: <|code_start|> self.appSettings = config self.onUpdateConfig = onUpdateConfig self.env = self.appSettings.get('Agent', 'Environment', fallback='live') global SETUP_URL global UPDATE_URL if self.env == 'live': SETUP_URL = SETUP_URL + SETUP_NAME ...
self.Continue = False
Predict the next line for this snippet: <|code_start|>TIME_TO_CHECK = 60 + random.randint(60, 300) #seconds - at least 2 minutes TIME_TO_SLEEP = 60 UPDATE_URL = 'https://updates.mydevices.com/raspberry/updatecfg' SETUP_URL = 'https://updates.mydevices.com/raspberry/' try: # For Python 3.0 and later except ImportEr...
self.scheduler = scheduler(time, sleep)
Based on the snippet: <|code_start|> debug('Updater cleanup executes delete') rmtree(UPDATE_PATH) return except: exception('UpdateCleanup error') def CheckUpdate(self): doUpdates = self.appSettings.get('Agent', 'DoUpdates', 'tru...
self.currentVersion = self.appSettings.get('Agent', 'Version', fallback=None)
Predict the next line for this snippet: <|code_start|> SETUP_NAME = 'update_raspberrypi.sh' INSTALL_PATH = '/etc/myDevices/' UPDATE_PATH = INSTALL_PATH + 'updates/' UPDATE_CFG = UPDATE_PATH + 'updatecfg' SETUP_PATH = UPDATE_PATH + SETUP_NAME TIME_TO_CHECK = 60 + random.randint(60, 300) #seconds - at least 2 minutes TI...
class Updater(Thread):
Here is a snippet: <|code_start|> def DownloadFile(self, url, localPath): try: info(url + ' ' + localPath) with urlopen(url) as response: with open(localPath, 'wb') as output: output.write(response.read()) debug('Updater download success...
bVal = LooseVersion(currentVersion) < LooseVersion(newVersion)
Given the code snippet: <|code_start|> SETUP_NAME = 'update_raspberrypi.sh' INSTALL_PATH = '/etc/myDevices/' UPDATE_PATH = INSTALL_PATH + 'updates/' UPDATE_CFG = UPDATE_PATH + 'updatecfg' SETUP_PATH = UPDATE_PATH + SETUP_NAME TIME_TO_CHECK = 60 + random.randint(60, 300) #seconds - at least 2 minutes TIME_TO_SLEEP = 60...
self.setDaemon(True)
Predict the next line for this snippet: <|code_start|> class ApiClientTest(unittest.TestCase): def testMessageBody(self): cayenneApiClient = CayenneApiClient('https://api.mydevices.com') message = loads(cayenneApiClient.getMessageBody('invite_code')) # info(message) self.assertIn('i...
self.assertIn('sysinfo', message['properties'])
Using the snippet: <|code_start|> class ApiClientTest(unittest.TestCase): def testMessageBody(self): cayenneApiClient = CayenneApiClient('https://api.mydevices.com') message = loads(cayenneApiClient.getMessageBody('invite_code')) # info(message) self.assertIn('id', message) ...
self.assertIn('sysinfo', message['properties'])
Predict the next line after this snippet: <|code_start|> value_dict['value'] = value[0] value_dict['type'] = value[1] value_dict['unit'] = value[2] except: if not value_dict: value_dict['value'] = value if 'type' in value_dict and 'unit'...
if actuator in self.plugins.keys():
Using the snippet: <|code_start|> except: if not value_dict: value_dict['value'] = value if 'type' in value_dict and 'unit' not in value_dict: if value_dict['type'] in ('digital_sensor', 'digital_actuator'): value_dict['unit'] = 'd' ...
write_args = self.get_args(self.plugins[actuator], 'write_args')
Given the code snippet: <|code_start|> if value_dict['type'] in ('digital_sensor', 'digital_actuator'): value_dict['unit'] = 'd' elif value_dict['type'] in ('analog_sensor', 'analog_actuator'): value_dict['unit'] = 'null' return value_dict ...
return False
Predict the next line for this snippet: <|code_start|> return value_dict def is_plugin(self, plugin, channel=None): """Returns True if the specified plugin or plugin:channel are valid plugins.""" try: key = plugin if channel is not None: key = plugin +...
else:
Based on the snippet: <|code_start|> value_dict['unit'] = 'd' elif value_dict['type'] in ('analog_sensor', 'analog_actuator'): value_dict['unit'] = 'null' return value_dict def is_plugin(self, plugin, channel=None): """Returns True if the speci...
except Exception as e:
Given the following code snippet before the placeholder: <|code_start|> value_dict['value'] = value if 'type' in value_dict and 'unit' not in value_dict: if value_dict['type'] in ('digital_sensor', 'digital_actuator'): value_dict['unit'] = 'd' ...
except KeyError as e:
Using the snippet: <|code_start|> if value_dict['type'] in ('digital_sensor', 'digital_actuator'): value_dict['unit'] = 'd' elif value_dict['type'] in ('analog_sensor', 'analog_actuator'): value_dict['unit'] = 'null' return value_dict d...
return False
Predict the next line after this snippet: <|code_start|> class HarwareTest(unittest.TestCase): def setUp(self): setInfo() self.hardware = Hardware() def testGetManufacturer(self): manufacturer = self.hardware.getManufacturer() info(manufacturer) self.assertNotEqual(manuf...
self.assertNotEqual(model, 'Unknown')
Given the code snippet: <|code_start|> class HarwareTest(unittest.TestCase): def setUp(self): setInfo() self.hardware = Hardware() def testGetManufacturer(self): manufacturer = self.hardware.getManufacturer() info(manufacturer) self.assertNotEqual(manufacturer, '') ...
mac = self.hardware.getMac()
Here is a snippet: <|code_start|> class HarwareTest(unittest.TestCase): def setUp(self): setInfo() self.hardware = Hardware() def testGetManufacturer(self): <|code_end|> . Write the next line using the current file imports: import unittest from myDevices.utils.logger import setInfo, info from ...
manufacturer = self.hardware.getManufacturer()
Given the following code snippet before the placeholder: <|code_start|> class HarwareTest(unittest.TestCase): def setUp(self): setInfo() self.hardware = Hardware() def testGetManufacturer(self): manufacturer = self.hardware.getManufacturer() info(manufacturer) self.asser...
def testGetMac(self):
Predict the next line for this snippet: <|code_start|> def __init__(self, network: str) -> None: """ : network = peercoin [ppc], peercoin-testnet [tppc] ... """ self.net = self._netname(network)['short'] self.api_url = self.api_url_fmt.format(net=self.format_name(self.net)) ...
raise Exception(response.reason)
Next line prediction: <|code_start|> : network = peercoin [ppc], peercoin-testnet [tppc] ... """ self.net = self._netname(network)['short'] self.api_url = self.api_url_fmt.format(net=self.format_name(self.net)) if 'ppc' in self.net: getcontext().prec = 6 # set to six...
def api_req(self, query: str) -> dict:
Predict the next line for this snippet: <|code_start|> return r.decode() def getdifficulty(self) -> dict: '''Returns the current difficulty.''' return cast(dict, self.api_fetch(''))['backend']['difficulty'] def getblockcount(self) -> int: '''Returns the current bloc...
def getaddress(self, address: str) -> dict:
Predict the next line for this snippet: <|code_start|> return json.loads(r.decode()) except json.decoder.JSONDecodeError: return r.decode() def getdifficulty(self) -> dict: '''Returns the current difficulty.''' return cast(dict, self.api_fetch(''))['backend'][...
return cast(dict, self.api_fetch(q))
Using the snippet: <|code_start|> return json.loads(r.decode()) except json.decoder.JSONDecodeError: return r.decode() def getdifficulty(self) -> dict: '''Returns the current difficulty.''' return cast(dict, self.api_fetch(''))['backend']['difficulty'] ...
return cast(dict, self.api_fetch(q))
Continue the code snippet: <|code_start|>'''Common provider class with basic features.''' class Provider(ABC): net = "" headers = {"User-Agent": "pypeerassets"} @staticmethod def _netname(name: str) -> dict: '''resolute network name, required because some providers use shortnames...
try:
Using the snippet: <|code_start|>'''Common provider class with basic features.''' class Provider(ABC): net = "" headers = {"User-Agent": "pypeerassets"} @staticmethod def _netname(name: str) -> dict: '''resolute network name, required because some providers use shortnames and oth...
def network(self) -> str:
Based on the snippet: <|code_start|>'''Common provider class with basic features.''' class Provider(ABC): net = "" headers = {"User-Agent": "pypeerassets"} @staticmethod def _netname(name: str) -> dict: '''resolute network name, required because some providers use shortnames and ...
return {'long': long,
Here is a snippet: <|code_start|>'''Common provider class with basic features.''' class Provider(ABC): net = "" headers = {"User-Agent": "pypeerassets"} @staticmethod def _netname(name: str) -> dict: '''resolute network name, required because some providers use shortnames and oth...
@property
Given the following code snippet before the placeholder: <|code_start|>'''Common provider class with basic features.''' class Provider(ABC): net = "" headers = {"User-Agent": "pypeerassets"} @staticmethod def _netname(name: str) -> dict: '''resolute network name, required because...
try:
Using the snippet: <|code_start|> '''Communicate with local or remote peercoin-daemon via JSON-RPC''' getcontext().prec = 6 try: except ImportError: raise ImportError("peercoin_rpc library is required for this to work,\ use the pip to install it.") class RpcNode(Client, Provider): '''...
if tx["address"] not in (self.pa_parameters.P2TH_addr,
Based on the snippet: <|code_start|> '''Communicate with local or remote peercoin-daemon via JSON-RPC''' getcontext().prec = 6 try: except ImportError: raise ImportError("peercoin_rpc library is required for this to work,\ use the pip to install it.") class RpcNode(Client, Provider): ...
self.pa_parameters.test_P2TH_addr):
Given snippet: <|code_start|> def test_net_query(): "Check that we can find NetworkParams for networks by name." # Use a network's long name net_params = net_query("peercoin") <|code_end|> , continue by predicting the next line. Consider current file imports: import pytest from pypeerassets.exceptions i...
assert net_params.shortname == "ppc"
Using the snippet: <|code_start|> def test_net_query(): "Check that we can find NetworkParams for networks by name." # Use a network's long name net_params = net_query("peercoin") assert net_params.shortname == "ppc" # Use a network's short name net_params = net_query("tppc") <|code_end|> , ...
assert net_params.name == "peercoin-testnet"
Given the following code snippet before the placeholder: <|code_start|># Install the Peercoin Wallet software and make the testnet rpc server # available. A peercoin.conf with the following options should work: # # testnet=1 # server=1 # txindex=1 # rpcuser=<rpc username> # rpcpassword=<rpc password> RPC_USERNAME = "<...
if transaction["confirmations"] > 0:
Continue the code snippet: <|code_start|> print("Waiting for confirmation...") wait_for_confirmation(rpc_node, card_transfer_tx.txid) print("Friendly Co. Cards created!") print("Double checking the Friendly Co. Deck State...") cards = pa.find_all_valid_cards(rpc_node, deck) deck_state = pa.DeckS...
inputs=rpc_node.select_inputs(ALICE, 0.02),
Next line prediction: <|code_start|> transaction = provider.gettransaction(transaction_id) if transaction["confirmations"] > 0: break time.sleep(10) if __name__ == "__main__": # Deck Spawn print("Build, sign and send the Friendly Co. Deck spawning transaction...") rpc...
provider=rpc_node,
Given snippet: <|code_start|>def test_crypotid_network(): assert Cryptoid(network="ppc").network == "peercoin" def test_cryptoid_getblockcount(): assert isinstance(Cryptoid(network="ppc").getblockcount(), int) def test_cryptoid_getblock(): provider = Cryptoid(network="tppc") assert isinstance(pro...
'PHvDhfz1dGyPbZZ3Qnp56y92zmy98sncZT'), Decimal)
Next line prediction: <|code_start|> class PeercoinTxOut(TxOut): def get_dust_threshold(self, size_to_relay_fee) -> float: if isinstance(self.script_pubkey, NulldataScript): return 0 return 0.01 # constants to be consumed by the backend Constants = namedtuple('Constants', [ '...
'tx_out_cls',
Using the snippet: <|code_start|> return cast(dict, self.api_fetch('getdifficulty')) def getconnectioncount(self) -> int: '''Returns the number of connections the block explorer has to other nodes.''' return cast(int, self.api_fetch('getconnectioncount')) def getblockcount(self) -> int...
def getnetworkghps(self) -> float:
Here is a snippet: <|code_start|> '''Returns the current difficulty.''' return cast(dict, self.api_fetch('getdifficulty')) def getconnectioncount(self) -> int: '''Returns the number of connections the block explorer has to other nodes.''' return cast(int, self.api_fetch('getconnect...
return cast(dict, self.api_fetch(q))
Predict the next line for this snippet: <|code_start|> return cast(dict, self.api_fetch('getdifficulty')) def getconnectioncount(self) -> int: '''Returns the number of connections the block explorer has to other nodes.''' return cast(int, self.api_fetch('getconnectioncount')) def getbl...
def getnetworkghps(self) -> float:
Given the code snippet: <|code_start|> self.assertTrue(m.called_once) self.assertExpectedAuthHeaders() @mock.patch.object( osprofiler.profiler._Profiler, 'get_base_id', mock.MagicMock(return_value=PROFILER_TRACE_ID) ) @mock.patch.object( osprofiler.profiler._...
self.assertEqual(signed_data[0], headers['X-Trace-Info'])
Continue the code snippet: <|code_start|> self.assertEqual(target_project_id, headers['X-Target-Project-Id']) self.assertEqual(str(target_insecure), headers['X-Target-Insecure']) self.assertEqual(target_region, headers['X-Target-Region-Name']) self.assertEqual(target_user_domain_name, ...
headers = self.assertExpectedAuthHeaders()
Based on the snippet: <|code_start|> COLUMNS = [ ('id', 'ID'), ('name', 'Name'), ('is_system', 'Is system'), ('input', 'Input'), ('description', 'Description'), ('tags', 'Tags'), ('created_at', 'Created at'), ('updated_at', 'Updated at'), ] @st...
else: