Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Here is a snippet: <|code_start|>
# This loads the geodata for this city if <city>.geojson exists in the same directory as this file.
geodata = GeoData(__file__)
def parse_html(text_content):
elems = text_content.split("\r\n\r\n")
data = {
"last_updated": convert_date(elems[0], "%d-%m-%Y %H:%M:%S ")... | for elem in elems[1:]: |
Predict the next line after this snippet: <|code_start|>
# This loads the geodata for this city if <city>.geojson exists in the same directory as this file.
geodata = GeoData(__file__)
def parse_html(text_content):
elems = text_content.split("\r\n\r\n")
data = {
"last_updated": convert_date(elems[0]... | state_mappings = { |
Given the code snippet: <|code_start|> #
if ( len(one_row) <= 5 ) :
startingPoint = 0
else :
startingPoint = 1
parking_name = one_row[startingPoint+0].text.strip()
lot = geodata.lot(parking_name)
try :
parking_free = 0
if ( '... | rows = inner_tables[2].find_all('tr') |
Using the snippet: <|code_start|> # inner_tables[0] ist Navi-Leiste, weiter mit first_part[1]
rows = inner_tables[1].find_all('tr')
for row in rows[6:] :
one_row = row.find_all('td')
if ( one_row[0].text == '' ) : continue
#
if ( len(one_row) <= 5 ) :
startingPoin... | "id": lot.id, |
Next line prediction: <|code_start|> 0: "Münsterplatzgarage",
1: "Stadthausgarage",
2: "Beethoven-Parkhaus",
3: "Bahnhofgarage",
4: "Friedensplatzgarage",
5: "Marktgarage",
}
def parse_html(html):
soup = BeautifulSoup(html, "html.parser")
lots = []
for row in soup.find_all("div", ... | "name": name, |
Here is a snippet: <|code_start|> 2: "Beethoven-Parkhaus",
3: "Bahnhofgarage",
4: "Friedensplatzgarage",
5: "Marktgarage",
}
def parse_html(html):
soup = BeautifulSoup(html, "html.parser")
lots = []
for row in soup.find_all("div", class_='parking-lots'):
entity_wrapper_class = 'wp... | "free": free, |
Predict the next line for this snippet: <|code_start|>
# This loads the geodata for this city if <city>.geojson exists in the same directory as this file.
# No need to remove this if there's no geodata (yet), everything will still work.
geodata = GeoData(__file__)
# This function is called by the scraper and given ... | } |
Given the code snippet: <|code_start|>
# This loads the geodata for this city if <city>.geojson exists in the same directory as this file.
# No need to remove this if there's no geodata (yet), everything will still work.
geodata = GeoData(__file__)
# This function is called by the scraper and given the data of the ... | for ph in soup.find_all("parkhaus"): |
Predict the next line after this snippet: <|code_start|> # everything is in table-objects
table=soup.select('table')
# table[0] is a big table-object around everything
# table[1] contains some headers
# table[2] contains column-headers and one row for each parking-lot
# so we look in thi... | data["lots"].append({ |
Continue the code snippet: <|code_start|>
# Additional information for single lots:
# http://www2.ingolstadt.de/Wirtschaft/Parken/Parkeinrichtungen_der_IFG/
geodata = GeoData(__file__)
def parse_html(html):
soup = BeautifulSoup(html, "html.parser")
data = {
"last_updated": convert_date(soup.p.string,... | "name": lot.name, |
Given the following code snippet before the placeholder: <|code_start|>
# Additional information for single lots:
# http://www2.ingolstadt.de/Wirtschaft/Parken/Parkeinrichtungen_der_IFG/
geodata = GeoData(__file__)
def parse_html(html):
soup = BeautifulSoup(html, "html.parser")
data = {
"last_updated... | elements = raw_lot.find_all("td") |
Here is a snippet: <|code_start|>
# This function is called by the scraper and given the data of the page specified as source in geojson above.
# It's supposed to return a dictionary containing everything the current spec expects. Tests will fail if it doesn't ;)
def parse_html(html):
# BeautifulSoup is a great an... | "free": lot_free, |
Based on the snippet: <|code_start|># No need to remove this if there's no geodata (yet), everything will still work.
geodata = GeoData(__file__)
# This function is called by the scraper and given the data of the page specified as source in geojson above.
# It's supposed to return a dictionary containing everything th... | data["lots"].append({ |
Given the following code snippet before the placeholder: <|code_start|>
# BeautifulSoup is a great and easy way to parse the html and find the bits and pieces we're looking for.
soup = BeautifulSoup(html, "html.parser")
# last_updated is the date when the data on the page was last updated, it should be lis... | "total": lot.total, |
Given the code snippet: <|code_start|> data = {
# last_updated like Konstanz
"last_updated": utc_now(),
# URL for the page where the scraper can gather the data
"lots": []
}
table = soup.find('table', id='haupttabelle')
table2 = table.find('table', width='790')
rows =... | "forecast": False, |
Based on the snippet: <|code_start|># This function is called by the scraper and
# given the data of the page specified as data_url above.
# It's supposed to return a dictionary,
# containing everything the current spec expects.
# Tests will fail if it doesn't ;)
def parse_html(html):
# BeautifulSoup is a great and... | td = tr.findAll('td') |
Predict the next line after this snippet: <|code_start|> # BeautifulSoup is a great and easy way to parse the html and
# find the bits and pieces we're looking for.
soup = BeautifulSoup(html, "html.parser")
# last_updated is the date when the data on the page was last updated
last_updated = str(soup... | lot = geodata.lot(parking_name) |
Given snippet: <|code_start|> date_time = div_level1.find('p')
data['last_updated'] = convert_date(date_time.text, 'zuletzt aktualisiert am %d.%m.%Y, %H:%M Uhr')
# find all entries:
div_level2 = div_level1.find('div')
div_level3 = div_level2.find_all('div')
count = 0
while (count < len(div_l... | return data |
Given the following code snippet before the placeholder: <|code_start|>
# This loads the geodata for this city if <city>.geojson exists in the same directory as this file.
# No need to remove this if there's no geodata (yet), everything will still work.
geodata = GeoData(__file__)
# This function is called by the scra... | data = { |
Next line prediction: <|code_start|> # BeautifulSoup is a great and easy way to parse the html and find the bits and pieces we're looking for.
soup = BeautifulSoup(html, "html.parser")
data = {
"last_updated": '', # will fill this later
# URL for the page where the scraper can gather the... | parking_state = 'nodata' |
Continue the code snippet: <|code_start|>
# This loads the geodata for this city if <city>.geojson exists in the same directory as this file.
# No need to remove this if there's no geodata (yet), everything will still work.
geodata = GeoData(__file__)
# This function is called by the scraper and given the data of the ... | "last_updated": '', # will fill this later |
Predict the next line for this snippet: <|code_start|>geodata = GeoData(__file__)
# This function is called by the scraper and given the data of the page specified as source in geojson above.
# It's supposed to return a dictionary containing everything the current spec expects. Tests will fail if it doesn't ;)
def par... | parking_free = int(temp[0]) |
Given the code snippet: <|code_start|>
# This loads the geodata for this city if <city>.geojson exists in the same directory as this file.
# No need to remove this if there's no geodata (yet), everything will still work.
geodata = GeoData(__file__)
# This function is called by the scraper and given the data of the pag... | lots = soup.find_all( 'div', class_='parkhaus') |
Given the code snippet: <|code_start|> updated = soup.find( "p", class_="updateinfo")
last_updated = convert_date(updated.text, 'zuletzt aktualisiert: %d.%m.%Y %H.%M Uhr')
data = {
"last_updated": last_updated,
# URL for the page where the scraper can gather the data
"lots": []
}... | "id": lot.id, |
Based on the snippet: <|code_start|># This loads the geodata for this city if <city>.geojson exists in the same directory as this file.
# No need to remove this if there's no geodata (yet), everything will still work.
geodata = GeoData(__file__)
# This function is called by the scraper and given the data of the page s... | if (parking_belegung != None ) : |
Predict the next line for this snippet: <|code_start|> app.logger.info("GET /" + city + " - " + user_agent(request))
city_module = env.supported_cities().get(city, None)
if city_module is None:
app.logger.info("Unsupported city: " + city)
return ("Error 404: Sorry, '" +
city... | version = request.args['version'] |
Given snippet: <|code_start|> except IndexError:
app.logger.warning("Failed to get static data for " + city)
def update_cache(city):
global cache
with db.cursor() as cursor:
if city in cache:
sql = "SELECT timestamp_downloaded FROM parkapi WHERE city=%s ORDER BY timestamp_dow... | "source": city.public_source, |
Given the following code snippet before the placeholder: <|code_start|> abort(500)
@app.route("/<city>/<lot_id>/timespan")
@crossdomain("*")
def get_longtime_forecast(city, lot_id):
app.logger.info("GET /%s/%s/timespan %s" %
(city, lot_id, user_agent(request)))
date_from = request.a... | if version == 1.0: |
Using the snippet: <|code_start|> static[city][lot["id"]] = {"total": lot["total"]}
except IndexError:
app.logger.warning("Failed to get static data for " + city)
def update_cache(city):
global cache
with db.cursor() as cursor:
if city in cache:
sql = "SEL... | "coords": city.coords, |
Predict the next line for this snippet: <|code_start|>
# This loads the geodata for this city if <city>.geojson exists in the same directory as this file.
# No need to remove this if there's no geodata (yet), everything will still work.
geodata = GeoData(__file__)
# This function is called by the scraper and given the... | parking_state = 'open' |
Using the snippet: <|code_start|># It's supposed to return a dictionary containing everything the current spec expects. Tests will fail if it doesn't ;)
def parse_html(html):
# BeautifulSoup is a great and easy way to parse the html and find the bits and pieces we're looking for.
soup = BeautifulSoup(html, "ht... | data["lots"].append({ |
Using the snippet: <|code_start|>
geodata = GeoData(__file__)
def parse_html(html):
soup = BeautifulSoup(html, "html.parser")
# last update time (UTC)
# Konstanz does not support the last_updated yet. I hope they will inform me when it's added
# as the data seems accurate I will return the current ti... | parking_state = 'open' |
Given snippet: <|code_start|>
geodata = GeoData(__file__)
def parse_html(html):
soup = BeautifulSoup(html, "html.parser")
# last update time (UTC)
# Konstanz does not support the last_updated yet. I hope they will inform me when it's added
# as the data seems accurate I will return the current time a... | continue |
Predict the next line after this snippet: <|code_start|># It's supposed to return a dictionary containing everything the current spec expects. Tests will fail if it doesn't ;)
def parse_html(html):
# BeautifulSoup is a great and easy way to parse the html and find the bits and pieces we're looking for.
soup = ... | if ( html_parkhaus.text.strip() == '' ) : continue # table is empty |
Predict the next line for this snippet: <|code_start|>
# This loads the geodata for this city if <city>.geojson exists in the same directory as this file.
# No need to remove this if there's no geodata (yet), everything will still work.
geodata = GeoData(__file__)
# This function is called by the scraper and given the... | date_time_text = soup.find('td', width='233').text.strip() |
Here is a snippet: <|code_start|>
# This loads the geodata for this city if <city>.geojson exists in the same directory as this file.
# No need to remove this if there's no geodata (yet), everything will still work.
geodata = GeoData(__file__)
# This function is called by the scraper and given the data of the page spe... | lot_free = max(lot_total - int(tr.find("totalnumberofoccupiedparkingspaces").text), 0) |
Next line prediction: <|code_start|> id_lots = {}
for l in geodata.lots:
aux = json.loads(geodata.lots[l].aux)
id_lots[aux["identifier"]] = {"lot":geodata.lots[l],
"open":aux["open"]}
timestamps = []
for feature in data["features"]:
try:
... | pass |
Next line prediction: <|code_start|>
# This loads the geodata for this city if <city>.geojson exists in the same directory as this file.
# No need to remove this if there's no geodata (yet), everything will still work.
geodata = GeoData(__file__)
# This function is called by the scraper and given the data of the page ... | state = "unknown" |
Predict the next line for this snippet: <|code_start|>
def timespan(city, lot_id, total, date_from, date_to, version):
now = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S")
if date_from > now or version == 1.0:
data = forecast(lot_id, total, date_from, date_to, version)
elif date_to < now:
... | if version == 1: |
Given the code snippet: <|code_start|>
def timespan(city, lot_id, total, date_from, date_to, version):
now = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S")
if date_from > now or version == 1.0:
data = forecast(lot_id, total, date_from, date_to, version)
elif date_to < now:
data = known_ti... | data.append({"timestamp": row["timestamp_downloaded"].strftime("%Y-%m-%dT%H:%M:%S"), |
Next line prediction: <|code_start|>#!/usr/bin/env python
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument("-c", "--city", help="city to dump")
parser.add_argument("-y", "--year", help="year to dump")
parser.add_argument("-m", "--month", help="month of year to dump")
parser.... | return parser.parse_args() |
Based on the snippet: <|code_start|>
POOL = None
def setup(url=env.DATABASE_URI):
global POOL
<|code_end|>
, predict the immediate next line with the help of imports:
from urllib.parse import urlparse
from contextlib import contextmanager
from psycopg2.pool import ThreadedConnectionPool
from park_api import env
i... | u = urlparse(url) |
Here is a snippet: <|code_start|> "coords": lot.coords,
"state": "unknown",
"lot_type": lot.type,
"id": lot.id,
"forecast": False,
})
elif lot_code not in cummulatives.keys():
lot_name = cummulatives[lot_code]... | "id": lot.id, |
Given the code snippet: <|code_start|> "Urban Level 1": "Dokk1",
"Urban Level 2+3": "Dokk1"
}
cumulative_lots = {}
for record in data_as_json["result"]["records"]:
lot_code = record["garageCode"]
total = int(record["totalSpaces"])
free = max(int(record["totalSpaces"]... | cumulative_lots[lot_name] = { |
Here is a snippet: <|code_start|> await ctx.send(embed=embed)
@commands.command(aliases=["aghs", "ags", "aghanims", "scepter", "shard"])
async def aghanim(self, ctx, *, name):
"""Gets the aghs upgrade for the given hero or ability
This command will get the information about shard upgrades AND scepter upgrades.... | upgrade_types = [ "scepter", "shard" ] |
Given the code snippet: <|code_start|> level = 1
if match:
if match.group(1):
level = 30
else:
level = int(match.group(2))
if level < 1 or level > 30:
raise UserError("Please enter a level between 1 and 30")
hero = re.sub(lvl_regex, "", hero)
hero = self.lookup_hero(hero)
if not hero:
... | description += f"\n{name}: **{value}**" |
Given snippet: <|code_start|> def add_attr(name, base_func, gain_func):
global description
result = f"{base_func(hero)} + {gain_func(hero)}"
if hero.attr_primary == name:
result = f"**{result}**"
icon = self.get_emoji(f"attr_{name}")
return f"{icon} {result}\n"
description += add_attr("strength",... | f"{self.get_emoji('hero_attack_rate')} {hero.attack_rate}\n" |
Given the following code snippet before the placeholder: <|code_start|> image = f.read()
if not ctx.guild:
raise UserError("You have to be in a server to use this command")
if not ctx.guild.me.guild_permissions.manage_emojis:
raise UserError("An admin needs to give me the 'Manage Emojis' permission before... | for ability in session.query(Ability).filter(Ability.lore != ""): |
Continue the code snippet: <|code_start|>logger = logging.getLogger("mangologger")
class Artifact(MangoCog):
"""Artifact related commands
A few commands providing information about Valve's new game [Artifact](https://playartifact.com)"""
def __init__(self, bot):
MangoCog.__init__(self, bot)
self.card_sets_uri... | await self.update_card_sets() |
Given the code snippet: <|code_start|> await self.update_card_sets()
return
self.card_sets = []
self.cards = []
for set_data in read_json(card_sets_filename):
card_set = CardSet(set_data)
self.card_sets.append(card_set)
for card_data in set_data["card_list"]:
self.cards.append(Card(card_data, c... | break # valve has removed the api D: |
Given the code snippet: <|code_start|> for n in range(0, 100):
try:
set_data = await httpgetter.get(f"https://playartifact.com/cardset/{str(n).zfill(2)}")
except HttpError as e:
if e.code == 400:
break # this set doesnt exist yet
else:
raise
except json.decoder.JSONDecodeError as e:
... | name = name.lower() |
Predict the next line for this snippet: <|code_start|>
Example:
`{cmdpfx}shiny charizard`"""
# Sanitize input first
with ctx.channel.typing():
data, species_data = await self.get_pokemon_data(pokemon)
if not data["sprites"].get("front_shiny"):
await ctx.send("This pokemon doesn't have a shiny version"... | words = pokemon.split(" ") |
Continue the code snippet: <|code_start|> @property
def color(self):
if self.color_name:
return CARD_COLOR_MAP[self.color_name]
elif self.type == "Item":
return CARD_COLOR_MAP["item"]
else:
return CARD_COLOR_MAP["default"]
@property
def type_image(self):
type_name = None
if self.type in CARD_TYPE... | "Hero", |
Using the snippet: <|code_start|>
config = parse_config()
register = template.Library()
# Lets me call dict values with spaces and hypens from a django template
@register.filter
def get(mapping, key):
return mapping.get(key, '')
@register.filter
<|code_end|>
, determine the next line of code. You have imports:
f... | def theme(mapping, key): |
Predict the next line for this snippet: <|code_start|> new_session['status'] = 'Detecting Profile'
db.update_session(session_id, new_session)
# Doesnt support json at the moment
kdbg_results = vol_int.run_plugin('kdbgscan', output_style='text')
lines = kdbg_results['rows'][0][0]
... | if 'auto_run' in request.POST: |
Given snippet: <|code_start|># https://github.com/viper-framework/viper/blob/master/viper/core/plugins.py
logger = logging.getLogger(__name__)
config = parse_config()
def load_extensions():
# Import modules package.
extension_list = dict()
disable_list = config['extensions']['disabled'].split(',')
... | except Exception as e: |
Using the snippet: <|code_start|># https://github.com/viper-framework/viper/blob/master/viper/core/plugins.py
logger = logging.getLogger(__name__)
config = parse_config()
def load_extensions():
# Import modules package.
extension_list = dict()
disable_list = config['extensions']['disabled'].split(',')
... | logger.error("There was an error importing the extension {0}: {1}".format(extension_name, e)) |
Here is a snippet: <|code_start|> return counter_and_return
def fake_loop_list(self, *cmd, **kwargs):
return """/dev/loop0: [8010]:264910 (/block/image0)
/dev/loop1: [8010]:264910 (/block/image1)""", None
def test_findloop(self):
expected_commands = ['losetup -f']
blocks... | mock.Mock(side_effect=self.fake_loop_list)) |
Predict the next line for this snippet: <|code_start|> '/root/blocks/snap1.blk bs=1M count=512',
'losetup /dev/loop1 /root/blocks/snap1.blk']
exists_side_effect = self.exists_side_effect(2)
self.mock_object(os.path, 'exists',
... | self.assertEqual(expected_commands, self.cmds) |
Predict the next line after this snippet: <|code_start|> def fake_execute(self, *cmd, **kwargs):
self.cmds.append(string.join(cmd))
return "", None
def exists_side_effect(self, false_times):
count = [0]
max_times = [false_times]
def counter_and_return(*arg):
... | exists_side_effect = self.exists_side_effect(2) |
Predict the next line after this snippet: <|code_start|>
def test_destroy(self):
self.mock_object(dmsetup, 'remove_table', mock.Mock())
self.mock_object(blockservice, 'unlinkloop', mock.Mock())
result = self.instance.destroy()
self.assertEqual(True, result)
class TestBlockDeviceS... | def counter_and_return(*arg): |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
test_snapshot_connection = {
'target_portal': '10.0.0.1:3260',
'target_iqn': 'iqn.2010-10.org.openstack:volume-shanpshot',
'target_lun': '1'}
device_info = {'path': '/dev/disk/by-path/ip-10.0.0.1:3260-iscsi-iqn.2010-10'
... | super(TestLocalSnapshot, self).setUp() |
Predict the next line for this snippet: <|code_start|>class TestBlockDeviceSnapshot(base.TestCase):
def setUp(self):
super(TestBlockDeviceSnapshot, self).setUp()
self.snapshot = snapshot.BlockDeviceSnapshot(
origin_path='/dev/mapper/origin',
instance_name='vm_test',
... | mock.Mock(return_value=device_info)) |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
test_snapshot_connection = {
'target_portal': '10.0.0.1:3260',
'target_iqn': 'iqn.2010-10.org.openstack:volume-shanpshot',
'target_lun': '1'}
device_info = {'path': '/dev/disk/by-path/ip-10.0.0.1:3260-iscsi-iqn.2010-10'
... | def setUp(self): |
Continue the code snippet: <|code_start|> self.mock_object(blockservice, 'unlinkloop', mock.Mock())
result = self.instance.destroy()
self.assertEqual(True, result)
class TestBlockDeviceSnapshot(base.TestCase):
def setUp(self):
super(TestBlockDeviceSnapshot, self).setUp()
s... | return not first_return |
Given the following code snippet before the placeholder: <|code_start|> mock.Mock(return_value=device_info))
self.mock_object(os.path, 'exists',
mock.Mock(side_effect=self.exists_side_effect(2)))
self.mock_object(os.path, 'realpath', mock.Mock(
... | '/dev/disk/by-path/ip-10.0.0.1:3260-iscsi-iqn.' |
Given the code snippet: <|code_start|>#!/usr/bin/env python
# TODO: Auto determine host ip if not filled in conf file
CONF = cfg.CONF
def start():
cn = compute.Virtman()
class HeartBeater(threading.Thread):
def __init__(self, thread_name):
super(HeartBeater, self).__init__(name=threa... | clock() |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
class MyDemo():
def show(self):
print 'funDemo'
class FakeDemo():
def show(self):
print 'FakeDemo'
fun = FunDemo()
print fun
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import mock
impor... | with mock.patch('tests.test_demo.FunDemo', FakeDemo): |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
class MyDemo():
def show(self):
print 'funDemo'
class FakeDemo():
def show(self):
print 'FakeDemo'
fun = FunDemo()
print fun
with mock.patch('tests.test_demo.FunDemo', FakeDemo):
fun = FunDemo()
print fun
fun.show()
with... | @mock.patch('tests.test_demo.FunDemo', FakeDemo) |
Based on the snippet: <|code_start|> 'test_image',
test_image_connections,
test_snapshot_connection1)
self.assertEqual(expected_result, result)
self.assertEqual(0, len(self.te... | expected_result = "2:Virtman: destroy VM instance failed" |
Given the code snippet: <|code_start|> self.mock_object(FakeImage, 'deploy_image',
mock.Mock(side_effect=baseimage_exception_for_test))
expected_result = "2:Virtman: create image failed"
result = self.test_computer.create('test_vm1',
... | mock.Mock(side_effect=exception_for_test)) |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
test_image_connections = [{
'target_portal': '10.0.0.3:3260',
'target_iqn': 'iqn.2010-10.org.openstack:volume-image',
<|code_end|>
. Use current file imports:
(import mock
import logging
from tests import base
from virtman import compute_new
from vi... | 'target_lun': '1'} |
Continue the code snippet: <|code_start|> 'target_lun': '1'}
]
test_snapshot_connection1 = {
'target_portal': '10.0.0.1:3260',
'target_iqn': 'iqn.2010-10.org.openstack:volume-shanpshot1',
'target_lun': '1'}
test_snapshot_connection2 = {
'target_portal': '10.0.0.1:3260',
'target_iqn': 'iqn.2010-... | self.assertEqual(expected_result1, result1) |
Given snippet: <|code_start|> expected_result = "1:Virtman: the instance_name 'test_vm1' " \
"does not exist!"
result = self.test_computer.destroy('test_vm1')
self.assertEqual(expected_result, result)
def test_destroy_with_exception(self):
self.mock_object(F... | result = self.test_computer.list() |
Continue the code snippet: <|code_start|> help='Whether snapshot can have cache'),
]
CONF = cfg.CONF
CONF.register_opts(snapshot_opts)
LOG = logging.getLogger(__name__)
class Snapshot(object):
def __init__(self):
pass
def create(self):
raise NotImplementedError()
def des... | class LocalSnapshot(Snapshot): |
Continue the code snippet: <|code_start|> help='Whether snapshot can have cache'),
]
CONF = cfg.CONF
CONF.register_opts(snapshot_opts)
LOG = logging.getLogger(__name__)
class Snapshot(object):
def __init__(self):
pass
def create(self):
raise NotImplementedError()
def des... | class LocalSnapshot(Snapshot): |
Based on the snippet: <|code_start|> self.instance_path = None
self.instance_name = instance_name
self.origin_path = origin_path
self.snapshot_with_cache = CONF.snapshot_with_cache
self.snapshot_dev = snapshot_dev
self.snapshot_dev_name = "snapshot_" + instance_name
d... | "snapshot_name %s" % (self.instance_name, self.snapshot_dev_name)) |
Predict the next line after this snippet: <|code_start|> self.origin_path = origin_path
self.snapshot_with_cache = CONF.snapshot_with_cache
self.snapshot_dev = snapshot_dev
self.snapshot_dev_name = "snapshot_" + instance_name
def create(self):
LOG.debug("Virtman: start VM ins... | self._destroy_snap_dev() |
Here is a snippet: <|code_start|>
snapshot_opts = [
cfg.BoolOpt('snapshot_with_cache',
default=False,
<|code_end|>
. Write the next line using the current file imports:
import os
from oslo.config import cfg
from virtman.utils import commands
from virtman.drivers import dmsetup
from virtman impor... | help='Whether snapshot can have cache'), |
Given the code snippet: <|code_start|>
STATUS = Enum(['empty', 'building', 'ok', 'destroying', 'error'])
ACTIONS = Enum(['build', 'destroy'])
class BaseImage(object):
def __init__(self):
pass
def deploy_base_image(self):
return NotImplementedError()
def destroy_base_image(self):
... | self.multipath_path = None |
Given the following code snippet before the placeholder: <|code_start|> def deploy_base_image(self):
return NotImplementedError()
def destroy_base_image(self):
return NotImplementedError()
class BlockDeviceBaseImage(BaseImage):
def __init__(self, image_name, image_connections):
sel... | self.image_name) |
Using the snippet: <|code_start|>
CONF = cfg.CONF
LOG = logging.getLogger(__name__)
STATUS = Enum(['empty', 'building', 'ok', 'destroying', 'error'])
ACTIONS = Enum(['build', 'destroy'])
class BaseImage(object):
def __init__(self):
pass
def deploy_base_image(self):
return NotImplementedErro... | self.is_login = False |
Next line prediction: <|code_start|>#!/usr/bin/env python
CONF = cfg.CONF
LOG = logging.getLogger(__name__)
STATUS = Enum(['empty', 'building', 'ok', 'destroying', 'error'])
ACTIONS = Enum(['build', 'destroy'])
class BaseImage(object):
<|code_end|>
. Use current file imports:
(import eventlet
import time
import... | def __init__(self): |
Next line prediction: <|code_start|> pass
def deploy_base_image(self):
return NotImplementedError()
def destroy_base_image(self):
return NotImplementedError()
class BlockDeviceBaseImage(BaseImage):
def __init__(self, image_name, image_connections):
self.image_name = image_... | self.status_lock = threading.Lock() |
Continue the code snippet: <|code_start|>ACTIONS = Enum(['build', 'destroy'])
class BaseImage(object):
def __init__(self):
pass
def deploy_base_image(self):
return NotImplementedError()
def destroy_base_image(self):
return NotImplementedError()
class BlockDeviceBaseImage(BaseIm... | self.origin_path = None |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python
# import json
class Client(object):
USER_AGENT = 'python-virtmanclient'
def __init__(self, name='virtman'):
self.name = name
def requests(self, url, method, **kwargs):
resp = requests.request(method, url, **k... | body = 'Is Body' |
Given the code snippet: <|code_start|> self.mock_object(os.path, 'exists', mock.Mock(return_value=True))
result = imageservice.create_image_target('image1', '/blocks/image1',
'/dev/loop2', test_iqn_prefix)
self.assertEqual(expected_result, result)... | 'volume-image2': '1:/dev/loop2'} |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
test_iqn_prefix = 'iqn.2010-10.org.test:'
class TestImageService(base.TestCase):
def setUp(self):
super(TestImageService, self).setUp()
self.cmds = []
self.mock_object(putils, 'execute',
mock.Mock(sid... | self.cmds.append(string.join(cmd)) |
Here is a snippet: <|code_start|>
class TestImageService(base.TestCase):
def setUp(self):
super(TestImageService, self).setUp()
self.cmds = []
self.mock_object(putils, 'execute',
mock.Mock(side_effect=self.fake_execute))
def fake_execute(self, *cmd, **kwargs):
... | '/dev/loop2', test_iqn_prefix) |
Using the snippet: <|code_start|> super(TestImageService, self).setUp()
self.cmds = []
self.mock_object(putils, 'execute',
mock.Mock(side_effect=self.fake_execute))
def fake_execute(self, *cmd, **kwargs):
self.cmds.append(string.join(cmd))
return "", ... | expected_result = '1:Virtman: Image Service: Warning! image_name = ' \ |
Given the following code snippet before the placeholder: <|code_start|>
LOG = logging.getLogger(__name__)
iscsi_disk_format = "ip-%s-iscsi-%s-lun-%s"
class Path(object):
def __init__(self, connection):
self.connection = connection
self.connected = False
self.device_info = None
s... | def connection_to_str(connection): |
Next line prediction: <|code_start|> result = path.Path.connect(self.path)
self.assertEqual(expected, result)
self.assertEqual(True, self.path.connected)
def test_disconnect(self):
self.mock_object(connector, 'disconnect_volume', mock.Mock())
path.Path.disconnect(self.path)
... | multipath_path=False) |
Predict the next line after this snippet: <|code_start|>class TestPaths(base.TestCase):
def setUp(self):
super(TestPaths, self).setUp()
self.paths = test_paths
# @mock.patch('virtman.path.Path', FakePath)
def test_rebuild_multipath(self):
self.mock_object(dmsetup, 'multipath',
... | self.assertEqual(2, len(self.paths)) |
Predict the next line for this snippet: <|code_start|> def connect(path):
path.device_info = fake_connect(path.connection)
path.device_path = path.device_info['path']
path.connected = True
return '/dev/disk/by-path/'+str(path)
@staticmethod
def disconnect(path):
path.... | expected = '/dev/disk/by-path/ip-10.0.0.1:3260-iscsi-iqn.2010-10.' \ |
Here is a snippet: <|code_start|>test_connection1 = {
'target_portal': '10.0.0.1:3260',
'target_iqn': 'iqn.2010-10.org.openstack:volume-00000001',
'target_lun': '1'
}
test_connection2 = {
'target_portal': '10.0.0.1:3260',
'target_iqn': 'iqn.2010-10.org.openstack:volume-00000002',
'target_lun': ... | def __init__(self, connection): |
Given the code snippet: <|code_start|>#!/usr/bin/env python
# from virtman.image import LocalImage
# from virtman.image import BlockDeviceImage
host_opts = [
cfg.StrOpt('host_ip',
default='192.168.137.101',
help='localhost ip provide Virtman service'),
cfg.StrOpt('host_port',
... | ] |
Continue the code snippet: <|code_start|> default='8001',
help='localhost port to provide Virtman service'),
cfg.IntOpt('heartbeat_interval',
default=20,
help='localhost heartbeat interval'),
]
compute_opts = [
cfg.IntOpt('thread_pool_size',
... | return NotImplementedError() |
Using the snippet: <|code_start|> if not fcg.is_valid():
fcg.create_group()
self.heartbeat_event = threading.Event()
self.heartbeat_thread = threading.Thread(target=self.heartbeat_clock)
self.heartbeat_thread.daemon = True
# self.heartbeat_thread.start()
LOG.i... | self._heartbeat() |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python
# from virtman.image import LocalImage
# from virtman.image import BlockDeviceImage
host_opts = [
cfg.StrOpt('host_ip',
default='192.168.137.101',
help='localhost ip provide Virtman service'),
cfg.St... | help='localhost port to provide Virtman service'), |
Given snippet: <|code_start|># Copyright 2011 OpenStack Foundation.
# All Rights Reserved.
#
# 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/... | help='Whether to disable inter-process locks'), |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.