Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given snippet: <|code_start|> report += f"{''.join(footers_f)}\n"
return report
def get_flat_report_header(headers, width=14):
header_lists = get_flat_report_header_lists(headers, width)
report_header = ""
for i in range(len(header_lists[0])):
row = [line[i] for line in header_lists]
headers_f = [f"{header:>{width}}" for header in row]
report_header += f"{''.join(headers_f)}\n"
return report_header
def get_flat_report_header_lists(headers, width=14):
"""Attempts to break up account and payee names into chunks that
will read better when they are used as column headers"""
TRUNC_CHAR = "~"
ACCOUNT_TYPES = ["assets:", "liabilities:", "income:", "expenses:", "equity:"]
HEADER_SPLIT = r"(?<=: )|(?<=:)(?=\S)|(?<=[- ])"
padded_width = width - 3 if width >= 14 else width - 1
header_lists = []
for header in headers:
the_header = []
row_in_progress = []
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import argparse
import csv
import re
import sys
from collections import defaultdict
from concurrent import futures
from datetime import date
from io import StringIO
from textwrap import dedent
from dateutil.relativedelta import relativedelta
from .. import util
from ..colorable import Colorable
from ..settings_getter import get_setting
from ..util import get_date, parse_args
from .runner import get_ledger_output
from .util import get_account_balance, get_first_dollar_amount_float, get_payee_subtotal
and context:
# Path: ledgerbil/colorable.py
# class Colorable:
#
# START_CODE = "\033"
# END_CODE = f"{START_CODE}[0m"
#
# BRIGHT_OFFSET = 60
#
# COLORS = {
# "black": 30,
# "gray": 30,
# "grey": 30,
# "red": 31,
# "green": 32,
# "yellow": 33,
# "blue": 34,
# "magenta": 35,
# "purple": 35,
# "cyan": 36,
# "white": 37,
# }
#
# ansi_escape = re.compile(r"\x1B\[[0-?]*[ -/]*[@-~]")
#
# def __init__(self, color, value, fmt="", bright=False):
#
# if color not in self.COLORS:
# raise UnsupportedColorError(
# f"I don't know what to do with this color: {color}"
# )
#
# self.my_color = color
# self.value = value
# self.bright = bright
# self.format_string = fmt
#
# def __repr__(self):
# return (
# f"Colorable('{self.my_color}', '{self.value}', "
# f"fmt='{self.format_string}', bright={self.bright})"
# )
#
# def __str__(self):
# start = self.ansi_sequence(self.COLORS[self.my_color], bright=self.bright)
# ansi_str = f"{start}{self.value:{self.format_string}}{self.END_CODE}"
# return ansi_str
#
# def __len__(self):
# return len(self.value)
#
# def __eq__(self, other):
# return str(self) == str(other)
#
# def ansi_sequence(self, code, bright=False):
# offset = 60 if bright else 0
# color = code + offset
# return f"{self.START_CODE}[0;{color}m"
#
# def plain(self):
# return self.value
#
# @staticmethod
# def get_plain_string(ansi_string):
# return Colorable.ansi_escape.sub("", ansi_string)
#
# Path: ledgerbil/settings_getter.py
# def get_setting(setting, default=None):
# if settings and hasattr(settings, setting):
# return getattr(settings, setting)
#
# return defaults.get(setting, default)
#
# Path: ledgerbil/util.py
# def get_date(date_string, the_format=None):
# if not the_format:
# the_format = get_setting("DATE_FORMAT")
# return datetime.strptime(date_string, the_format).date()
#
# def parse_args(args):
# # args should be a string, but we'll make sure it isn't None
# # (which would cause the string to be read from stdin)
# try:
# return shlex.split(args or "")
# except ValueError as e:
# print(f"*** {e}")
# return None
#
# Path: ledgerbil/ledgershell/runner.py
# def get_ledger_output(args=None):
# cmd = get_ledger_command(args)
# process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
# output, _ = process.communicate()
# return output.decode("unicode_escape").rstrip()
#
# Path: ledgerbil/ledgershell/util.py
# def get_account_balance(line, shares=False, strip_account=True):
# if shares:
# match = SHARES_REGEX.match(line)
# if match:
# amount, symbol, account = match.groups()
# else:
# match = DOLLARS_REGEX.match(line)
# if match:
# amount, account = match.groups()
# symbol = "$"
#
# if not match:
# return None
#
# return AccountBalance(
# account.strip() if strip_account else account, get_float(amount), symbol
# )
#
# def get_first_dollar_amount_float(line):
# DOLLARS = 0
# match = FIRST_DOLLAR_AMOUNT_REGEX.match(line)
# if match:
# return get_float(match.groups()[DOLLARS])
# return None
#
# def get_payee_subtotal(line):
# DOLLARS = 0
# match = PAYEE_SUBTOTAL_REGEX.match(line)
# if match:
# return get_float(match.groups()[DOLLARS])
# return None
which might include code, classes, or functions. Output only the next line. | parts = re.split(HEADER_SPLIT, header) |
Here is a snippet: <|code_start|> footers = rows[FOOTER_ROW][:ACCOUNT_PAYEE_COLUMN]
dashes = [f"{'-' * (AMOUNT_WIDTH - 2):>{AMOUNT_WIDTH}}" for x in footers]
footers_f = [util.get_colored_amount(t, AMOUNT_WIDTH) for t in footers]
report += f"{Colorable('white', ''.join(dashes))}\n"
report += f"{''.join(footers_f)}\n"
return report
def get_flat_report_header(headers, width=14):
header_lists = get_flat_report_header_lists(headers, width)
report_header = ""
for i in range(len(header_lists[0])):
row = [line[i] for line in header_lists]
headers_f = [f"{header:>{width}}" for header in row]
report_header += f"{''.join(headers_f)}\n"
return report_header
def get_flat_report_header_lists(headers, width=14):
"""Attempts to break up account and payee names into chunks that
will read better when they are used as column headers"""
TRUNC_CHAR = "~"
ACCOUNT_TYPES = ["assets:", "liabilities:", "income:", "expenses:", "equity:"]
HEADER_SPLIT = r"(?<=: )|(?<=:)(?=\S)|(?<=[- ])"
padded_width = width - 3 if width >= 14 else width - 1
header_lists = []
<|code_end|>
. Write the next line using the current file imports:
import argparse
import csv
import re
import sys
from collections import defaultdict
from concurrent import futures
from datetime import date
from io import StringIO
from textwrap import dedent
from dateutil.relativedelta import relativedelta
from .. import util
from ..colorable import Colorable
from ..settings_getter import get_setting
from ..util import get_date, parse_args
from .runner import get_ledger_output
from .util import get_account_balance, get_first_dollar_amount_float, get_payee_subtotal
and context from other files:
# Path: ledgerbil/colorable.py
# class Colorable:
#
# START_CODE = "\033"
# END_CODE = f"{START_CODE}[0m"
#
# BRIGHT_OFFSET = 60
#
# COLORS = {
# "black": 30,
# "gray": 30,
# "grey": 30,
# "red": 31,
# "green": 32,
# "yellow": 33,
# "blue": 34,
# "magenta": 35,
# "purple": 35,
# "cyan": 36,
# "white": 37,
# }
#
# ansi_escape = re.compile(r"\x1B\[[0-?]*[ -/]*[@-~]")
#
# def __init__(self, color, value, fmt="", bright=False):
#
# if color not in self.COLORS:
# raise UnsupportedColorError(
# f"I don't know what to do with this color: {color}"
# )
#
# self.my_color = color
# self.value = value
# self.bright = bright
# self.format_string = fmt
#
# def __repr__(self):
# return (
# f"Colorable('{self.my_color}', '{self.value}', "
# f"fmt='{self.format_string}', bright={self.bright})"
# )
#
# def __str__(self):
# start = self.ansi_sequence(self.COLORS[self.my_color], bright=self.bright)
# ansi_str = f"{start}{self.value:{self.format_string}}{self.END_CODE}"
# return ansi_str
#
# def __len__(self):
# return len(self.value)
#
# def __eq__(self, other):
# return str(self) == str(other)
#
# def ansi_sequence(self, code, bright=False):
# offset = 60 if bright else 0
# color = code + offset
# return f"{self.START_CODE}[0;{color}m"
#
# def plain(self):
# return self.value
#
# @staticmethod
# def get_plain_string(ansi_string):
# return Colorable.ansi_escape.sub("", ansi_string)
#
# Path: ledgerbil/settings_getter.py
# def get_setting(setting, default=None):
# if settings and hasattr(settings, setting):
# return getattr(settings, setting)
#
# return defaults.get(setting, default)
#
# Path: ledgerbil/util.py
# def get_date(date_string, the_format=None):
# if not the_format:
# the_format = get_setting("DATE_FORMAT")
# return datetime.strptime(date_string, the_format).date()
#
# def parse_args(args):
# # args should be a string, but we'll make sure it isn't None
# # (which would cause the string to be read from stdin)
# try:
# return shlex.split(args or "")
# except ValueError as e:
# print(f"*** {e}")
# return None
#
# Path: ledgerbil/ledgershell/runner.py
# def get_ledger_output(args=None):
# cmd = get_ledger_command(args)
# process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
# output, _ = process.communicate()
# return output.decode("unicode_escape").rstrip()
#
# Path: ledgerbil/ledgershell/util.py
# def get_account_balance(line, shares=False, strip_account=True):
# if shares:
# match = SHARES_REGEX.match(line)
# if match:
# amount, symbol, account = match.groups()
# else:
# match = DOLLARS_REGEX.match(line)
# if match:
# amount, account = match.groups()
# symbol = "$"
#
# if not match:
# return None
#
# return AccountBalance(
# account.strip() if strip_account else account, get_float(amount), symbol
# )
#
# def get_first_dollar_amount_float(line):
# DOLLARS = 0
# match = FIRST_DOLLAR_AMOUNT_REGEX.match(line)
# if match:
# return get_float(match.groups()[DOLLARS])
# return None
#
# def get_payee_subtotal(line):
# DOLLARS = 0
# match = PAYEE_SUBTOTAL_REGEX.match(line)
# if match:
# return get_float(match.groups()[DOLLARS])
# return None
, which may include functions, classes, or code. Output only the next line. | for header in headers: |
Here is a snippet: <|code_start|>
with futures.ThreadPoolExecutor(max_workers=50) as executor:
to_do = []
ending = ()
for period_name in period_names:
if current_period and current_period == period_name:
ending = ("--end", "tomorrow")
future = executor.submit(get_column, args, ledger_args, period_name, ending)
to_do.append(future)
row_headers = set()
columns = {}
for future in futures.as_completed(to_do):
period_name, column = future.result()
row_headers.update(column.keys())
columns[period_name] = column
return row_headers, columns
def get_column(args, ledger_args, period_name, ending):
if args.payees:
column = get_column_payees(period_name, ledger_args + ending)
elif args.networth:
networth_period = "tomorrow" if ending else period_name
column = get_column_networth(networth_period, ledger_args)
else:
column = get_column_accounts(period_name, ledger_args + ending, args.depth)
<|code_end|>
. Write the next line using the current file imports:
import argparse
import csv
import re
import sys
from collections import defaultdict
from concurrent import futures
from datetime import date
from io import StringIO
from textwrap import dedent
from dateutil.relativedelta import relativedelta
from .. import util
from ..colorable import Colorable
from ..settings_getter import get_setting
from ..util import get_date, parse_args
from .runner import get_ledger_output
from .util import get_account_balance, get_first_dollar_amount_float, get_payee_subtotal
and context from other files:
# Path: ledgerbil/colorable.py
# class Colorable:
#
# START_CODE = "\033"
# END_CODE = f"{START_CODE}[0m"
#
# BRIGHT_OFFSET = 60
#
# COLORS = {
# "black": 30,
# "gray": 30,
# "grey": 30,
# "red": 31,
# "green": 32,
# "yellow": 33,
# "blue": 34,
# "magenta": 35,
# "purple": 35,
# "cyan": 36,
# "white": 37,
# }
#
# ansi_escape = re.compile(r"\x1B\[[0-?]*[ -/]*[@-~]")
#
# def __init__(self, color, value, fmt="", bright=False):
#
# if color not in self.COLORS:
# raise UnsupportedColorError(
# f"I don't know what to do with this color: {color}"
# )
#
# self.my_color = color
# self.value = value
# self.bright = bright
# self.format_string = fmt
#
# def __repr__(self):
# return (
# f"Colorable('{self.my_color}', '{self.value}', "
# f"fmt='{self.format_string}', bright={self.bright})"
# )
#
# def __str__(self):
# start = self.ansi_sequence(self.COLORS[self.my_color], bright=self.bright)
# ansi_str = f"{start}{self.value:{self.format_string}}{self.END_CODE}"
# return ansi_str
#
# def __len__(self):
# return len(self.value)
#
# def __eq__(self, other):
# return str(self) == str(other)
#
# def ansi_sequence(self, code, bright=False):
# offset = 60 if bright else 0
# color = code + offset
# return f"{self.START_CODE}[0;{color}m"
#
# def plain(self):
# return self.value
#
# @staticmethod
# def get_plain_string(ansi_string):
# return Colorable.ansi_escape.sub("", ansi_string)
#
# Path: ledgerbil/settings_getter.py
# def get_setting(setting, default=None):
# if settings and hasattr(settings, setting):
# return getattr(settings, setting)
#
# return defaults.get(setting, default)
#
# Path: ledgerbil/util.py
# def get_date(date_string, the_format=None):
# if not the_format:
# the_format = get_setting("DATE_FORMAT")
# return datetime.strptime(date_string, the_format).date()
#
# def parse_args(args):
# # args should be a string, but we'll make sure it isn't None
# # (which would cause the string to be read from stdin)
# try:
# return shlex.split(args or "")
# except ValueError as e:
# print(f"*** {e}")
# return None
#
# Path: ledgerbil/ledgershell/runner.py
# def get_ledger_output(args=None):
# cmd = get_ledger_command(args)
# process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
# output, _ = process.communicate()
# return output.decode("unicode_escape").rstrip()
#
# Path: ledgerbil/ledgershell/util.py
# def get_account_balance(line, shares=False, strip_account=True):
# if shares:
# match = SHARES_REGEX.match(line)
# if match:
# amount, symbol, account = match.groups()
# else:
# match = DOLLARS_REGEX.match(line)
# if match:
# amount, account = match.groups()
# symbol = "$"
#
# if not match:
# return None
#
# return AccountBalance(
# account.strip() if strip_account else account, get_float(amount), symbol
# )
#
# def get_first_dollar_amount_float(line):
# DOLLARS = 0
# match = FIRST_DOLLAR_AMOUNT_REGEX.match(line)
# if match:
# return get_float(match.groups()[DOLLARS])
# return None
#
# def get_payee_subtotal(line):
# DOLLARS = 0
# match = PAYEE_SUBTOTAL_REGEX.match(line)
# if match:
# return get_float(match.groups()[DOLLARS])
# return None
, which may include functions, classes, or code. Output only the next line. | return period_name, column |
Predict the next line for this snippet: <|code_start|> # double count them in line items but not in the total.
# In the column total, which is "our" total and what will be shown in
# the report, we will get the wrong sum. Let's warn when this happens.
# (Which means ledgerbil's stance is that you really shouldn't use
# your accounts this way.)
# We'll not concern ourselves over small floating point differences
if round(abs(column_total - ledgers_total), 2) > 0.05:
warn_column_total(period_name, column_total, ledgers_total)
def warn_column_total(period_name, column_total=0, ledgers_total=0):
message = (
f"Warning: Differing total found between ledger's {ledgers_total} "
f"and ledgerbil's {column_total} for --period {period_name}. "
"Ledger's will be the correct total. This is mostly likely caused "
"by funds being applied to both a parent and child account."
)
print(message, file=sys.stderr)
def get_column_payees(period_name, ledger_args):
lines = get_ledger_output(
(
"register",
"--group-by",
"(payee)",
"--collapse",
"--subtotal",
<|code_end|>
with the help of current file imports:
import argparse
import csv
import re
import sys
from collections import defaultdict
from concurrent import futures
from datetime import date
from io import StringIO
from textwrap import dedent
from dateutil.relativedelta import relativedelta
from .. import util
from ..colorable import Colorable
from ..settings_getter import get_setting
from ..util import get_date, parse_args
from .runner import get_ledger_output
from .util import get_account_balance, get_first_dollar_amount_float, get_payee_subtotal
and context from other files:
# Path: ledgerbil/colorable.py
# class Colorable:
#
# START_CODE = "\033"
# END_CODE = f"{START_CODE}[0m"
#
# BRIGHT_OFFSET = 60
#
# COLORS = {
# "black": 30,
# "gray": 30,
# "grey": 30,
# "red": 31,
# "green": 32,
# "yellow": 33,
# "blue": 34,
# "magenta": 35,
# "purple": 35,
# "cyan": 36,
# "white": 37,
# }
#
# ansi_escape = re.compile(r"\x1B\[[0-?]*[ -/]*[@-~]")
#
# def __init__(self, color, value, fmt="", bright=False):
#
# if color not in self.COLORS:
# raise UnsupportedColorError(
# f"I don't know what to do with this color: {color}"
# )
#
# self.my_color = color
# self.value = value
# self.bright = bright
# self.format_string = fmt
#
# def __repr__(self):
# return (
# f"Colorable('{self.my_color}', '{self.value}', "
# f"fmt='{self.format_string}', bright={self.bright})"
# )
#
# def __str__(self):
# start = self.ansi_sequence(self.COLORS[self.my_color], bright=self.bright)
# ansi_str = f"{start}{self.value:{self.format_string}}{self.END_CODE}"
# return ansi_str
#
# def __len__(self):
# return len(self.value)
#
# def __eq__(self, other):
# return str(self) == str(other)
#
# def ansi_sequence(self, code, bright=False):
# offset = 60 if bright else 0
# color = code + offset
# return f"{self.START_CODE}[0;{color}m"
#
# def plain(self):
# return self.value
#
# @staticmethod
# def get_plain_string(ansi_string):
# return Colorable.ansi_escape.sub("", ansi_string)
#
# Path: ledgerbil/settings_getter.py
# def get_setting(setting, default=None):
# if settings and hasattr(settings, setting):
# return getattr(settings, setting)
#
# return defaults.get(setting, default)
#
# Path: ledgerbil/util.py
# def get_date(date_string, the_format=None):
# if not the_format:
# the_format = get_setting("DATE_FORMAT")
# return datetime.strptime(date_string, the_format).date()
#
# def parse_args(args):
# # args should be a string, but we'll make sure it isn't None
# # (which would cause the string to be read from stdin)
# try:
# return shlex.split(args or "")
# except ValueError as e:
# print(f"*** {e}")
# return None
#
# Path: ledgerbil/ledgershell/runner.py
# def get_ledger_output(args=None):
# cmd = get_ledger_command(args)
# process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
# output, _ = process.communicate()
# return output.decode("unicode_escape").rstrip()
#
# Path: ledgerbil/ledgershell/util.py
# def get_account_balance(line, shares=False, strip_account=True):
# if shares:
# match = SHARES_REGEX.match(line)
# if match:
# amount, symbol, account = match.groups()
# else:
# match = DOLLARS_REGEX.match(line)
# if match:
# amount, account = match.groups()
# symbol = "$"
#
# if not match:
# return None
#
# return AccountBalance(
# account.strip() if strip_account else account, get_float(amount), symbol
# )
#
# def get_first_dollar_amount_float(line):
# DOLLARS = 0
# match = FIRST_DOLLAR_AMOUNT_REGEX.match(line)
# if match:
# return get_float(match.groups()[DOLLARS])
# return None
#
# def get_payee_subtotal(line):
# DOLLARS = 0
# match = PAYEE_SUBTOTAL_REGEX.match(line)
# if match:
# return get_float(match.groups()[DOLLARS])
# return None
, which may contain function names, class names, or code. Output only the next line. | "--depth", |
Given snippet: <|code_start|> if args.transpose:
rows = list(map(list, zip(*rows)))
if args.csv:
return get_csv_report(rows, tabs=args.tab)
if args.transpose:
# Move account/payee back to the right side
for row in rows:
row.append(row.pop(0))
return get_flat_report(rows, networth=args.networth)
def get_csv_report(rows, tabs=False):
delimiter = "\t" if tabs else ","
output = StringIO()
writer = csv.writer(output, delimiter=delimiter, lineterminator="\n")
writer.writerows(rows)
return output.getvalue()
def get_flat_report(rows, networth=False):
# 2 columns means has a single data column and account/payee column;
# will have 4 or more columns otherwise, and have a total column;
# same deal for total row; however! note that we sneak in --total-only
# as if a regular single column (is also highlighted as a non-total col)
has_total_column = len(rows[0]) > 3 and not networth
has_total_row = len(rows) > 3 and not networth
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import argparse
import csv
import re
import sys
from collections import defaultdict
from concurrent import futures
from datetime import date
from io import StringIO
from textwrap import dedent
from dateutil.relativedelta import relativedelta
from .. import util
from ..colorable import Colorable
from ..settings_getter import get_setting
from ..util import get_date, parse_args
from .runner import get_ledger_output
from .util import get_account_balance, get_first_dollar_amount_float, get_payee_subtotal
and context:
# Path: ledgerbil/colorable.py
# class Colorable:
#
# START_CODE = "\033"
# END_CODE = f"{START_CODE}[0m"
#
# BRIGHT_OFFSET = 60
#
# COLORS = {
# "black": 30,
# "gray": 30,
# "grey": 30,
# "red": 31,
# "green": 32,
# "yellow": 33,
# "blue": 34,
# "magenta": 35,
# "purple": 35,
# "cyan": 36,
# "white": 37,
# }
#
# ansi_escape = re.compile(r"\x1B\[[0-?]*[ -/]*[@-~]")
#
# def __init__(self, color, value, fmt="", bright=False):
#
# if color not in self.COLORS:
# raise UnsupportedColorError(
# f"I don't know what to do with this color: {color}"
# )
#
# self.my_color = color
# self.value = value
# self.bright = bright
# self.format_string = fmt
#
# def __repr__(self):
# return (
# f"Colorable('{self.my_color}', '{self.value}', "
# f"fmt='{self.format_string}', bright={self.bright})"
# )
#
# def __str__(self):
# start = self.ansi_sequence(self.COLORS[self.my_color], bright=self.bright)
# ansi_str = f"{start}{self.value:{self.format_string}}{self.END_CODE}"
# return ansi_str
#
# def __len__(self):
# return len(self.value)
#
# def __eq__(self, other):
# return str(self) == str(other)
#
# def ansi_sequence(self, code, bright=False):
# offset = 60 if bright else 0
# color = code + offset
# return f"{self.START_CODE}[0;{color}m"
#
# def plain(self):
# return self.value
#
# @staticmethod
# def get_plain_string(ansi_string):
# return Colorable.ansi_escape.sub("", ansi_string)
#
# Path: ledgerbil/settings_getter.py
# def get_setting(setting, default=None):
# if settings and hasattr(settings, setting):
# return getattr(settings, setting)
#
# return defaults.get(setting, default)
#
# Path: ledgerbil/util.py
# def get_date(date_string, the_format=None):
# if not the_format:
# the_format = get_setting("DATE_FORMAT")
# return datetime.strptime(date_string, the_format).date()
#
# def parse_args(args):
# # args should be a string, but we'll make sure it isn't None
# # (which would cause the string to be read from stdin)
# try:
# return shlex.split(args or "")
# except ValueError as e:
# print(f"*** {e}")
# return None
#
# Path: ledgerbil/ledgershell/runner.py
# def get_ledger_output(args=None):
# cmd = get_ledger_command(args)
# process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
# output, _ = process.communicate()
# return output.decode("unicode_escape").rstrip()
#
# Path: ledgerbil/ledgershell/util.py
# def get_account_balance(line, shares=False, strip_account=True):
# if shares:
# match = SHARES_REGEX.match(line)
# if match:
# amount, symbol, account = match.groups()
# else:
# match = DOLLARS_REGEX.match(line)
# if match:
# amount, account = match.groups()
# symbol = "$"
#
# if not match:
# return None
#
# return AccountBalance(
# account.strip() if strip_account else account, get_float(amount), symbol
# )
#
# def get_first_dollar_amount_float(line):
# DOLLARS = 0
# match = FIRST_DOLLAR_AMOUNT_REGEX.match(line)
# if match:
# return get_float(match.groups()[DOLLARS])
# return None
#
# def get_payee_subtotal(line):
# DOLLARS = 0
# match = PAYEE_SUBTOTAL_REGEX.match(line)
# if match:
# return get_float(match.groups()[DOLLARS])
# return None
which might include code, classes, or functions. Output only the next line. | AMOUNT_WIDTH = 14 # width of columns with amounts |
Continue the code snippet: <|code_start|> else:
networth = 0
column = {"net worth": networth}
return column
def get_rows(
row_headers,
columns,
period_names,
sort=SORT_DEFAULT,
limit_rows=0,
total_only=False,
no_total=False,
):
ACCOUNT_PAYEE_HEADER = EMPTY_VALUE
ACCOUNT_PAYEE_COLUMN = -1
TOTAL_COLUMN = -2
grid = get_grid(row_headers, columns)
rows = []
for row_header in row_headers:
amounts = [grid[row_header].get(pn, 0) for pn in period_names]
rows.append(amounts + [sum(amounts)] + [row_header])
if sort == "row":
sort_index = ACCOUNT_PAYEE_COLUMN
<|code_end|>
. Use current file imports:
import argparse
import csv
import re
import sys
from collections import defaultdict
from concurrent import futures
from datetime import date
from io import StringIO
from textwrap import dedent
from dateutil.relativedelta import relativedelta
from .. import util
from ..colorable import Colorable
from ..settings_getter import get_setting
from ..util import get_date, parse_args
from .runner import get_ledger_output
from .util import get_account_balance, get_first_dollar_amount_float, get_payee_subtotal
and context (classes, functions, or code) from other files:
# Path: ledgerbil/colorable.py
# class Colorable:
#
# START_CODE = "\033"
# END_CODE = f"{START_CODE}[0m"
#
# BRIGHT_OFFSET = 60
#
# COLORS = {
# "black": 30,
# "gray": 30,
# "grey": 30,
# "red": 31,
# "green": 32,
# "yellow": 33,
# "blue": 34,
# "magenta": 35,
# "purple": 35,
# "cyan": 36,
# "white": 37,
# }
#
# ansi_escape = re.compile(r"\x1B\[[0-?]*[ -/]*[@-~]")
#
# def __init__(self, color, value, fmt="", bright=False):
#
# if color not in self.COLORS:
# raise UnsupportedColorError(
# f"I don't know what to do with this color: {color}"
# )
#
# self.my_color = color
# self.value = value
# self.bright = bright
# self.format_string = fmt
#
# def __repr__(self):
# return (
# f"Colorable('{self.my_color}', '{self.value}', "
# f"fmt='{self.format_string}', bright={self.bright})"
# )
#
# def __str__(self):
# start = self.ansi_sequence(self.COLORS[self.my_color], bright=self.bright)
# ansi_str = f"{start}{self.value:{self.format_string}}{self.END_CODE}"
# return ansi_str
#
# def __len__(self):
# return len(self.value)
#
# def __eq__(self, other):
# return str(self) == str(other)
#
# def ansi_sequence(self, code, bright=False):
# offset = 60 if bright else 0
# color = code + offset
# return f"{self.START_CODE}[0;{color}m"
#
# def plain(self):
# return self.value
#
# @staticmethod
# def get_plain_string(ansi_string):
# return Colorable.ansi_escape.sub("", ansi_string)
#
# Path: ledgerbil/settings_getter.py
# def get_setting(setting, default=None):
# if settings and hasattr(settings, setting):
# return getattr(settings, setting)
#
# return defaults.get(setting, default)
#
# Path: ledgerbil/util.py
# def get_date(date_string, the_format=None):
# if not the_format:
# the_format = get_setting("DATE_FORMAT")
# return datetime.strptime(date_string, the_format).date()
#
# def parse_args(args):
# # args should be a string, but we'll make sure it isn't None
# # (which would cause the string to be read from stdin)
# try:
# return shlex.split(args or "")
# except ValueError as e:
# print(f"*** {e}")
# return None
#
# Path: ledgerbil/ledgershell/runner.py
# def get_ledger_output(args=None):
# cmd = get_ledger_command(args)
# process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
# output, _ = process.communicate()
# return output.decode("unicode_escape").rstrip()
#
# Path: ledgerbil/ledgershell/util.py
# def get_account_balance(line, shares=False, strip_account=True):
# if shares:
# match = SHARES_REGEX.match(line)
# if match:
# amount, symbol, account = match.groups()
# else:
# match = DOLLARS_REGEX.match(line)
# if match:
# amount, account = match.groups()
# symbol = "$"
#
# if not match:
# return None
#
# return AccountBalance(
# account.strip() if strip_account else account, get_float(amount), symbol
# )
#
# def get_first_dollar_amount_float(line):
# DOLLARS = 0
# match = FIRST_DOLLAR_AMOUNT_REGEX.match(line)
# if match:
# return get_float(match.groups()[DOLLARS])
# return None
#
# def get_payee_subtotal(line):
# DOLLARS = 0
# match = PAYEE_SUBTOTAL_REGEX.match(line)
# if match:
# return get_float(match.groups()[DOLLARS])
# return None
. Output only the next line. | reverse_sort = False |
Given snippet: <|code_start|>
class OwnerOnly:
__slots__ = ('bot',)
def __init__(self, bot: Yasen):
self.bot = bot
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from discord import Forbidden, TextChannel
from discord.embeds import Embed
from discord.ext.commands import Context, command
from bot import Yasen
from scripts.checks import is_owner
and context:
# Path: bot/yasen.py
# class Yasen(AutoShardedBot):
# """
# The yasen bot object
# """
#
# def __init__(self, *,
# logger,
# version: str,
# config: Config,
# start_time: int,
# wows_api=WowsAsync,
# data_manager: DataManager,
# wows_manager: WowsManager,
# anime_search: AnimeSearcher):
# self.config = config
# self.logger = logger
# self.version = version
# self.start_time = start_time
# self.data_manager = data_manager
# self.anime_search = anime_search
# self.session_manager = anime_search.session_manager
# self.wows_manager = wows_manager
# self.wows_api = wows_api
# super().__init__(get_prefix)
#
# @property
# def default_prefix(self):
# return self.config.default_prefix
#
# @property
# def client_id(self):
# return self.user.id
#
# @property
# def error_log(self) -> Optional[Messageable]:
# """
# Get the error log channel for the bot.
# :return: the error log channel.
# """
# c = self.get_channel(self.config.error_log)
# return c if isinstance(c, Messageable) else None
#
# @property
# def uptime(self) -> timedelta:
# """
# Get the uptime of the bot.
# :return: A timedelta object between now and the start time.
# """
# return datetime.now() - datetime.fromtimestamp(self.start_time)
#
# @property
# def invite_link(self):
# return oauth_url(self.client_id, permissions=Permissions.all())
#
# async def try_change_presence(
# self, retry: bool, *,
# game: Optional[Game] = None,
# status: Optional[Status] = None,
# afk: bool = False,
# shard_id: Optional[int] = None):
# """
# Try changing presence of the bot.
#
# :param retry: True to enable retry. Will log out the bot.
#
# :param game: The game being played. None if no game is being played.
#
# :param status: Indicates what status to change to. If None, then
# :attr:`Status.online` is used.
#
# :param afk: Indicates if you are going AFK. This allows the discord
# client to know how to handle push notifications better
# for you in case you are actually idle and not lying.
#
# :param shard_id: The shard_id to change the presence to. If not
# specified or ``None``, then it will change the presence of every
# shard the bot can see.
#
# :raises InvalidArgument:
# If the ``game`` parameter is not :class:`Game` or None.
#
# :raises ConnectionClosed:
# If retry parameter is set to False and ConnectionClosed was raised by
# super().change_presence
# """
# try:
# await self.wait_until_ready()
# await super().change_presence(
# game=game, status=status, afk=afk, shard_id=shard_id)
# except ConnectionClosed as e:
# if retry:
# self.logger.warn(str(e))
# await self.logout()
# await self.login(self.config.token)
# await self.try_change_presence(
# retry, game=game, status=status, afk=afk,
# shard_id=shard_id)
# else:
# raise e
#
# def start_bot(self, cogs):
# """
# Start the bot.
# :param cogs: the list of cogs.
# """
# self.remove_command('help')
# for cog in cogs:
# self.add_cog(cog)
# self.run(self.config.token)
#
# def get_channels(self, type_: Optional[type] = None):
# """
# Get all channels the bot can see with an optional filter.
# :param type_: the type of the channel desired, None for all.
# :return: A generator that retrives all channels with type `type_`
# """
# if type_:
# for guild in self.guilds:
# for channel in guild.channels:
# if isinstance(channel, type_):
# yield channel
# else:
# yield from super().get_all_channels()
#
# async def on_error(self, event_method, *args, **kwargs):
# """
# General error handling for discord
# Check :func:`discord.Client.on_error` for more details.
# """
# ig = 'Ignoring exception in {}\n'.format(event_method)
# tb = format_exc()
# log_msg = f'\n{ig}\n{tb}'
# header = f'**CRITICAL**\n{ig}'
# lvl = CRITICAL
# for arg in chain(args, kwargs.values()):
# if isinstance(arg, Context):
# await arg.send(':x: I ran into a critical error. '
# 'It has been reported to my developer.')
# header = f'**ERROR**\n{ig}'
# lvl = ERROR
# break
# self.logger.log(lvl, log_msg)
# await self.send_tb(header, tb)
#
# async def send_tb(self, header: str, tb: str):
# """
# Send traceback to error log channel if it exists.
# :param header: the header.
# :param tb: the traceback.
# """
# channel = self.error_log
# if channel:
# await channel.send(header)
# for s in code_block(tb, 'Python'):
# await channel.send(s)
#
# Path: scripts/checks.py
# async def is_owner(ctx):
# """
# Check if the user is bot owner.
# :param ctx: the discord context
# :return: True if the user is the bot owner.
# """
# if not (await ctx.bot.is_owner(ctx.author)):
# raise NotOwner('This is an owner only command.')
# return True
which might include code, classes, or functions. Output only the next line. | async def __local_check(self, ctx: Context): |
Given snippet: <|code_start|>
class ConvertRegion(Converter):
__slots__ = ()
async def convert(self, ctx, argument) -> Region:
try:
return Region[str(argument).upper()] if argument else Region.NA
except KeyError:
raise BadArgument('Please enter a region in `NA, EU, RU, AS`')
async def get_player_id(ctx: Context, name, region: Region):
if not name:
raise BadArgument('Please enter a player name.')
bot = ctx.bot
wows_api = bot.wows_api
logger = bot.logger
data_manager = bot.data_manager
members, _ = leading_members(ctx, name)
if not members:
id_ = await gpid(region, wows_api, logger, name)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from discord.ext.commands import BadArgument, Context, Converter
from wowspy import Region
from data_manager.data_utils import get_prefix
from scripts.discord_utils import leading_members
from world_of_warships.war_gaming import get_clan_id as gcid, \
get_player_id as gpid
and context:
# Path: data_manager/data_utils.py
# def get_prefix(yasen, message: Message):
# """
# Get command prefix for a message.
# :param yasen: the bot instance.
# :param message: the message.
# :return: the prefix for that message.
# """
# guild = message.guild
# default = yasen.default_prefix
# if not guild:
# return default
# try:
# return yasen.data_manager.get_prefix(str(guild.id)) or default
# except AttributeError:
# return default
#
# Path: scripts/discord_utils.py
# def leading_members(ctx: Context, msg: str) -> tuple:
# """
# Get leading mentions as members from a message.
# :param ctx: the discord context.
# :param msg: the message.
# :return: A tuple of (a list of mentioned members, leftover message)
# """
# ids, left = leading_mentions(msg)
# guild = ctx.guild
# return [m for m in (get(guild.members, id=i) for i in set(ids)) if m], left
#
# Path: world_of_warships/war_gaming.py
# async def get_clan_id(region: Region, wows_api: WowsAsync,
# logger, search) -> Optional[int]:
# """
# Get clan id by search term.
# :param region: the region.
# :param wows_api: the WowsAsync instance.
# :param logger: the logger.
# :param search: the search query.
# :return: the clan id.
# """
# coro = wows_api.clans(region, search=search, language='en', limit=1)
# return await __get_id(coro, logger, 'clan_id')
#
# async def get_player_id(region: Region, wows_api: WowsAsync,
# logger, search) -> Optional[int]:
# """
# Get player id by search term.
# :param region: the region.
# :param wows_api: the WowsAsync instance.
# :param logger: the logger.
# :param search: the search query.
# :return: the player id.
# """
# coro = wows_api.players(region, search, language='en', limit=1)
# return await __get_id(coro, logger, 'account_id')
which might include code, classes, or functions. Output only the next line. | if id_ is not None: |
Here is a snippet: <|code_start|> raise BadArgument('Please enter a region in `NA, EU, RU, AS`')
async def get_player_id(ctx: Context, name, region: Region):
if not name:
raise BadArgument('Please enter a player name.')
bot = ctx.bot
wows_api = bot.wows_api
logger = bot.logger
data_manager = bot.data_manager
members, _ = leading_members(ctx, name)
if not members:
id_ = await gpid(region, wows_api, logger, name)
if id_ is not None:
return id_
raise BadArgument(f'Player **{name}** not found!')
member = members[0]
saved = data_manager.get_shame(
str(ctx.guild.id), str(member.id), region.name
)
if saved:
return saved
else:
prefix = get_prefix(ctx.bot, ctx.message)
raise BadArgument(
f'Member {member} is not registered in the {region} region. '
f'You can register using the `{prefix}shamelist add` command.'
)
<|code_end|>
. Write the next line using the current file imports:
from discord.ext.commands import BadArgument, Context, Converter
from wowspy import Region
from data_manager.data_utils import get_prefix
from scripts.discord_utils import leading_members
from world_of_warships.war_gaming import get_clan_id as gcid, \
get_player_id as gpid
and context from other files:
# Path: data_manager/data_utils.py
# def get_prefix(yasen, message: Message):
# """
# Get command prefix for a message.
# :param yasen: the bot instance.
# :param message: the message.
# :return: the prefix for that message.
# """
# guild = message.guild
# default = yasen.default_prefix
# if not guild:
# return default
# try:
# return yasen.data_manager.get_prefix(str(guild.id)) or default
# except AttributeError:
# return default
#
# Path: scripts/discord_utils.py
# def leading_members(ctx: Context, msg: str) -> tuple:
# """
# Get leading mentions as members from a message.
# :param ctx: the discord context.
# :param msg: the message.
# :return: A tuple of (a list of mentioned members, leftover message)
# """
# ids, left = leading_mentions(msg)
# guild = ctx.guild
# return [m for m in (get(guild.members, id=i) for i in set(ids)) if m], left
#
# Path: world_of_warships/war_gaming.py
# async def get_clan_id(region: Region, wows_api: WowsAsync,
# logger, search) -> Optional[int]:
# """
# Get clan id by search term.
# :param region: the region.
# :param wows_api: the WowsAsync instance.
# :param logger: the logger.
# :param search: the search query.
# :return: the clan id.
# """
# coro = wows_api.clans(region, search=search, language='en', limit=1)
# return await __get_id(coro, logger, 'clan_id')
#
# async def get_player_id(region: Region, wows_api: WowsAsync,
# logger, search) -> Optional[int]:
# """
# Get player id by search term.
# :param region: the region.
# :param wows_api: the WowsAsync instance.
# :param logger: the logger.
# :param search: the search query.
# :return: the player id.
# """
# coro = wows_api.players(region, search, language='en', limit=1)
# return await __get_id(coro, logger, 'account_id')
, which may include functions, classes, or code. Output only the next line. | async def get_clan_id(ctx: Context, name, region: Region): |
Using the snippet: <|code_start|> data_manager = bot.data_manager
members, _ = leading_members(ctx, name)
if not members:
id_ = await gpid(region, wows_api, logger, name)
if id_ is not None:
return id_
raise BadArgument(f'Player **{name}** not found!')
member = members[0]
saved = data_manager.get_shame(
str(ctx.guild.id), str(member.id), region.name
)
if saved:
return saved
else:
prefix = get_prefix(ctx.bot, ctx.message)
raise BadArgument(
f'Member {member} is not registered in the {region} region. '
f'You can register using the `{prefix}shamelist add` command.'
)
async def get_clan_id(ctx: Context, name, region: Region):
if not name:
raise BadArgument('Please enter a clan name.')
bot = ctx.bot
wows_api = bot.wows_api
logger = bot.logger
id_ = await gcid(region, wows_api, logger, name)
if id_ is not None:
return id_
<|code_end|>
, determine the next line of code. You have imports:
from discord.ext.commands import BadArgument, Context, Converter
from wowspy import Region
from data_manager.data_utils import get_prefix
from scripts.discord_utils import leading_members
from world_of_warships.war_gaming import get_clan_id as gcid, \
get_player_id as gpid
and context (class names, function names, or code) available:
# Path: data_manager/data_utils.py
# def get_prefix(yasen, message: Message):
# """
# Get command prefix for a message.
# :param yasen: the bot instance.
# :param message: the message.
# :return: the prefix for that message.
# """
# guild = message.guild
# default = yasen.default_prefix
# if not guild:
# return default
# try:
# return yasen.data_manager.get_prefix(str(guild.id)) or default
# except AttributeError:
# return default
#
# Path: scripts/discord_utils.py
# def leading_members(ctx: Context, msg: str) -> tuple:
# """
# Get leading mentions as members from a message.
# :param ctx: the discord context.
# :param msg: the message.
# :return: A tuple of (a list of mentioned members, leftover message)
# """
# ids, left = leading_mentions(msg)
# guild = ctx.guild
# return [m for m in (get(guild.members, id=i) for i in set(ids)) if m], left
#
# Path: world_of_warships/war_gaming.py
# async def get_clan_id(region: Region, wows_api: WowsAsync,
# logger, search) -> Optional[int]:
# """
# Get clan id by search term.
# :param region: the region.
# :param wows_api: the WowsAsync instance.
# :param logger: the logger.
# :param search: the search query.
# :return: the clan id.
# """
# coro = wows_api.clans(region, search=search, language='en', limit=1)
# return await __get_id(coro, logger, 'clan_id')
#
# async def get_player_id(region: Region, wows_api: WowsAsync,
# logger, search) -> Optional[int]:
# """
# Get player id by search term.
# :param region: the region.
# :param wows_api: the WowsAsync instance.
# :param logger: the logger.
# :param search: the search query.
# :return: the player id.
# """
# coro = wows_api.players(region, search, language='en', limit=1)
# return await __get_id(coro, logger, 'account_id')
. Output only the next line. | raise BadArgument(f'Clan **{name}** not found!') |
Given snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Gets information from ENVI header file and prints this to screen or saves
to a text file.
Author: Dan Clewley
Creation Date: 07/08/2015
read_hdr_file written by Ben Taylor
"""
###########################################################
# This file has been created by ARSF Data Analysis Node and
# is licensed under the GPL v3 Licence. A copy of this
# licence is available to download with this file.
###########################################################
from __future__ import print_function
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='''
Get information from ENVI header file and prints to screen.
Can optionally save some attributes (e.g., wavelengths) to
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import argparse
import csv
import os
import sys
from arsf_envi_reader import envi_header
and context:
# Path: arsf_envi_reader/envi_header.py
# ENVI_TO_NUMPY_DTYPE = {'1': numpy.uint8,
# '2': numpy.int16,
# '3': numpy.int32,
# '4': numpy.float32,
# '5': numpy.float64,
# '6': numpy.complex64,
# '9': numpy.complex128,
# '12': numpy.uint16,
# '13': numpy.uint32,
# '14': numpy.int64,
# '15': numpy.uint64}
# def find_hdr_file(rawfilename):
# def read_hdr_file(hdrfilename, keep_case=False):
# def write_envi_header(filename, header_dict):
which might include code, classes, or functions. Output only the next line. | a CSV file. |
Using the snippet: <|code_start|> "binning, temp, all", default = "fps, tint")
parser.add_argument("-c","--outcsv", required=False, type=str,
help="Output file to store values for each band to")
parser.add_argument("-k","--keep_order", required=False, action = "store_true",
help="If used, will keep the order specified in the commmand line")
args = parser.parse_args()
# On Windows don't have shell expansion so fake it using glob
if args.inputfiles[0].find('*') > -1:
args.inputfiles = glob.glob(args.inputfiles[0])
else:
args.inputfiles = args.inputfiles
# Check multiple files provided
if len(args.inputfiles) < 2:
print("Only one input file provided. Use get_info_from_header.py to display to screen")
sys.exit()
# Reorder files by line number
if not args.keep_order:
args.inputfiles.sort(key=alphanum_key)
#Static dictionary filled with all the information for every plot (titles, labels filename etc)
labeldict={'fps' : {'xlabel':'File Index','ylabel':'Frames per second','filename':'fps.png'},
'tint' : {'xlabel':'File Index','ylabel':'Integration time (ms)','filename':'tint.png'},
'nbands' : {'xlabel':'File Index','ylabel':'Number of bands','filename':'nbands.png'},
'nsamples' : {'xlabel':'File Index','ylabel':'Number of spatial samples','filename':'nsamples.png'},
'nlines' : {'xlabel':'File Index','ylabel':'Number of lines','filename':'nlines.png'},
'binning' : {'xlabel':'File Index','ylabel':'Spectral binning factor','filename':'binning.png'},
'temp' : {'xlabel':'File Index','ylabel':'Temperature of detector (K)','filename':'temp.png'}
<|code_end|>
, determine the next line of code. You have imports:
import argparse
import csv
import os
import sys
import matplotlib.pyplot as plt
import re
import numpy as np
import glob
from arsf_envi_reader import envi_header
and context (class names, function names, or code) available:
# Path: arsf_envi_reader/envi_header.py
# ENVI_TO_NUMPY_DTYPE = {'1': numpy.uint8,
# '2': numpy.int16,
# '3': numpy.int32,
# '4': numpy.float32,
# '5': numpy.float64,
# '6': numpy.complex64,
# '9': numpy.complex128,
# '12': numpy.uint16,
# '13': numpy.uint32,
# '14': numpy.int64,
# '15': numpy.uint64}
# def find_hdr_file(rawfilename):
# def read_hdr_file(hdrfilename, keep_case=False):
# def write_envi_header(filename, header_dict):
. Output only the next line. | } |
Using the snippet: <|code_start|> if os.path.isfile(args.targetheader[0] + '.bak'):
print("Backup file {}.bak already exists. Please remove "
"and retry".format(args.targetheader[0]), file=sys.stderr)
sys.exit(1)
shutil.copy2(args.targetheader[0],args.targetheader[0] + '.bak')
except IOError:
print("Could create backup copy of header in same destination as source "
"- possibly due to folder permissions. Aborting",file=sys.stderr)
except Exception:
raise
envi_header.write_envi_header(args.targetheader[0], target_header_dict)
print("Copied items to {0}, origional header "
"saved as {0}.bak".format(args.targetheader[0]))
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='''
Copy information from one ENVI header to another.
Created by ARSF-DAN at Plymouth Marine Laboratory.
Latest version available from https://github.com/pmlrsg/arsf_tools/.''')
parser.add_argument("sourceheader", nargs=1,type=str,
help="Header containing information to copy from")
parser.add_argument("targetheader", nargs=1,type=str,
help="Header to copy fields into")
parser.add_argument("-k","--keys", nargs='*', required=False, type=str,
help="Keys to copy from 'sourceheader' to 'targetheader'")
args = parser.parse_args()
<|code_end|>
, determine the next line of code. You have imports:
import argparse
import os
import shutil
import sys
from arsf_envi_reader import envi_header
and context (class names, function names, or code) available:
# Path: arsf_envi_reader/envi_header.py
# ENVI_TO_NUMPY_DTYPE = {'1': numpy.uint8,
# '2': numpy.int16,
# '3': numpy.int32,
# '4': numpy.float32,
# '5': numpy.float64,
# '6': numpy.complex64,
# '9': numpy.complex128,
# '12': numpy.uint16,
# '13': numpy.uint32,
# '14': numpy.int64,
# '15': numpy.uint64}
# def find_hdr_file(rawfilename):
# def read_hdr_file(hdrfilename, keep_case=False):
# def write_envi_header(filename, header_dict):
. Output only the next line. | run_copy_header(args.sourceheader[0], args.targetheader[0], args.keys) |
Continue the code snippet: <|code_start|>
class BookIndex(models.Model):
book_index_pk = models.AutoField(primary_key=True)
bytes = models.TextField()
filename = models.CharField(max_length=255)
mimetype = models.CharField(max_length=50)
class BookPages(models.Model):
book_pages_pk = models.AutoField(primary_key=True)
bytes = models.TextField()
filename = models.CharField(max_length=255)
mimetype = models.CharField(max_length=50)
class BookCover(models.Model):
book_cover_pk = models.AutoField(primary_key=True)
bytes = models.BinaryField()
filename = models.CharField(max_length=255)
mimetype = models.CharField(max_length=50)
class Book(models.Model):
book_pk = models.AutoField(primary_key=True)
name = models.CharField(max_length=100, unique=True)
index = models.FileField(
upload_to='model_filefields_example.BookIndex/bytes/filename/mimetype',
blank=True, null=True
)
pages = models.FileField(
<|code_end|>
. Use current file imports:
from django.db import models
from db_file_storage.model_utils import delete_file, delete_file_if_needed
from db_file_storage.compat import reverse
and context (classes, functions, or code) from other files:
# Path: db_file_storage/model_utils.py
# def delete_file(instance, filefield_name):
# """Delete the file (if any) from the database.
#
# Call this function immediately AFTER deleting the instance.
# """
# file_instance = getattr(instance, filefield_name)
# if file_instance:
# DatabaseFileStorage().delete(file_instance.name)
#
# def delete_file_if_needed(instance, filefield_name):
# """Delete file from database only if needed.
#
# When editing and the filefield is a new file,
# deletes the previous file (if any) from the database.
# Call this function immediately BEFORE saving the instance.
# """
# if instance.pk:
# model_class = type(instance)
#
# # Check if there is a file for the instance in the database
# if model_class.objects.filter(pk=instance.pk).exclude(
# **{'%s__isnull' % filefield_name: True}
# ).exclude(
# **{'%s__exact' % filefield_name: ''}
# ).exists():
# old_file = getattr(
# model_class.objects.only(filefield_name).get(pk=instance.pk),
# filefield_name
# )
# else:
# old_file = None
#
# # If there is a file, delete it if needed
# if old_file:
# # When editing and NOT changing the file,
# # old_file.name == getattr(instance, filefield_name)
# # returns True. In this case, the file must NOT be deleted.
# # If the file IS being changed, the comparison returns False.
# # In this case, the old file MUST be deleted.
# if (old_file.name == getattr(instance, filefield_name)) is False:
# DatabaseFileStorage().delete(old_file.name)
#
# Path: db_file_storage/compat.py
. Output only the next line. | upload_to='model_filefields_example.BookPages/bytes/filename/mimetype', |
Next line prediction: <|code_start|> blank=True, null=True
)
pages = models.FileField(
upload_to='model_filefields_example.BookPages/bytes/filename/mimetype',
blank=True, null=True
)
cover = models.ImageField(
upload_to='model_filefields_example.BookCover/bytes/filename/mimetype',
blank=True, null=True
)
def get_absolute_url(self):
return reverse('model_files:book.edit', kwargs={'pk': self.pk})
def save(self, *args, **kwargs):
delete_file_if_needed(self, 'index')
delete_file_if_needed(self, 'pages')
super(Book, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
super(Book, self).delete(*args, **kwargs)
delete_file(self, 'index')
delete_file(self, 'pages')
def __str__(self):
return self.name
class SoundDeviceInstructionManual(models.Model):
bytes = models.TextField()
<|code_end|>
. Use current file imports:
(from django.db import models
from db_file_storage.model_utils import delete_file, delete_file_if_needed
from db_file_storage.compat import reverse)
and context including class names, function names, or small code snippets from other files:
# Path: db_file_storage/model_utils.py
# def delete_file(instance, filefield_name):
# """Delete the file (if any) from the database.
#
# Call this function immediately AFTER deleting the instance.
# """
# file_instance = getattr(instance, filefield_name)
# if file_instance:
# DatabaseFileStorage().delete(file_instance.name)
#
# def delete_file_if_needed(instance, filefield_name):
# """Delete file from database only if needed.
#
# When editing and the filefield is a new file,
# deletes the previous file (if any) from the database.
# Call this function immediately BEFORE saving the instance.
# """
# if instance.pk:
# model_class = type(instance)
#
# # Check if there is a file for the instance in the database
# if model_class.objects.filter(pk=instance.pk).exclude(
# **{'%s__isnull' % filefield_name: True}
# ).exclude(
# **{'%s__exact' % filefield_name: ''}
# ).exists():
# old_file = getattr(
# model_class.objects.only(filefield_name).get(pk=instance.pk),
# filefield_name
# )
# else:
# old_file = None
#
# # If there is a file, delete it if needed
# if old_file:
# # When editing and NOT changing the file,
# # old_file.name == getattr(instance, filefield_name)
# # returns True. In this case, the file must NOT be deleted.
# # If the file IS being changed, the comparison returns False.
# # In this case, the old file MUST be deleted.
# if (old_file.name == getattr(instance, filefield_name)) is False:
# DatabaseFileStorage().delete(old_file.name)
#
# Path: db_file_storage/compat.py
. Output only the next line. | filename = models.CharField(max_length=255) |
Here is a snippet: <|code_start|> )
pages = models.FileField(
upload_to='model_filefields_example.BookPages/bytes/filename/mimetype',
blank=True, null=True
)
cover = models.ImageField(
upload_to='model_filefields_example.BookCover/bytes/filename/mimetype',
blank=True, null=True
)
def get_absolute_url(self):
return reverse('model_files:book.edit', kwargs={'pk': self.pk})
def save(self, *args, **kwargs):
delete_file_if_needed(self, 'index')
delete_file_if_needed(self, 'pages')
super(Book, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
super(Book, self).delete(*args, **kwargs)
delete_file(self, 'index')
delete_file(self, 'pages')
def __str__(self):
return self.name
class SoundDeviceInstructionManual(models.Model):
bytes = models.TextField()
filename = models.CharField(max_length=255)
<|code_end|>
. Write the next line using the current file imports:
from django.db import models
from db_file_storage.model_utils import delete_file, delete_file_if_needed
from db_file_storage.compat import reverse
and context from other files:
# Path: db_file_storage/model_utils.py
# def delete_file(instance, filefield_name):
# """Delete the file (if any) from the database.
#
# Call this function immediately AFTER deleting the instance.
# """
# file_instance = getattr(instance, filefield_name)
# if file_instance:
# DatabaseFileStorage().delete(file_instance.name)
#
# def delete_file_if_needed(instance, filefield_name):
# """Delete file from database only if needed.
#
# When editing and the filefield is a new file,
# deletes the previous file (if any) from the database.
# Call this function immediately BEFORE saving the instance.
# """
# if instance.pk:
# model_class = type(instance)
#
# # Check if there is a file for the instance in the database
# if model_class.objects.filter(pk=instance.pk).exclude(
# **{'%s__isnull' % filefield_name: True}
# ).exclude(
# **{'%s__exact' % filefield_name: ''}
# ).exists():
# old_file = getattr(
# model_class.objects.only(filefield_name).get(pk=instance.pk),
# filefield_name
# )
# else:
# old_file = None
#
# # If there is a file, delete it if needed
# if old_file:
# # When editing and NOT changing the file,
# # old_file.name == getattr(instance, filefield_name)
# # returns True. In this case, the file must NOT be deleted.
# # If the file IS being changed, the comparison returns False.
# # In this case, the old file MUST be deleted.
# if (old_file.name == getattr(instance, filefield_name)) is False:
# DatabaseFileStorage().delete(old_file.name)
#
# Path: db_file_storage/compat.py
, which may include functions, classes, or code. Output only the next line. | mimetype = models.CharField(max_length=50) |
Continue the code snippet: <|code_start|># project
urlpatterns = [
url(r'^download/', views.get_file, {'add_attachment_headers': True},
name='db_file_storage.download_file'),
url(r'^get/', views.get_file, {'add_attachment_headers': False},
<|code_end|>
. Use current file imports:
from . import views
from .compat import url
and context (classes, functions, or code) from other files:
# Path: db_file_storage/compat.py
. Output only the next line. | name='db_file_storage.get_file') |
Given the code snippet: <|code_start|># python
# django
# third party
# project
class SongLyricsWizard(SessionWizardView):
file_storage = FixedModelDatabaseFileStorage(
model_class_path='form_wizard_example.FormWizardTempFile',
content_field='content',
filename_field='name',
mimetype_field='mimetype'
)
form_list = [SongLyricsForm1, SongLyricsForm2, SongLyricsForm3]
template_name = 'form_wizard_example/form.html'
def done(self, form_list, **kwargs):
if sys.version_info.major == 3: # python3
form_list = list(form_list)
song = form_list[0].cleaned_data['song']
artist = form_list[0].cleaned_data['artist']
lyrics = form_list[1].cleaned_data['attachment'].read()
sender = form_list[2].cleaned_data['sender']
<|code_end|>
, generate the next line using the imports in this file:
import sys
from django.shortcuts import render
from db_file_storage.storage import FixedModelDatabaseFileStorage
from formtools.wizard.views import SessionWizardView
from .forms import SongLyricsForm1, SongLyricsForm2, SongLyricsForm3
and context (functions, classes, or occasionally code) from other files:
# Path: db_file_storage/storage.py
# class FixedModelDatabaseFileStorage(DatabaseFileStorage):
# """File storage system that saves files in the database.
#
# Intended for use without Models' FileFields, e.g. with Form Wizards.
# Uses a fixed Model to store the all the saved files.
# """
#
# def __init__(self, *args, **kwargs):
# try:
# self.model_class_path = kwargs.pop('model_class_path')
# self.content_field = kwargs.pop('content_field')
# self.filename_field = kwargs.pop('filename_field')
# self.mimetype_field = kwargs.pop('mimetype_field')
# except KeyError:
# raise KeyError(
# "keyword args 'model_class_path', 'content_field', "
# "'filename_field' and 'mimetype_field' are required."
# )
# super(FixedModelDatabaseFileStorage, self).__init__(*args, **kwargs)
#
# def _get_storage_attributes(self, name):
# return {
# 'model_class_path': self.model_class_path,
# 'content_field': self.content_field,
# 'filename_field': self.filename_field,
# 'mimetype_field': self.mimetype_field,
# 'filename': name,
# }
#
# Path: demo_and_tests/form_wizard_example/forms.py
# class SongLyricsForm1(forms.Form):
# song = forms.CharField(max_length=100)
# artist = forms.CharField(max_length=100)
#
# class SongLyricsForm2(forms.Form):
# attachment = forms.FileField(label='Lyrics', help_text='a plain text file')
#
# class SongLyricsForm3(forms.Form):
# sender = forms.CharField(max_length=100)
. Output only the next line. | context = {'song': song, 'artist': artist, |
Given the code snippet: <|code_start|># python
# django
# third party
# project
class SongLyricsWizard(SessionWizardView):
file_storage = FixedModelDatabaseFileStorage(
model_class_path='form_wizard_example.FormWizardTempFile',
content_field='content',
filename_field='name',
mimetype_field='mimetype'
)
form_list = [SongLyricsForm1, SongLyricsForm2, SongLyricsForm3]
template_name = 'form_wizard_example/form.html'
def done(self, form_list, **kwargs):
if sys.version_info.major == 3: # python3
<|code_end|>
, generate the next line using the imports in this file:
import sys
from django.shortcuts import render
from db_file_storage.storage import FixedModelDatabaseFileStorage
from formtools.wizard.views import SessionWizardView
from .forms import SongLyricsForm1, SongLyricsForm2, SongLyricsForm3
and context (functions, classes, or occasionally code) from other files:
# Path: db_file_storage/storage.py
# class FixedModelDatabaseFileStorage(DatabaseFileStorage):
# """File storage system that saves files in the database.
#
# Intended for use without Models' FileFields, e.g. with Form Wizards.
# Uses a fixed Model to store the all the saved files.
# """
#
# def __init__(self, *args, **kwargs):
# try:
# self.model_class_path = kwargs.pop('model_class_path')
# self.content_field = kwargs.pop('content_field')
# self.filename_field = kwargs.pop('filename_field')
# self.mimetype_field = kwargs.pop('mimetype_field')
# except KeyError:
# raise KeyError(
# "keyword args 'model_class_path', 'content_field', "
# "'filename_field' and 'mimetype_field' are required."
# )
# super(FixedModelDatabaseFileStorage, self).__init__(*args, **kwargs)
#
# def _get_storage_attributes(self, name):
# return {
# 'model_class_path': self.model_class_path,
# 'content_field': self.content_field,
# 'filename_field': self.filename_field,
# 'mimetype_field': self.mimetype_field,
# 'filename': name,
# }
#
# Path: demo_and_tests/form_wizard_example/forms.py
# class SongLyricsForm1(forms.Form):
# song = forms.CharField(max_length=100)
# artist = forms.CharField(max_length=100)
#
# class SongLyricsForm2(forms.Form):
# attachment = forms.FileField(label='Lyrics', help_text='a plain text file')
#
# class SongLyricsForm3(forms.Form):
# sender = forms.CharField(max_length=100)
. Output only the next line. | form_list = list(form_list) |
Predict the next line after this snippet: <|code_start|># python
# django
# third party
# project
class SongLyricsWizard(SessionWizardView):
file_storage = FixedModelDatabaseFileStorage(
model_class_path='form_wizard_example.FormWizardTempFile',
content_field='content',
filename_field='name',
mimetype_field='mimetype'
)
form_list = [SongLyricsForm1, SongLyricsForm2, SongLyricsForm3]
template_name = 'form_wizard_example/form.html'
def done(self, form_list, **kwargs):
<|code_end|>
using the current file's imports:
import sys
from django.shortcuts import render
from db_file_storage.storage import FixedModelDatabaseFileStorage
from formtools.wizard.views import SessionWizardView
from .forms import SongLyricsForm1, SongLyricsForm2, SongLyricsForm3
and any relevant context from other files:
# Path: db_file_storage/storage.py
# class FixedModelDatabaseFileStorage(DatabaseFileStorage):
# """File storage system that saves files in the database.
#
# Intended for use without Models' FileFields, e.g. with Form Wizards.
# Uses a fixed Model to store the all the saved files.
# """
#
# def __init__(self, *args, **kwargs):
# try:
# self.model_class_path = kwargs.pop('model_class_path')
# self.content_field = kwargs.pop('content_field')
# self.filename_field = kwargs.pop('filename_field')
# self.mimetype_field = kwargs.pop('mimetype_field')
# except KeyError:
# raise KeyError(
# "keyword args 'model_class_path', 'content_field', "
# "'filename_field' and 'mimetype_field' are required."
# )
# super(FixedModelDatabaseFileStorage, self).__init__(*args, **kwargs)
#
# def _get_storage_attributes(self, name):
# return {
# 'model_class_path': self.model_class_path,
# 'content_field': self.content_field,
# 'filename_field': self.filename_field,
# 'mimetype_field': self.mimetype_field,
# 'filename': name,
# }
#
# Path: demo_and_tests/form_wizard_example/forms.py
# class SongLyricsForm1(forms.Form):
# song = forms.CharField(max_length=100)
# artist = forms.CharField(max_length=100)
#
# class SongLyricsForm2(forms.Form):
# attachment = forms.FileField(label='Lyrics', help_text='a plain text file')
#
# class SongLyricsForm3(forms.Form):
# sender = forms.CharField(max_length=100)
. Output only the next line. | if sys.version_info.major == 3: # python3 |
Given snippet: <|code_start|># python
# django
# third party
# project
class SongLyricsWizard(SessionWizardView):
file_storage = FixedModelDatabaseFileStorage(
model_class_path='form_wizard_example.FormWizardTempFile',
content_field='content',
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import sys
from django.shortcuts import render
from db_file_storage.storage import FixedModelDatabaseFileStorage
from formtools.wizard.views import SessionWizardView
from .forms import SongLyricsForm1, SongLyricsForm2, SongLyricsForm3
and context:
# Path: db_file_storage/storage.py
# class FixedModelDatabaseFileStorage(DatabaseFileStorage):
# """File storage system that saves files in the database.
#
# Intended for use without Models' FileFields, e.g. with Form Wizards.
# Uses a fixed Model to store the all the saved files.
# """
#
# def __init__(self, *args, **kwargs):
# try:
# self.model_class_path = kwargs.pop('model_class_path')
# self.content_field = kwargs.pop('content_field')
# self.filename_field = kwargs.pop('filename_field')
# self.mimetype_field = kwargs.pop('mimetype_field')
# except KeyError:
# raise KeyError(
# "keyword args 'model_class_path', 'content_field', "
# "'filename_field' and 'mimetype_field' are required."
# )
# super(FixedModelDatabaseFileStorage, self).__init__(*args, **kwargs)
#
# def _get_storage_attributes(self, name):
# return {
# 'model_class_path': self.model_class_path,
# 'content_field': self.content_field,
# 'filename_field': self.filename_field,
# 'mimetype_field': self.mimetype_field,
# 'filename': name,
# }
#
# Path: demo_and_tests/form_wizard_example/forms.py
# class SongLyricsForm1(forms.Form):
# song = forms.CharField(max_length=100)
# artist = forms.CharField(max_length=100)
#
# class SongLyricsForm2(forms.Form):
# attachment = forms.FileField(label='Lyrics', help_text='a plain text file')
#
# class SongLyricsForm3(forms.Form):
# sender = forms.CharField(max_length=100)
which might include code, classes, or functions. Output only the next line. | filename_field='name', |
Given the code snippet: <|code_start|>
saved_device = SoundDevice.objects.get(id=device_id)
saved_device.instruction_manual.open('r')
saved_device_file_content_string = \
saved_device.instruction_manual.read()
saved_device.instruction_manual.close()
self.assertEqual(
file_content_string,
saved_device_file_content_string
)
def test_save_file_with_accents_without_using_form(self):
file_name = 'manual.txt'
if sys.version_info.major == 2: # python2
file_content_string = 'Accents: áãüí'.encode('utf-8')
else: # python3
file_content_string = bytearray('Accents: áãüí', 'utf-8')
content_file = ContentFile(file_content_string)
device = SoundDevice(name='BXPM 778')
device.instruction_manual.save(file_name, content_file)
device.save()
saved_device = SoundDevice.objects.get()
saved_device.instruction_manual.open('r')
saved_device_file_content_string = \
saved_device.instruction_manual.read()
saved_device.instruction_manual.close()
<|code_end|>
, generate the next line using the imports in this file:
import mimetypes
import os
import sys
from django.core.files.storage import default_storage
from django.conf import settings
from django.core.files.base import ContentFile
from django.test import TestCase
from django.utils.http import urlencode
from .forms import BookForm, BookAdminForm
from .models import Book, BookIndex, BookPages, SoundDevice
from db_file_storage.compat import reverse
and context (functions, classes, or occasionally code) from other files:
# Path: demo_and_tests/model_filefields_example/forms.py
# class BookForm(forms.ModelForm):
# class Meta(object):
# model = Book
# exclude = []
# widgets = {
# 'index': DBClearableFileInput,
# 'pages': DBClearableFileInput,
# 'cover': DBClearableFileInput,
# }
#
# class BookAdminForm(adminforms.ModelForm):
# class Meta(object):
# model = Book
# exclude = []
# widgets = {
# 'index': DBAdminClearableFileInput,
# 'pages': DBAdminClearableFileInput,
# 'cover': DBAdminClearableFileInput,
# }
#
# Path: demo_and_tests/model_filefields_example/models.py
# class Book(models.Model):
# book_pk = models.AutoField(primary_key=True)
# name = models.CharField(max_length=100, unique=True)
# index = models.FileField(
# upload_to='model_filefields_example.BookIndex/bytes/filename/mimetype',
# blank=True, null=True
# )
# pages = models.FileField(
# upload_to='model_filefields_example.BookPages/bytes/filename/mimetype',
# blank=True, null=True
# )
# cover = models.ImageField(
# upload_to='model_filefields_example.BookCover/bytes/filename/mimetype',
# blank=True, null=True
# )
#
# def get_absolute_url(self):
# return reverse('model_files:book.edit', kwargs={'pk': self.pk})
#
# def save(self, *args, **kwargs):
# delete_file_if_needed(self, 'index')
# delete_file_if_needed(self, 'pages')
# super(Book, self).save(*args, **kwargs)
#
# def delete(self, *args, **kwargs):
# super(Book, self).delete(*args, **kwargs)
# delete_file(self, 'index')
# delete_file(self, 'pages')
#
# def __str__(self):
# return self.name
#
# class BookIndex(models.Model):
# book_index_pk = models.AutoField(primary_key=True)
# bytes = models.TextField()
# filename = models.CharField(max_length=255)
# mimetype = models.CharField(max_length=50)
#
# class BookPages(models.Model):
# book_pages_pk = models.AutoField(primary_key=True)
# bytes = models.TextField()
# filename = models.CharField(max_length=255)
# mimetype = models.CharField(max_length=50)
#
# class SoundDevice(models.Model):
# name = models.CharField(max_length=100)
# instruction_manual = models.FileField(
# upload_to='model_filefields_example.SoundDeviceInstructionManual'
# '/bytes/filename/mimetype',
# blank=True,
# null=True
# )
#
# Path: db_file_storage/compat.py
. Output only the next line. | self.assertEqual( |
Given the following code snippet before the placeholder: <|code_start|> save_new_url = reverse('model_files:book.add')
download_url = reverse('db_file_storage.download_file')
#
# Add "Inferno" book without index or pages.
#
form_data = {'name': 'Inferno'}
self.client.post(save_new_url, form_data, follow=True)
inferno = Book.objects.get(name='Inferno')
edit_inferno_url = reverse('model_files:book.edit',
kwargs={'pk': inferno.pk})
# Assert book file fields are empty
self.assertEqual(inferno.index.name, '')
self.assertEqual(inferno.pages.name, '')
# Assert no BookIndex and no BookPages were created
self.assertEqual(BookIndex.objects.count(), 0)
self.assertEqual(BookPages.objects.count(), 0)
#
# Edit Inferno: add index file
#
form_data = {'name': 'Inferno',
'index': open(get_file_path('inferno_index.txt'))}
self.client.post(edit_inferno_url, form_data, follow=True)
inferno = Book.objects.get(name='Inferno')
# Assert that only a BookIndex was created
self.assertEqual(BookIndex.objects.count(), 1)
self.assertEqual(BookPages.objects.count(), 0)
# Verify Inferno's new index
url = download_url + '?' + urlencode({'name': inferno.index.name})
<|code_end|>
, predict the next line using imports from the current file:
import mimetypes
import os
import sys
from django.core.files.storage import default_storage
from django.conf import settings
from django.core.files.base import ContentFile
from django.test import TestCase
from django.utils.http import urlencode
from .forms import BookForm, BookAdminForm
from .models import Book, BookIndex, BookPages, SoundDevice
from db_file_storage.compat import reverse
and context including class names, function names, and sometimes code from other files:
# Path: demo_and_tests/model_filefields_example/forms.py
# class BookForm(forms.ModelForm):
# class Meta(object):
# model = Book
# exclude = []
# widgets = {
# 'index': DBClearableFileInput,
# 'pages': DBClearableFileInput,
# 'cover': DBClearableFileInput,
# }
#
# class BookAdminForm(adminforms.ModelForm):
# class Meta(object):
# model = Book
# exclude = []
# widgets = {
# 'index': DBAdminClearableFileInput,
# 'pages': DBAdminClearableFileInput,
# 'cover': DBAdminClearableFileInput,
# }
#
# Path: demo_and_tests/model_filefields_example/models.py
# class Book(models.Model):
# book_pk = models.AutoField(primary_key=True)
# name = models.CharField(max_length=100, unique=True)
# index = models.FileField(
# upload_to='model_filefields_example.BookIndex/bytes/filename/mimetype',
# blank=True, null=True
# )
# pages = models.FileField(
# upload_to='model_filefields_example.BookPages/bytes/filename/mimetype',
# blank=True, null=True
# )
# cover = models.ImageField(
# upload_to='model_filefields_example.BookCover/bytes/filename/mimetype',
# blank=True, null=True
# )
#
# def get_absolute_url(self):
# return reverse('model_files:book.edit', kwargs={'pk': self.pk})
#
# def save(self, *args, **kwargs):
# delete_file_if_needed(self, 'index')
# delete_file_if_needed(self, 'pages')
# super(Book, self).save(*args, **kwargs)
#
# def delete(self, *args, **kwargs):
# super(Book, self).delete(*args, **kwargs)
# delete_file(self, 'index')
# delete_file(self, 'pages')
#
# def __str__(self):
# return self.name
#
# class BookIndex(models.Model):
# book_index_pk = models.AutoField(primary_key=True)
# bytes = models.TextField()
# filename = models.CharField(max_length=255)
# mimetype = models.CharField(max_length=50)
#
# class BookPages(models.Model):
# book_pages_pk = models.AutoField(primary_key=True)
# bytes = models.TextField()
# filename = models.CharField(max_length=255)
# mimetype = models.CharField(max_length=50)
#
# class SoundDevice(models.Model):
# name = models.CharField(max_length=100)
# instruction_manual = models.FileField(
# upload_to='model_filefields_example.SoundDeviceInstructionManual'
# '/bytes/filename/mimetype',
# blank=True,
# null=True
# )
#
# Path: db_file_storage/compat.py
. Output only the next line. | self.verify_file(url, 'inferno_index.txt') |
Here is a snippet: <|code_start|>
def get_file_path(file_name):
return os.path.join(settings.TEST_FILES_DIR, file_name)
class AddEditAndDeleteBooksTestCase(TestCase):
def test_download(self):
# Create book
save_url = reverse('model_files:book.add')
index_file = open(get_file_path('inferno_index.txt'))
form_data = {'name': 'Inferno',
'index': index_file}
self.client.post(save_url, form_data, follow=True)
index_file.close()
book = Book.objects.get(name='Inferno')
# Valid name
download_url = reverse('db_file_storage.download_file')
download_url += '?' + urlencode({'name': str(book.index)})
response = self.client.get(download_url)
self.assertEqual(response.status_code, 200)
# Invalid name
download_url = reverse('db_file_storage.download_file')
download_url += '?' + urlencode({'name': 'invalid_name'})
response = self.client.get(download_url)
self.assertEqual(response.status_code, 400)
<|code_end|>
. Write the next line using the current file imports:
import mimetypes
import os
import sys
from django.core.files.storage import default_storage
from django.conf import settings
from django.core.files.base import ContentFile
from django.test import TestCase
from django.utils.http import urlencode
from .forms import BookForm, BookAdminForm
from .models import Book, BookIndex, BookPages, SoundDevice
from db_file_storage.compat import reverse
and context from other files:
# Path: demo_and_tests/model_filefields_example/forms.py
# class BookForm(forms.ModelForm):
# class Meta(object):
# model = Book
# exclude = []
# widgets = {
# 'index': DBClearableFileInput,
# 'pages': DBClearableFileInput,
# 'cover': DBClearableFileInput,
# }
#
# class BookAdminForm(adminforms.ModelForm):
# class Meta(object):
# model = Book
# exclude = []
# widgets = {
# 'index': DBAdminClearableFileInput,
# 'pages': DBAdminClearableFileInput,
# 'cover': DBAdminClearableFileInput,
# }
#
# Path: demo_and_tests/model_filefields_example/models.py
# class Book(models.Model):
# book_pk = models.AutoField(primary_key=True)
# name = models.CharField(max_length=100, unique=True)
# index = models.FileField(
# upload_to='model_filefields_example.BookIndex/bytes/filename/mimetype',
# blank=True, null=True
# )
# pages = models.FileField(
# upload_to='model_filefields_example.BookPages/bytes/filename/mimetype',
# blank=True, null=True
# )
# cover = models.ImageField(
# upload_to='model_filefields_example.BookCover/bytes/filename/mimetype',
# blank=True, null=True
# )
#
# def get_absolute_url(self):
# return reverse('model_files:book.edit', kwargs={'pk': self.pk})
#
# def save(self, *args, **kwargs):
# delete_file_if_needed(self, 'index')
# delete_file_if_needed(self, 'pages')
# super(Book, self).save(*args, **kwargs)
#
# def delete(self, *args, **kwargs):
# super(Book, self).delete(*args, **kwargs)
# delete_file(self, 'index')
# delete_file(self, 'pages')
#
# def __str__(self):
# return self.name
#
# class BookIndex(models.Model):
# book_index_pk = models.AutoField(primary_key=True)
# bytes = models.TextField()
# filename = models.CharField(max_length=255)
# mimetype = models.CharField(max_length=50)
#
# class BookPages(models.Model):
# book_pages_pk = models.AutoField(primary_key=True)
# bytes = models.TextField()
# filename = models.CharField(max_length=255)
# mimetype = models.CharField(max_length=50)
#
# class SoundDevice(models.Model):
# name = models.CharField(max_length=100)
# instruction_manual = models.FileField(
# upload_to='model_filefields_example.SoundDeviceInstructionManual'
# '/bytes/filename/mimetype',
# blank=True,
# null=True
# )
#
# Path: db_file_storage/compat.py
, which may include functions, classes, or code. Output only the next line. | def test_download_with_extra_headers(self): |
Predict the next line after this snippet: <|code_start|> # Assert that the mimetype of the saved file is correct
self.assertEqual(
mimetypes.guess_type(file_name)[0],
response['Content-Type']
)
def test_files_operations(self):
save_new_url = reverse('model_files:book.add')
download_url = reverse('db_file_storage.download_file')
#
# Add "Inferno" book without index or pages.
#
form_data = {'name': 'Inferno'}
self.client.post(save_new_url, form_data, follow=True)
inferno = Book.objects.get(name='Inferno')
edit_inferno_url = reverse('model_files:book.edit',
kwargs={'pk': inferno.pk})
# Assert book file fields are empty
self.assertEqual(inferno.index.name, '')
self.assertEqual(inferno.pages.name, '')
# Assert no BookIndex and no BookPages were created
self.assertEqual(BookIndex.objects.count(), 0)
self.assertEqual(BookPages.objects.count(), 0)
#
# Edit Inferno: add index file
#
form_data = {'name': 'Inferno',
'index': open(get_file_path('inferno_index.txt'))}
<|code_end|>
using the current file's imports:
import mimetypes
import os
import sys
from django.core.files.storage import default_storage
from django.conf import settings
from django.core.files.base import ContentFile
from django.test import TestCase
from django.utils.http import urlencode
from .forms import BookForm, BookAdminForm
from .models import Book, BookIndex, BookPages, SoundDevice
from db_file_storage.compat import reverse
and any relevant context from other files:
# Path: demo_and_tests/model_filefields_example/forms.py
# class BookForm(forms.ModelForm):
# class Meta(object):
# model = Book
# exclude = []
# widgets = {
# 'index': DBClearableFileInput,
# 'pages': DBClearableFileInput,
# 'cover': DBClearableFileInput,
# }
#
# class BookAdminForm(adminforms.ModelForm):
# class Meta(object):
# model = Book
# exclude = []
# widgets = {
# 'index': DBAdminClearableFileInput,
# 'pages': DBAdminClearableFileInput,
# 'cover': DBAdminClearableFileInput,
# }
#
# Path: demo_and_tests/model_filefields_example/models.py
# class Book(models.Model):
# book_pk = models.AutoField(primary_key=True)
# name = models.CharField(max_length=100, unique=True)
# index = models.FileField(
# upload_to='model_filefields_example.BookIndex/bytes/filename/mimetype',
# blank=True, null=True
# )
# pages = models.FileField(
# upload_to='model_filefields_example.BookPages/bytes/filename/mimetype',
# blank=True, null=True
# )
# cover = models.ImageField(
# upload_to='model_filefields_example.BookCover/bytes/filename/mimetype',
# blank=True, null=True
# )
#
# def get_absolute_url(self):
# return reverse('model_files:book.edit', kwargs={'pk': self.pk})
#
# def save(self, *args, **kwargs):
# delete_file_if_needed(self, 'index')
# delete_file_if_needed(self, 'pages')
# super(Book, self).save(*args, **kwargs)
#
# def delete(self, *args, **kwargs):
# super(Book, self).delete(*args, **kwargs)
# delete_file(self, 'index')
# delete_file(self, 'pages')
#
# def __str__(self):
# return self.name
#
# class BookIndex(models.Model):
# book_index_pk = models.AutoField(primary_key=True)
# bytes = models.TextField()
# filename = models.CharField(max_length=255)
# mimetype = models.CharField(max_length=50)
#
# class BookPages(models.Model):
# book_pages_pk = models.AutoField(primary_key=True)
# bytes = models.TextField()
# filename = models.CharField(max_length=255)
# mimetype = models.CharField(max_length=50)
#
# class SoundDevice(models.Model):
# name = models.CharField(max_length=100)
# instruction_manual = models.FileField(
# upload_to='model_filefields_example.SoundDeviceInstructionManual'
# '/bytes/filename/mimetype',
# blank=True,
# null=True
# )
#
# Path: db_file_storage/compat.py
. Output only the next line. | self.client.post(edit_inferno_url, form_data, follow=True) |
Continue the code snippet: <|code_start|> response = self.client.get(download_url)
self.assertEqual(response.status_code, 200)
# Invalid name
download_url = reverse('db_file_storage.download_file')
download_url += '?' + urlencode({'name': 'invalid_name'})
response = self.client.get(download_url)
self.assertEqual(response.status_code, 400)
def test_download_with_extra_headers(self):
# Create book
save_url = reverse('model_files:book.add')
cover_file = open(get_file_path('book.png'), 'rb')
form_data = {'name': 'Inferno',
'cover': cover_file}
self.client.post(save_url, form_data, follow=True)
cover_file.close()
book = Book.objects.get(name='Inferno')
# Valid name
download_url = reverse('model_files:book.download_cover')
download_url += '?' + urlencode({'name': str(book.cover)})
response = self.client.get(download_url)
self.assertEqual(response.status_code, 200)
print(dir(response))
self.assertEqual(response['Content-Language'], 'en')
def test_form_widget_shows_proper_filename(self):
# Create book
save_url = reverse('model_files:book.add')
<|code_end|>
. Use current file imports:
import mimetypes
import os
import sys
from django.core.files.storage import default_storage
from django.conf import settings
from django.core.files.base import ContentFile
from django.test import TestCase
from django.utils.http import urlencode
from .forms import BookForm, BookAdminForm
from .models import Book, BookIndex, BookPages, SoundDevice
from db_file_storage.compat import reverse
and context (classes, functions, or code) from other files:
# Path: demo_and_tests/model_filefields_example/forms.py
# class BookForm(forms.ModelForm):
# class Meta(object):
# model = Book
# exclude = []
# widgets = {
# 'index': DBClearableFileInput,
# 'pages': DBClearableFileInput,
# 'cover': DBClearableFileInput,
# }
#
# class BookAdminForm(adminforms.ModelForm):
# class Meta(object):
# model = Book
# exclude = []
# widgets = {
# 'index': DBAdminClearableFileInput,
# 'pages': DBAdminClearableFileInput,
# 'cover': DBAdminClearableFileInput,
# }
#
# Path: demo_and_tests/model_filefields_example/models.py
# class Book(models.Model):
# book_pk = models.AutoField(primary_key=True)
# name = models.CharField(max_length=100, unique=True)
# index = models.FileField(
# upload_to='model_filefields_example.BookIndex/bytes/filename/mimetype',
# blank=True, null=True
# )
# pages = models.FileField(
# upload_to='model_filefields_example.BookPages/bytes/filename/mimetype',
# blank=True, null=True
# )
# cover = models.ImageField(
# upload_to='model_filefields_example.BookCover/bytes/filename/mimetype',
# blank=True, null=True
# )
#
# def get_absolute_url(self):
# return reverse('model_files:book.edit', kwargs={'pk': self.pk})
#
# def save(self, *args, **kwargs):
# delete_file_if_needed(self, 'index')
# delete_file_if_needed(self, 'pages')
# super(Book, self).save(*args, **kwargs)
#
# def delete(self, *args, **kwargs):
# super(Book, self).delete(*args, **kwargs)
# delete_file(self, 'index')
# delete_file(self, 'pages')
#
# def __str__(self):
# return self.name
#
# class BookIndex(models.Model):
# book_index_pk = models.AutoField(primary_key=True)
# bytes = models.TextField()
# filename = models.CharField(max_length=255)
# mimetype = models.CharField(max_length=50)
#
# class BookPages(models.Model):
# book_pages_pk = models.AutoField(primary_key=True)
# bytes = models.TextField()
# filename = models.CharField(max_length=255)
# mimetype = models.CharField(max_length=50)
#
# class SoundDevice(models.Model):
# name = models.CharField(max_length=100)
# instruction_manual = models.FileField(
# upload_to='model_filefields_example.SoundDeviceInstructionManual'
# '/bytes/filename/mimetype',
# blank=True,
# null=True
# )
#
# Path: db_file_storage/compat.py
. Output only the next line. | index_file = open(get_file_path('inferno_index.txt')) |
Continue the code snippet: <|code_start|> # Assert that the mimetype of the saved file is correct
self.assertEqual(
mimetypes.guess_type(file_name)[0],
response['Content-Type']
)
def test_files_operations(self):
save_new_url = reverse('model_files:book.add')
download_url = reverse('db_file_storage.download_file')
#
# Add "Inferno" book without index or pages.
#
form_data = {'name': 'Inferno'}
self.client.post(save_new_url, form_data, follow=True)
inferno = Book.objects.get(name='Inferno')
edit_inferno_url = reverse('model_files:book.edit',
kwargs={'pk': inferno.pk})
# Assert book file fields are empty
self.assertEqual(inferno.index.name, '')
self.assertEqual(inferno.pages.name, '')
# Assert no BookIndex and no BookPages were created
self.assertEqual(BookIndex.objects.count(), 0)
self.assertEqual(BookPages.objects.count(), 0)
#
# Edit Inferno: add index file
#
form_data = {'name': 'Inferno',
'index': open(get_file_path('inferno_index.txt'))}
<|code_end|>
. Use current file imports:
import mimetypes
import os
import sys
from django.core.files.storage import default_storage
from django.conf import settings
from django.core.files.base import ContentFile
from django.test import TestCase
from django.utils.http import urlencode
from .forms import BookForm, BookAdminForm
from .models import Book, BookIndex, BookPages, SoundDevice
from db_file_storage.compat import reverse
and context (classes, functions, or code) from other files:
# Path: demo_and_tests/model_filefields_example/forms.py
# class BookForm(forms.ModelForm):
# class Meta(object):
# model = Book
# exclude = []
# widgets = {
# 'index': DBClearableFileInput,
# 'pages': DBClearableFileInput,
# 'cover': DBClearableFileInput,
# }
#
# class BookAdminForm(adminforms.ModelForm):
# class Meta(object):
# model = Book
# exclude = []
# widgets = {
# 'index': DBAdminClearableFileInput,
# 'pages': DBAdminClearableFileInput,
# 'cover': DBAdminClearableFileInput,
# }
#
# Path: demo_and_tests/model_filefields_example/models.py
# class Book(models.Model):
# book_pk = models.AutoField(primary_key=True)
# name = models.CharField(max_length=100, unique=True)
# index = models.FileField(
# upload_to='model_filefields_example.BookIndex/bytes/filename/mimetype',
# blank=True, null=True
# )
# pages = models.FileField(
# upload_to='model_filefields_example.BookPages/bytes/filename/mimetype',
# blank=True, null=True
# )
# cover = models.ImageField(
# upload_to='model_filefields_example.BookCover/bytes/filename/mimetype',
# blank=True, null=True
# )
#
# def get_absolute_url(self):
# return reverse('model_files:book.edit', kwargs={'pk': self.pk})
#
# def save(self, *args, **kwargs):
# delete_file_if_needed(self, 'index')
# delete_file_if_needed(self, 'pages')
# super(Book, self).save(*args, **kwargs)
#
# def delete(self, *args, **kwargs):
# super(Book, self).delete(*args, **kwargs)
# delete_file(self, 'index')
# delete_file(self, 'pages')
#
# def __str__(self):
# return self.name
#
# class BookIndex(models.Model):
# book_index_pk = models.AutoField(primary_key=True)
# bytes = models.TextField()
# filename = models.CharField(max_length=255)
# mimetype = models.CharField(max_length=50)
#
# class BookPages(models.Model):
# book_pages_pk = models.AutoField(primary_key=True)
# bytes = models.TextField()
# filename = models.CharField(max_length=255)
# mimetype = models.CharField(max_length=50)
#
# class SoundDevice(models.Model):
# name = models.CharField(max_length=100)
# instruction_manual = models.FileField(
# upload_to='model_filefields_example.SoundDeviceInstructionManual'
# '/bytes/filename/mimetype',
# blank=True,
# null=True
# )
#
# Path: db_file_storage/compat.py
. Output only the next line. | self.client.post(edit_inferno_url, form_data, follow=True) |
Predict the next line for this snippet: <|code_start|> 'index-clear': 'on'}
self.client.post(edit_lost_symbol_url, form_data, follow=True)
lost_symbol = Book.objects.get(name='Lost Symbol')
inferno = Book.objects.get(name='Inferno')
# Assert one BookIndex was deleted
self.assertEqual(BookIndex.objects.count(), 1)
self.assertEqual(BookPages.objects.count(), 1)
# Assert that the contents of Lost Symbol's pages are still correct
url = download_url + '?' + urlencode({'name': lost_symbol.pages.name})
self.verify_file(url, 'lost_symbol_pages_v1.txt')
# Assert that the contents of Inferno's index are still correct
url = download_url + '?' + urlencode({'name': inferno.index.name})
self.verify_file(url, 'inferno_index.txt')
# Assert that Inferno's pages are still empty
self.assertEqual(inferno.pages.name, '')
# Assert that Lost Symbol's index is empty now
self.assertEqual(lost_symbol.index.name, '')
#
# Delete Inferno
#
inferno.delete()
lost_symbol = Book.objects.get(name='Lost Symbol')
# Assert one BookIndex was deleted
self.assertEqual(BookIndex.objects.count(), 0)
self.assertEqual(BookPages.objects.count(), 1)
# Assert that the contents Lost Symbol's pages are still correct
url = download_url + '?' + urlencode({'name': lost_symbol.pages.name})
self.verify_file(url, 'lost_symbol_pages_v1.txt')
# Assert that Lost Symbol's index is still empty
<|code_end|>
with the help of current file imports:
import mimetypes
import os
import sys
from django.core.files.storage import default_storage
from django.conf import settings
from django.core.files.base import ContentFile
from django.test import TestCase
from django.utils.http import urlencode
from .forms import BookForm, BookAdminForm
from .models import Book, BookIndex, BookPages, SoundDevice
from db_file_storage.compat import reverse
and context from other files:
# Path: demo_and_tests/model_filefields_example/forms.py
# class BookForm(forms.ModelForm):
# class Meta(object):
# model = Book
# exclude = []
# widgets = {
# 'index': DBClearableFileInput,
# 'pages': DBClearableFileInput,
# 'cover': DBClearableFileInput,
# }
#
# class BookAdminForm(adminforms.ModelForm):
# class Meta(object):
# model = Book
# exclude = []
# widgets = {
# 'index': DBAdminClearableFileInput,
# 'pages': DBAdminClearableFileInput,
# 'cover': DBAdminClearableFileInput,
# }
#
# Path: demo_and_tests/model_filefields_example/models.py
# class Book(models.Model):
# book_pk = models.AutoField(primary_key=True)
# name = models.CharField(max_length=100, unique=True)
# index = models.FileField(
# upload_to='model_filefields_example.BookIndex/bytes/filename/mimetype',
# blank=True, null=True
# )
# pages = models.FileField(
# upload_to='model_filefields_example.BookPages/bytes/filename/mimetype',
# blank=True, null=True
# )
# cover = models.ImageField(
# upload_to='model_filefields_example.BookCover/bytes/filename/mimetype',
# blank=True, null=True
# )
#
# def get_absolute_url(self):
# return reverse('model_files:book.edit', kwargs={'pk': self.pk})
#
# def save(self, *args, **kwargs):
# delete_file_if_needed(self, 'index')
# delete_file_if_needed(self, 'pages')
# super(Book, self).save(*args, **kwargs)
#
# def delete(self, *args, **kwargs):
# super(Book, self).delete(*args, **kwargs)
# delete_file(self, 'index')
# delete_file(self, 'pages')
#
# def __str__(self):
# return self.name
#
# class BookIndex(models.Model):
# book_index_pk = models.AutoField(primary_key=True)
# bytes = models.TextField()
# filename = models.CharField(max_length=255)
# mimetype = models.CharField(max_length=50)
#
# class BookPages(models.Model):
# book_pages_pk = models.AutoField(primary_key=True)
# bytes = models.TextField()
# filename = models.CharField(max_length=255)
# mimetype = models.CharField(max_length=50)
#
# class SoundDevice(models.Model):
# name = models.CharField(max_length=100)
# instruction_manual = models.FileField(
# upload_to='model_filefields_example.SoundDeviceInstructionManual'
# '/bytes/filename/mimetype',
# blank=True,
# null=True
# )
#
# Path: db_file_storage/compat.py
, which may contain function names, class names, or code. Output only the next line. | self.assertEqual(lost_symbol.index.name, '') |
Continue the code snippet: <|code_start|># django
# third party
# project
class BookForm(forms.ModelForm):
class Meta(object):
model = Book
exclude = []
widgets = {
'index': DBClearableFileInput,
'pages': DBClearableFileInput,
'cover': DBClearableFileInput,
}
class BookAdminForm(adminforms.ModelForm):
class Meta(object):
model = Book
exclude = []
widgets = {
'index': DBAdminClearableFileInput,
'pages': DBAdminClearableFileInput,
'cover': DBAdminClearableFileInput,
}
class SoundDeviceForm(forms.ModelForm):
class Meta(object):
model = SoundDevice
<|code_end|>
. Use current file imports:
from django import forms
from django.contrib.admin.forms import forms as adminforms
from db_file_storage.form_widgets import DBClearableFileInput, \
DBAdminClearableFileInput
from .models import Book, SoundDevice
and context (classes, functions, or code) from other files:
# Path: db_file_storage/form_widgets.py
# class DBClearableFileInput(ClearableFileInput):
# template_name = 'db_file_storage/widgets/clearable_file_input.html'
#
# class DBAdminClearableFileInput(AdminFileWidget):
# template_name = 'db_file_storage/widgets/admin_clearable_file_input.html'
#
# Path: demo_and_tests/model_filefields_example/models.py
# class Book(models.Model):
# book_pk = models.AutoField(primary_key=True)
# name = models.CharField(max_length=100, unique=True)
# index = models.FileField(
# upload_to='model_filefields_example.BookIndex/bytes/filename/mimetype',
# blank=True, null=True
# )
# pages = models.FileField(
# upload_to='model_filefields_example.BookPages/bytes/filename/mimetype',
# blank=True, null=True
# )
# cover = models.ImageField(
# upload_to='model_filefields_example.BookCover/bytes/filename/mimetype',
# blank=True, null=True
# )
#
# def get_absolute_url(self):
# return reverse('model_files:book.edit', kwargs={'pk': self.pk})
#
# def save(self, *args, **kwargs):
# delete_file_if_needed(self, 'index')
# delete_file_if_needed(self, 'pages')
# super(Book, self).save(*args, **kwargs)
#
# def delete(self, *args, **kwargs):
# super(Book, self).delete(*args, **kwargs)
# delete_file(self, 'index')
# delete_file(self, 'pages')
#
# def __str__(self):
# return self.name
#
# class SoundDevice(models.Model):
# name = models.CharField(max_length=100)
# instruction_manual = models.FileField(
# upload_to='model_filefields_example.SoundDeviceInstructionManual'
# '/bytes/filename/mimetype',
# blank=True,
# null=True
# )
. Output only the next line. | exclude = [] |
Continue the code snippet: <|code_start|># django
# third party
# project
class BookForm(forms.ModelForm):
class Meta(object):
model = Book
exclude = []
widgets = {
'index': DBClearableFileInput,
'pages': DBClearableFileInput,
'cover': DBClearableFileInput,
}
class BookAdminForm(adminforms.ModelForm):
class Meta(object):
model = Book
exclude = []
widgets = {
'index': DBAdminClearableFileInput,
'pages': DBAdminClearableFileInput,
'cover': DBAdminClearableFileInput,
}
class SoundDeviceForm(forms.ModelForm):
<|code_end|>
. Use current file imports:
from django import forms
from django.contrib.admin.forms import forms as adminforms
from db_file_storage.form_widgets import DBClearableFileInput, \
DBAdminClearableFileInput
from .models import Book, SoundDevice
and context (classes, functions, or code) from other files:
# Path: db_file_storage/form_widgets.py
# class DBClearableFileInput(ClearableFileInput):
# template_name = 'db_file_storage/widgets/clearable_file_input.html'
#
# class DBAdminClearableFileInput(AdminFileWidget):
# template_name = 'db_file_storage/widgets/admin_clearable_file_input.html'
#
# Path: demo_and_tests/model_filefields_example/models.py
# class Book(models.Model):
# book_pk = models.AutoField(primary_key=True)
# name = models.CharField(max_length=100, unique=True)
# index = models.FileField(
# upload_to='model_filefields_example.BookIndex/bytes/filename/mimetype',
# blank=True, null=True
# )
# pages = models.FileField(
# upload_to='model_filefields_example.BookPages/bytes/filename/mimetype',
# blank=True, null=True
# )
# cover = models.ImageField(
# upload_to='model_filefields_example.BookCover/bytes/filename/mimetype',
# blank=True, null=True
# )
#
# def get_absolute_url(self):
# return reverse('model_files:book.edit', kwargs={'pk': self.pk})
#
# def save(self, *args, **kwargs):
# delete_file_if_needed(self, 'index')
# delete_file_if_needed(self, 'pages')
# super(Book, self).save(*args, **kwargs)
#
# def delete(self, *args, **kwargs):
# super(Book, self).delete(*args, **kwargs)
# delete_file(self, 'index')
# delete_file(self, 'pages')
#
# def __str__(self):
# return self.name
#
# class SoundDevice(models.Model):
# name = models.CharField(max_length=100)
# instruction_manual = models.FileField(
# upload_to='model_filefields_example.SoundDeviceInstructionManual'
# '/bytes/filename/mimetype',
# blank=True,
# null=True
# )
. Output only the next line. | class Meta(object): |
Continue the code snippet: <|code_start|># django
# third party
# project
class BookForm(forms.ModelForm):
class Meta(object):
model = Book
exclude = []
widgets = {
'index': DBClearableFileInput,
'pages': DBClearableFileInput,
'cover': DBClearableFileInput,
}
class BookAdminForm(adminforms.ModelForm):
class Meta(object):
model = Book
exclude = []
widgets = {
'index': DBAdminClearableFileInput,
'pages': DBAdminClearableFileInput,
'cover': DBAdminClearableFileInput,
<|code_end|>
. Use current file imports:
from django import forms
from django.contrib.admin.forms import forms as adminforms
from db_file_storage.form_widgets import DBClearableFileInput, \
DBAdminClearableFileInput
from .models import Book, SoundDevice
and context (classes, functions, or code) from other files:
# Path: db_file_storage/form_widgets.py
# class DBClearableFileInput(ClearableFileInput):
# template_name = 'db_file_storage/widgets/clearable_file_input.html'
#
# class DBAdminClearableFileInput(AdminFileWidget):
# template_name = 'db_file_storage/widgets/admin_clearable_file_input.html'
#
# Path: demo_and_tests/model_filefields_example/models.py
# class Book(models.Model):
# book_pk = models.AutoField(primary_key=True)
# name = models.CharField(max_length=100, unique=True)
# index = models.FileField(
# upload_to='model_filefields_example.BookIndex/bytes/filename/mimetype',
# blank=True, null=True
# )
# pages = models.FileField(
# upload_to='model_filefields_example.BookPages/bytes/filename/mimetype',
# blank=True, null=True
# )
# cover = models.ImageField(
# upload_to='model_filefields_example.BookCover/bytes/filename/mimetype',
# blank=True, null=True
# )
#
# def get_absolute_url(self):
# return reverse('model_files:book.edit', kwargs={'pk': self.pk})
#
# def save(self, *args, **kwargs):
# delete_file_if_needed(self, 'index')
# delete_file_if_needed(self, 'pages')
# super(Book, self).save(*args, **kwargs)
#
# def delete(self, *args, **kwargs):
# super(Book, self).delete(*args, **kwargs)
# delete_file(self, 'index')
# delete_file(self, 'pages')
#
# def __str__(self):
# return self.name
#
# class SoundDevice(models.Model):
# name = models.CharField(max_length=100)
# instruction_manual = models.FileField(
# upload_to='model_filefields_example.SoundDeviceInstructionManual'
# '/bytes/filename/mimetype',
# blank=True,
# null=True
# )
. Output only the next line. | } |
Given the following code snippet before the placeholder: <|code_start|># project
app_name = 'form_wizard_example'
urlpatterns = [
url(r'^song_lyrics/$', SongLyricsWizard.as_view(), name='song_lyrics'),
<|code_end|>
, predict the next line using imports from the current file:
from .views import SongLyricsWizard
from db_file_storage.compat import url
and context including class names, function names, and sometimes code from other files:
# Path: demo_and_tests/form_wizard_example/views.py
# class SongLyricsWizard(SessionWizardView):
# file_storage = FixedModelDatabaseFileStorage(
# model_class_path='form_wizard_example.FormWizardTempFile',
# content_field='content',
# filename_field='name',
# mimetype_field='mimetype'
# )
# form_list = [SongLyricsForm1, SongLyricsForm2, SongLyricsForm3]
# template_name = 'form_wizard_example/form.html'
#
# def done(self, form_list, **kwargs):
# if sys.version_info.major == 3: # python3
# form_list = list(form_list)
# song = form_list[0].cleaned_data['song']
# artist = form_list[0].cleaned_data['artist']
# lyrics = form_list[1].cleaned_data['attachment'].read()
# sender = form_list[2].cleaned_data['sender']
#
# context = {'song': song, 'artist': artist,
# 'lyrics': lyrics, 'sender': sender}
# return render(self.request, 'form_wizard_example/done.html', context)
#
# Path: db_file_storage/compat.py
. Output only the next line. | ] |
Based on the snippet: <|code_start|> '0-song': 'Californication',
'0-artist': 'Red Hot Chili Peppers'
}
response = self.client.post(url, form_data)
self.assertEqual(response.status_code, 200)
# second step - file
path = os.path.join(settings.TEST_FILES_DIR, 'californication.txt')
with open(path, 'rb') as lyric_file:
form_data = {
'song_lyrics_wizard-current_step': '1',
'1-attachment': lyric_file
}
response = self.client.post(url, form_data)
self.assertEqual(response.status_code, 200)
# Creates a file until the wizard is complete
self.assertEqual(FormWizardTempFile.objects.count(), 1)
# third step - song and artist
form_data = {
'song_lyrics_wizard-current_step': '2',
'2-sender': 'Victor Silva'
}
response = self.client.post(url, form_data)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.context['song'], 'Californication')
self.assertEqual(response.context['artist'], 'Red Hot Chili Peppers')
self.assertEqual(response.context['sender'], 'Victor Silva')
<|code_end|>
, predict the immediate next line with the help of imports:
import os
from django.conf import settings
from django.test import TestCase
from db_file_storage.storage import FixedModelDatabaseFileStorage
from db_file_storage.compat import reverse
from form_wizard_example.models import FormWizardTempFile
and context (classes, functions, sometimes code) from other files:
# Path: db_file_storage/storage.py
# class FixedModelDatabaseFileStorage(DatabaseFileStorage):
# """File storage system that saves files in the database.
#
# Intended for use without Models' FileFields, e.g. with Form Wizards.
# Uses a fixed Model to store the all the saved files.
# """
#
# def __init__(self, *args, **kwargs):
# try:
# self.model_class_path = kwargs.pop('model_class_path')
# self.content_field = kwargs.pop('content_field')
# self.filename_field = kwargs.pop('filename_field')
# self.mimetype_field = kwargs.pop('mimetype_field')
# except KeyError:
# raise KeyError(
# "keyword args 'model_class_path', 'content_field', "
# "'filename_field' and 'mimetype_field' are required."
# )
# super(FixedModelDatabaseFileStorage, self).__init__(*args, **kwargs)
#
# def _get_storage_attributes(self, name):
# return {
# 'model_class_path': self.model_class_path,
# 'content_field': self.content_field,
# 'filename_field': self.filename_field,
# 'mimetype_field': self.mimetype_field,
# 'filename': name,
# }
#
# Path: db_file_storage/compat.py
. Output only the next line. | some_lines = ( |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
# python
from __future__ import unicode_literals
# django
# third party
# project
class FormWizardTestCase(TestCase):
def test_fixed_model_storage_requires_fixed_model_fields(self):
with self.assertRaises(KeyError):
FixedModelDatabaseFileStorage()
def test_wizard_view(self):
url = reverse('form_wizard:song_lyrics')
# Begins with no files
self.assertEqual(FormWizardTempFile.objects.count(), 0)
# first step - song and artist
form_data = {
<|code_end|>
. Use current file imports:
import os
from django.conf import settings
from django.test import TestCase
from db_file_storage.storage import FixedModelDatabaseFileStorage
from db_file_storage.compat import reverse
from form_wizard_example.models import FormWizardTempFile
and context (classes, functions, or code) from other files:
# Path: db_file_storage/storage.py
# class FixedModelDatabaseFileStorage(DatabaseFileStorage):
# """File storage system that saves files in the database.
#
# Intended for use without Models' FileFields, e.g. with Form Wizards.
# Uses a fixed Model to store the all the saved files.
# """
#
# def __init__(self, *args, **kwargs):
# try:
# self.model_class_path = kwargs.pop('model_class_path')
# self.content_field = kwargs.pop('content_field')
# self.filename_field = kwargs.pop('filename_field')
# self.mimetype_field = kwargs.pop('mimetype_field')
# except KeyError:
# raise KeyError(
# "keyword args 'model_class_path', 'content_field', "
# "'filename_field' and 'mimetype_field' are required."
# )
# super(FixedModelDatabaseFileStorage, self).__init__(*args, **kwargs)
#
# def _get_storage_attributes(self, name):
# return {
# 'model_class_path': self.model_class_path,
# 'content_field': self.content_field,
# 'filename_field': self.filename_field,
# 'mimetype_field': self.mimetype_field,
# 'filename': name,
# }
#
# Path: db_file_storage/compat.py
. Output only the next line. | 'song_lyrics_wizard-current_step': '0', |
Continue the code snippet: <|code_start|># django imports
# project imports
app_name = 'model_filefields_example'
urlpatterns = [
url(
r'^$',
ListView.as_view(
queryset=Book.objects.all(),
template_name='model_filefields_example/book_list.html'
),
name='book.list'
),
url(
r'^books/add/$',
<|code_end|>
. Use current file imports:
from django.views.generic import ListView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from .forms import BookForm, SoundDeviceForm
from .models import Book, SoundDevice
from db_file_storage.compat import url, reverse_lazy
from db_file_storage import views as db_file_storage_views
and context (classes, functions, or code) from other files:
# Path: demo_and_tests/model_filefields_example/forms.py
# class BookForm(forms.ModelForm):
# class Meta(object):
# model = Book
# exclude = []
# widgets = {
# 'index': DBClearableFileInput,
# 'pages': DBClearableFileInput,
# 'cover': DBClearableFileInput,
# }
#
# class SoundDeviceForm(forms.ModelForm):
# class Meta(object):
# model = SoundDevice
# exclude = []
#
# Path: demo_and_tests/model_filefields_example/models.py
# class Book(models.Model):
# book_pk = models.AutoField(primary_key=True)
# name = models.CharField(max_length=100, unique=True)
# index = models.FileField(
# upload_to='model_filefields_example.BookIndex/bytes/filename/mimetype',
# blank=True, null=True
# )
# pages = models.FileField(
# upload_to='model_filefields_example.BookPages/bytes/filename/mimetype',
# blank=True, null=True
# )
# cover = models.ImageField(
# upload_to='model_filefields_example.BookCover/bytes/filename/mimetype',
# blank=True, null=True
# )
#
# def get_absolute_url(self):
# return reverse('model_files:book.edit', kwargs={'pk': self.pk})
#
# def save(self, *args, **kwargs):
# delete_file_if_needed(self, 'index')
# delete_file_if_needed(self, 'pages')
# super(Book, self).save(*args, **kwargs)
#
# def delete(self, *args, **kwargs):
# super(Book, self).delete(*args, **kwargs)
# delete_file(self, 'index')
# delete_file(self, 'pages')
#
# def __str__(self):
# return self.name
#
# class SoundDevice(models.Model):
# name = models.CharField(max_length=100)
# instruction_manual = models.FileField(
# upload_to='model_filefields_example.SoundDeviceInstructionManual'
# '/bytes/filename/mimetype',
# blank=True,
# null=True
# )
#
# Path: db_file_storage/compat.py
#
# Path: db_file_storage/views.py
# def get_file(request, add_attachment_headers, extra_headers=None):
. Output only the next line. | CreateView.as_view( |
Given the code snippet: <|code_start|># django imports
# project imports
app_name = 'model_filefields_example'
urlpatterns = [
url(
r'^$',
ListView.as_view(
queryset=Book.objects.all(),
<|code_end|>
, generate the next line using the imports in this file:
from django.views.generic import ListView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from .forms import BookForm, SoundDeviceForm
from .models import Book, SoundDevice
from db_file_storage.compat import url, reverse_lazy
from db_file_storage import views as db_file_storage_views
and context (functions, classes, or occasionally code) from other files:
# Path: demo_and_tests/model_filefields_example/forms.py
# class BookForm(forms.ModelForm):
# class Meta(object):
# model = Book
# exclude = []
# widgets = {
# 'index': DBClearableFileInput,
# 'pages': DBClearableFileInput,
# 'cover': DBClearableFileInput,
# }
#
# class SoundDeviceForm(forms.ModelForm):
# class Meta(object):
# model = SoundDevice
# exclude = []
#
# Path: demo_and_tests/model_filefields_example/models.py
# class Book(models.Model):
# book_pk = models.AutoField(primary_key=True)
# name = models.CharField(max_length=100, unique=True)
# index = models.FileField(
# upload_to='model_filefields_example.BookIndex/bytes/filename/mimetype',
# blank=True, null=True
# )
# pages = models.FileField(
# upload_to='model_filefields_example.BookPages/bytes/filename/mimetype',
# blank=True, null=True
# )
# cover = models.ImageField(
# upload_to='model_filefields_example.BookCover/bytes/filename/mimetype',
# blank=True, null=True
# )
#
# def get_absolute_url(self):
# return reverse('model_files:book.edit', kwargs={'pk': self.pk})
#
# def save(self, *args, **kwargs):
# delete_file_if_needed(self, 'index')
# delete_file_if_needed(self, 'pages')
# super(Book, self).save(*args, **kwargs)
#
# def delete(self, *args, **kwargs):
# super(Book, self).delete(*args, **kwargs)
# delete_file(self, 'index')
# delete_file(self, 'pages')
#
# def __str__(self):
# return self.name
#
# class SoundDevice(models.Model):
# name = models.CharField(max_length=100)
# instruction_manual = models.FileField(
# upload_to='model_filefields_example.SoundDeviceInstructionManual'
# '/bytes/filename/mimetype',
# blank=True,
# null=True
# )
#
# Path: db_file_storage/compat.py
#
# Path: db_file_storage/views.py
# def get_file(request, add_attachment_headers, extra_headers=None):
. Output only the next line. | template_name='model_filefields_example/book_list.html' |
Given the code snippet: <|code_start|># django imports
# project imports
app_name = 'model_filefields_example'
urlpatterns = [
url(
r'^$',
ListView.as_view(
queryset=Book.objects.all(),
template_name='model_filefields_example/book_list.html'
),
<|code_end|>
, generate the next line using the imports in this file:
from django.views.generic import ListView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from .forms import BookForm, SoundDeviceForm
from .models import Book, SoundDevice
from db_file_storage.compat import url, reverse_lazy
from db_file_storage import views as db_file_storage_views
and context (functions, classes, or occasionally code) from other files:
# Path: demo_and_tests/model_filefields_example/forms.py
# class BookForm(forms.ModelForm):
# class Meta(object):
# model = Book
# exclude = []
# widgets = {
# 'index': DBClearableFileInput,
# 'pages': DBClearableFileInput,
# 'cover': DBClearableFileInput,
# }
#
# class SoundDeviceForm(forms.ModelForm):
# class Meta(object):
# model = SoundDevice
# exclude = []
#
# Path: demo_and_tests/model_filefields_example/models.py
# class Book(models.Model):
# book_pk = models.AutoField(primary_key=True)
# name = models.CharField(max_length=100, unique=True)
# index = models.FileField(
# upload_to='model_filefields_example.BookIndex/bytes/filename/mimetype',
# blank=True, null=True
# )
# pages = models.FileField(
# upload_to='model_filefields_example.BookPages/bytes/filename/mimetype',
# blank=True, null=True
# )
# cover = models.ImageField(
# upload_to='model_filefields_example.BookCover/bytes/filename/mimetype',
# blank=True, null=True
# )
#
# def get_absolute_url(self):
# return reverse('model_files:book.edit', kwargs={'pk': self.pk})
#
# def save(self, *args, **kwargs):
# delete_file_if_needed(self, 'index')
# delete_file_if_needed(self, 'pages')
# super(Book, self).save(*args, **kwargs)
#
# def delete(self, *args, **kwargs):
# super(Book, self).delete(*args, **kwargs)
# delete_file(self, 'index')
# delete_file(self, 'pages')
#
# def __str__(self):
# return self.name
#
# class SoundDevice(models.Model):
# name = models.CharField(max_length=100)
# instruction_manual = models.FileField(
# upload_to='model_filefields_example.SoundDeviceInstructionManual'
# '/bytes/filename/mimetype',
# blank=True,
# null=True
# )
#
# Path: db_file_storage/compat.py
#
# Path: db_file_storage/views.py
# def get_file(request, add_attachment_headers, extra_headers=None):
. Output only the next line. | name='book.list' |
Given the code snippet: <|code_start|># django imports
# project imports
app_name = 'model_filefields_example'
urlpatterns = [
url(
r'^$',
ListView.as_view(
queryset=Book.objects.all(),
template_name='model_filefields_example/book_list.html'
),
name='book.list'
),
url(
r'^books/add/$',
<|code_end|>
, generate the next line using the imports in this file:
from django.views.generic import ListView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from .forms import BookForm, SoundDeviceForm
from .models import Book, SoundDevice
from db_file_storage.compat import url, reverse_lazy
from db_file_storage import views as db_file_storage_views
and context (functions, classes, or occasionally code) from other files:
# Path: demo_and_tests/model_filefields_example/forms.py
# class BookForm(forms.ModelForm):
# class Meta(object):
# model = Book
# exclude = []
# widgets = {
# 'index': DBClearableFileInput,
# 'pages': DBClearableFileInput,
# 'cover': DBClearableFileInput,
# }
#
# class SoundDeviceForm(forms.ModelForm):
# class Meta(object):
# model = SoundDevice
# exclude = []
#
# Path: demo_and_tests/model_filefields_example/models.py
# class Book(models.Model):
# book_pk = models.AutoField(primary_key=True)
# name = models.CharField(max_length=100, unique=True)
# index = models.FileField(
# upload_to='model_filefields_example.BookIndex/bytes/filename/mimetype',
# blank=True, null=True
# )
# pages = models.FileField(
# upload_to='model_filefields_example.BookPages/bytes/filename/mimetype',
# blank=True, null=True
# )
# cover = models.ImageField(
# upload_to='model_filefields_example.BookCover/bytes/filename/mimetype',
# blank=True, null=True
# )
#
# def get_absolute_url(self):
# return reverse('model_files:book.edit', kwargs={'pk': self.pk})
#
# def save(self, *args, **kwargs):
# delete_file_if_needed(self, 'index')
# delete_file_if_needed(self, 'pages')
# super(Book, self).save(*args, **kwargs)
#
# def delete(self, *args, **kwargs):
# super(Book, self).delete(*args, **kwargs)
# delete_file(self, 'index')
# delete_file(self, 'pages')
#
# def __str__(self):
# return self.name
#
# class SoundDevice(models.Model):
# name = models.CharField(max_length=100)
# instruction_manual = models.FileField(
# upload_to='model_filefields_example.SoundDeviceInstructionManual'
# '/bytes/filename/mimetype',
# blank=True,
# null=True
# )
#
# Path: db_file_storage/compat.py
#
# Path: db_file_storage/views.py
# def get_file(request, add_attachment_headers, extra_headers=None):
. Output only the next line. | CreateView.as_view( |
Predict the next line after this snippet: <|code_start|># django imports
# project imports
app_name = 'model_filefields_example'
urlpatterns = [
url(
r'^$',
ListView.as_view(
queryset=Book.objects.all(),
<|code_end|>
using the current file's imports:
from django.views.generic import ListView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from .forms import BookForm, SoundDeviceForm
from .models import Book, SoundDevice
from db_file_storage.compat import url, reverse_lazy
from db_file_storage import views as db_file_storage_views
and any relevant context from other files:
# Path: demo_and_tests/model_filefields_example/forms.py
# class BookForm(forms.ModelForm):
# class Meta(object):
# model = Book
# exclude = []
# widgets = {
# 'index': DBClearableFileInput,
# 'pages': DBClearableFileInput,
# 'cover': DBClearableFileInput,
# }
#
# class SoundDeviceForm(forms.ModelForm):
# class Meta(object):
# model = SoundDevice
# exclude = []
#
# Path: demo_and_tests/model_filefields_example/models.py
# class Book(models.Model):
# book_pk = models.AutoField(primary_key=True)
# name = models.CharField(max_length=100, unique=True)
# index = models.FileField(
# upload_to='model_filefields_example.BookIndex/bytes/filename/mimetype',
# blank=True, null=True
# )
# pages = models.FileField(
# upload_to='model_filefields_example.BookPages/bytes/filename/mimetype',
# blank=True, null=True
# )
# cover = models.ImageField(
# upload_to='model_filefields_example.BookCover/bytes/filename/mimetype',
# blank=True, null=True
# )
#
# def get_absolute_url(self):
# return reverse('model_files:book.edit', kwargs={'pk': self.pk})
#
# def save(self, *args, **kwargs):
# delete_file_if_needed(self, 'index')
# delete_file_if_needed(self, 'pages')
# super(Book, self).save(*args, **kwargs)
#
# def delete(self, *args, **kwargs):
# super(Book, self).delete(*args, **kwargs)
# delete_file(self, 'index')
# delete_file(self, 'pages')
#
# def __str__(self):
# return self.name
#
# class SoundDevice(models.Model):
# name = models.CharField(max_length=100)
# instruction_manual = models.FileField(
# upload_to='model_filefields_example.SoundDeviceInstructionManual'
# '/bytes/filename/mimetype',
# blank=True,
# null=True
# )
#
# Path: db_file_storage/compat.py
#
# Path: db_file_storage/views.py
# def get_file(request, add_attachment_headers, extra_headers=None):
. Output only the next line. | template_name='model_filefields_example/book_list.html' |
Given snippet: <|code_start|> CreateView.as_view(
model=Book,
form_class=BookForm,
template_name='model_filefields_example/book_form.html',
success_url=reverse_lazy('model_files:book.list')
),
name='book.add'
),
url(
r'^books/edit/(?P<pk>\d+)/$',
UpdateView.as_view(
model=Book,
form_class=BookForm,
template_name='model_filefields_example/book_form.html',
success_url=reverse_lazy('model_files:book.list')
),
name='book.edit'
),
url(
r'^books/delete/(?P<pk>\d+)/$',
DeleteView.as_view(
model=Book,
success_url=reverse_lazy('model_files:book.list')
),
name='book.delete'
),
url(
r'^book-cover-download/',
db_file_storage_views.get_file,
{
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.views.generic import ListView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from .forms import BookForm, SoundDeviceForm
from .models import Book, SoundDevice
from db_file_storage.compat import url, reverse_lazy
from db_file_storage import views as db_file_storage_views
and context:
# Path: demo_and_tests/model_filefields_example/forms.py
# class BookForm(forms.ModelForm):
# class Meta(object):
# model = Book
# exclude = []
# widgets = {
# 'index': DBClearableFileInput,
# 'pages': DBClearableFileInput,
# 'cover': DBClearableFileInput,
# }
#
# class SoundDeviceForm(forms.ModelForm):
# class Meta(object):
# model = SoundDevice
# exclude = []
#
# Path: demo_and_tests/model_filefields_example/models.py
# class Book(models.Model):
# book_pk = models.AutoField(primary_key=True)
# name = models.CharField(max_length=100, unique=True)
# index = models.FileField(
# upload_to='model_filefields_example.BookIndex/bytes/filename/mimetype',
# blank=True, null=True
# )
# pages = models.FileField(
# upload_to='model_filefields_example.BookPages/bytes/filename/mimetype',
# blank=True, null=True
# )
# cover = models.ImageField(
# upload_to='model_filefields_example.BookCover/bytes/filename/mimetype',
# blank=True, null=True
# )
#
# def get_absolute_url(self):
# return reverse('model_files:book.edit', kwargs={'pk': self.pk})
#
# def save(self, *args, **kwargs):
# delete_file_if_needed(self, 'index')
# delete_file_if_needed(self, 'pages')
# super(Book, self).save(*args, **kwargs)
#
# def delete(self, *args, **kwargs):
# super(Book, self).delete(*args, **kwargs)
# delete_file(self, 'index')
# delete_file(self, 'pages')
#
# def __str__(self):
# return self.name
#
# class SoundDevice(models.Model):
# name = models.CharField(max_length=100)
# instruction_manual = models.FileField(
# upload_to='model_filefields_example.SoundDeviceInstructionManual'
# '/bytes/filename/mimetype',
# blank=True,
# null=True
# )
#
# Path: db_file_storage/compat.py
#
# Path: db_file_storage/views.py
# def get_file(request, add_attachment_headers, extra_headers=None):
which might include code, classes, or functions. Output only the next line. | 'add_attachment_headers': True, |
Here is a snippet: <|code_start|> hbox.addStretch()
self.setLayout(hbox)
self.setFrameStyle(QFrame.Panel | QFrame.Raised)
self.setLineWidth(2)
self.setStyleSheet('QFrame{background-color: #999; border-radius: 10px;}')
class CheckableComboBox(QtGui.QComboBox):
def __init__(self):
super(CheckableComboBox, self).__init__()
self.view().pressed.connect(self.handleItemPressed)
self.setModel(QtGui.QStandardItemModel(self))
def handleItemPressed(self, index):
item = self.model().itemFromIndex(index)
if item.checkState() == QtCore.Qt.Checked:
item.setCheckState(QtCore.Qt.Unchecked)
else:
item.setCheckState(QtCore.Qt.Checked)
class MyTableWidget(QTableWidget):
def __init__(self, data=None, *args):
QTableWidget.__init__(self, *args)
self.data = data
self.update(self.data)
def setmydata(self):
horHeaders = self.data.keys()
for n, key in enumerate(sorted(horHeaders)):
for m, item in enumerate(self.data[key]):
<|code_end|>
. Write the next line using the current file imports:
import os
import numpy as np
import qtutil
from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from . import file_io
from .mygraphicsview import MyGraphicsView
and context from other files:
# Path: src/plugins/util/mygraphicsview.py
# class MyGraphicsView(pg.GraphicsView):
# def __init__(self, project, parent=None, image_view_on=None):
# super(MyGraphicsView, self).__init__(parent)
# self.image_view_on = image_view_on
# self.unit_per_pixel = 'units'
#
# self.project = project
# self.shape = 0, 0
#
# self.setup_ui()
#
# self.update()
#
# def setup_ui(self):
# self.setMinimumSize(200, 200)
# l = QGraphicsGridLayout()
#
# self.centralWidget.setLayout(l)
# l.setHorizontalSpacing(0)
# l.setVerticalSpacing(0)
# self.vb = MultiRoiViewBox(lockAspect=True, enableMenu=True)
#
# # if self.image_view_on:
# # self.vb = pg.ImageView()
# # else:
# # self.vb = MultiRoiViewBox(lockAspect=True, enableMenu=True)
# # todo: hovering for pyqtgraph
# #self.vb.hovering.connect(self.vbc_hovering)
# self.vb.enableAutoRange()
#
# # self.the_label = pg.LabelItem()
# # l.addItem(self.the_label, 1, 0)
#
# l.addItem(self.vb, 0, 1)
# self.xScale = pg.AxisItem(orientation='bottom', linkView=self.vb)
# self.xScale.setLabel(text="<span style='color: #ff0000; font-weight: bold'>X</span>"
# "<i>Width</i>", units=self.unit_per_pixel)
# l.addItem(self.xScale, 1, 1)
#
# self.yScale = pg.AxisItem(orientation='left', linkView=self.vb)
# self.yScale.setLabel(text="<span style='color: #ff0000; font-weight: bold'>Y</span>"
# "<i>Height</i>", units=self.unit_per_pixel)
# l.addItem(self.yScale, 0, 0)
#
# self.centralWidget.setLayout(l)
#
# def show(self, frame, min=None, max=None):
# self.shape = frame.shape
# self.vb.showImage(frame, min, max)
# self.update()
#
# def _update_rect(self):
# self.xScale.setLabel(text="<span style='color: #ff0000; font-weight: bold'>X</span>"
# "<i>Width</i>", units=self.unit_per_pixel)
# self.yScale.setLabel(text="<span style='color: #ff0000; font-weight: bold'>Y</span>"
# "<i>Height</i>", units=self.unit_per_pixel)
# w, h = self.shape[0], self.shape[1]
# if not (not self.project):
# ox, oy = self.project['origin']
# unit_per_pixel = self.project['unit_per_pixel']
#
# x = -ox *unit_per_pixel
# y = -oy * unit_per_pixel
# w = w * unit_per_pixel
# h = h * unit_per_pixel
#
# self.vb.update_rect(x, y, w, h)
#
# def update(self):
# self._update_rect()
#
# def vbc_hovering(self, x, y):
# #todo: hovering for pyqtgraph
# x_origin, y_origin = self.project['origin']
# unit_per_pixel = self.project['unit_per_pixel']
# x = round(x * unit_per_pixel, 2)
# y = round(y * unit_per_pixel, 2)
#
# try:
# self.the_label.setText('X:{}, '.format(x) + 'Y:{}'.format(y))
# except:
# self.the_label.setText('X:-, Y:-')
, which may include functions, classes, or code. Output only the next line. | newitem = QTableWidgetItem(str(item)) |
Given the code snippet: <|code_start|> if types:
ui_list.model().clear()
for typ in types:
for f in project.files:
item = QStandardItem(f['name'])
item.setDropEnabled(False)
if f['type'] != typ:
continue
if not last_manips_to_display or 'All' in last_manips_to_display:
ui_list.model().appendRow(QStandardItem(item))
elif f['manipulations'] != []:
if ast.literal_eval(f['manipulations'])[-1] in last_manips_to_display:
ui_list.model().appendRow(item)
if len(indices) == 0:
return
if len(indices) > 1:
ui_list.setCurrentIndex(ui_list.model().index(indices[0], 0))
theQIndexObjects = [ui_list.model().createIndex(rowIndex, 0) for rowIndex in
indices]
for Qindex in theQIndexObjects:
ui_list.selectionModel().select(Qindex, QItemSelectionModel.Select)
elif len(indices) == 1:
ui_list.setCurrentIndex(ui_list.model().index(indices[0], 0))
def refresh_video_list_via_combo_box(widget, list_display_type, trigger_item=None):
if trigger_item != 0:
widget.toolbutton.model().item(0, 0).setCheckState(Qt.Unchecked)
last_manips_to_display = []
<|code_end|>
, generate the next line using the imports in this file:
import ast
import functools
import os
import pickle
import uuid
import qtutil
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from . import constants
from . import file_io
from .custom_qt_items import CheckableComboBox, PlayerDialog
from .file_io import load_reference_frame
and context (functions, classes, or occasionally code) from other files:
# Path: src/plugins/util/custom_qt_items.py
# class CheckableComboBox(QtGui.QComboBox):
# def __init__(self):
# super(CheckableComboBox, self).__init__()
# self.view().pressed.connect(self.handleItemPressed)
# self.setModel(QtGui.QStandardItemModel(self))
#
# def handleItemPressed(self, index):
# item = self.model().itemFromIndex(index)
# if item.checkState() == QtCore.Qt.Checked:
# item.setCheckState(QtCore.Qt.Unchecked)
# else:
# item.setCheckState(QtCore.Qt.Checked)
#
# class PlayerDialog(QDialog):
# def __init__(self, project, filename, parent=None, scaling=True):
# super(PlayerDialog, self).__init__(parent)
# self.project = project
# self.setup_ui()
# self.setWindowTitle(os.path.basename(filename))
#
# self.scale = scaling
# self.fp = np.load(filename, mmap_mode='r')
# if isinstance(scaling, bool) and scaling:
# self.global_min = np.min(self.fp)
# self.global_max = np.max(self.fp)
# if isinstance(scaling, tuple):
# self.global_min = scaling[0]
# self.global_max = scaling[1]
# self.slider.setMaximum(len(self.fp)-1)
# self.show_frame(0)
#
# def show_frame(self, frame_num):
# frame = self.fp[frame_num]
# self.label_frame.setText(str(frame_num) + ' / ' + str(len(self.fp)-1))
# if hasattr(self, 'global_min') and hasattr(self, 'global_max'):
# self.view.show(frame, self.global_min, self.global_max)
# else:
# self.view.show(frame)
#
# def setup_ui(self):
# vbox = QVBoxLayout()
# self.view = MyGraphicsView(self.project)
# vbox.addWidget(self.view)
# hbox = QHBoxLayout()
# self.slider = QSlider(Qt.Horizontal)
# self.slider.valueChanged.connect(self.slider_moved)
# hbox.addWidget(self.slider)
# self.label_frame = QLabel('- / -')
# hbox.addWidget(self.label_frame)
# vbox.addLayout(hbox)
# self.setLayout(vbox)
#
# def slider_moved(self, value):
# self.show_frame(value)
#
# Path: src/plugins/util/file_io.py
# def load_reference_frame(filename, offset=0):
# if filename.endswith('.npy'):
# frame = load_reference_frame_npy(filename, offset)
# else:
# raise UnknownFileFormatError()
# return frame
. Output only the next line. | for i in range(widget.toolbutton.count()): |
Given the following code snippet before the placeholder: <|code_start|># def refresh_all_list(project, video_list, indices, last_manips_to_display=['All']):
# video_list.model().clear()
# for f in project.files:
# item = QStandardItem(f['name'])
# item.setDropEnabled(False)
# if f['type'] != 'ref_frame':
# continue
# video_list.model().appendRow(item)
# for f in project.files:
# item = QStandardItem(f['name'])
# item.setDropEnabled(False)
# if f['type'] != 'video':
# continue
# if 'All' in last_manips_to_display:
# video_list.model().appendRow(item)
# elif f['manipulations'] != []:
# if ast.literal_eval(f['manipulations'])[-1] in last_manips_to_display:
# video_list.model().appendRow(item)
#
# if len(indices) > 1:
# theQIndexObjects = [video_list.model().createIndex(rowIndex, 0) for rowIndex in
# indices]
# for Qindex in theQIndexObjects:
# video_list.selectionModel().select(Qindex, QItemSelectionModel.Select)
# else:
# video_list.setCurrentIndex(video_list.model().index(indices[0], 0))
def refresh_list(project, ui_list, indices, types=None, last_manips_to_display=None):
if types:
<|code_end|>
, predict the next line using imports from the current file:
import ast
import functools
import os
import pickle
import uuid
import qtutil
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from . import constants
from . import file_io
from .custom_qt_items import CheckableComboBox, PlayerDialog
from .file_io import load_reference_frame
and context including class names, function names, and sometimes code from other files:
# Path: src/plugins/util/custom_qt_items.py
# class CheckableComboBox(QtGui.QComboBox):
# def __init__(self):
# super(CheckableComboBox, self).__init__()
# self.view().pressed.connect(self.handleItemPressed)
# self.setModel(QtGui.QStandardItemModel(self))
#
# def handleItemPressed(self, index):
# item = self.model().itemFromIndex(index)
# if item.checkState() == QtCore.Qt.Checked:
# item.setCheckState(QtCore.Qt.Unchecked)
# else:
# item.setCheckState(QtCore.Qt.Checked)
#
# class PlayerDialog(QDialog):
# def __init__(self, project, filename, parent=None, scaling=True):
# super(PlayerDialog, self).__init__(parent)
# self.project = project
# self.setup_ui()
# self.setWindowTitle(os.path.basename(filename))
#
# self.scale = scaling
# self.fp = np.load(filename, mmap_mode='r')
# if isinstance(scaling, bool) and scaling:
# self.global_min = np.min(self.fp)
# self.global_max = np.max(self.fp)
# if isinstance(scaling, tuple):
# self.global_min = scaling[0]
# self.global_max = scaling[1]
# self.slider.setMaximum(len(self.fp)-1)
# self.show_frame(0)
#
# def show_frame(self, frame_num):
# frame = self.fp[frame_num]
# self.label_frame.setText(str(frame_num) + ' / ' + str(len(self.fp)-1))
# if hasattr(self, 'global_min') and hasattr(self, 'global_max'):
# self.view.show(frame, self.global_min, self.global_max)
# else:
# self.view.show(frame)
#
# def setup_ui(self):
# vbox = QVBoxLayout()
# self.view = MyGraphicsView(self.project)
# vbox.addWidget(self.view)
# hbox = QHBoxLayout()
# self.slider = QSlider(Qt.Horizontal)
# self.slider.valueChanged.connect(self.slider_moved)
# hbox.addWidget(self.slider)
# self.label_frame = QLabel('- / -')
# hbox.addWidget(self.label_frame)
# vbox.addLayout(hbox)
# self.setLayout(vbox)
#
# def slider_moved(self, value):
# self.show_frame(value)
#
# Path: src/plugins/util/file_io.py
# def load_reference_frame(filename, offset=0):
# if filename.endswith('.npy'):
# frame = load_reference_frame_npy(filename, offset)
# else:
# raise UnknownFileFormatError()
# return frame
. Output only the next line. | ui_list.model().clear() |
Predict the next line after this snippet: <|code_start|> # + '.npy')
# widget.selected_videos = [x for x in widget.selected_videos if x != vidpath]
widget.selected_videos = []
for index in widget.video_list.selectedIndexes():
vidpath = str(os.path.normpath(os.path.join(widget.project.path, index.data(Qt.DisplayRole)) + '.npy'))
if vidpath not in widget.selected_videos and vidpath != 'None':
widget.selected_videos = widget.selected_videos + [vidpath]
widget.shown_video_path = str(os.path.normpath(os.path.join(widget.project.path,
widget.video_list.currentIndex().data(Qt.DisplayRole))
+ '.npy'))
frame = load_reference_frame(widget.shown_video_path)
widget.view.show(frame)
def video_triggered(widget, index, scaling=False):
filename = str(os.path.join(widget.project.path, index.data(Qt.DisplayRole)) + '.npy')
dialog = PlayerDialog(widget.project, filename, widget, scaling)
dialog.show()
# widget.open_dialogs.append(dialog)
def update_plugin_params(widget, key, val):
widget.params[key] = val
widget.project.pipeline[widget.plugin_position] = widget.params
widget.project.save()
def save_dock_window_to_project(widget, window_type, pickle_path):
widget.project.files.append({
'path': pickle_path,
'type': window_type,
'name': os.path.basename(pickle_path)
<|code_end|>
using the current file's imports:
import ast
import functools
import os
import pickle
import uuid
import qtutil
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from . import constants
from . import file_io
from .custom_qt_items import CheckableComboBox, PlayerDialog
from .file_io import load_reference_frame
and any relevant context from other files:
# Path: src/plugins/util/custom_qt_items.py
# class CheckableComboBox(QtGui.QComboBox):
# def __init__(self):
# super(CheckableComboBox, self).__init__()
# self.view().pressed.connect(self.handleItemPressed)
# self.setModel(QtGui.QStandardItemModel(self))
#
# def handleItemPressed(self, index):
# item = self.model().itemFromIndex(index)
# if item.checkState() == QtCore.Qt.Checked:
# item.setCheckState(QtCore.Qt.Unchecked)
# else:
# item.setCheckState(QtCore.Qt.Checked)
#
# class PlayerDialog(QDialog):
# def __init__(self, project, filename, parent=None, scaling=True):
# super(PlayerDialog, self).__init__(parent)
# self.project = project
# self.setup_ui()
# self.setWindowTitle(os.path.basename(filename))
#
# self.scale = scaling
# self.fp = np.load(filename, mmap_mode='r')
# if isinstance(scaling, bool) and scaling:
# self.global_min = np.min(self.fp)
# self.global_max = np.max(self.fp)
# if isinstance(scaling, tuple):
# self.global_min = scaling[0]
# self.global_max = scaling[1]
# self.slider.setMaximum(len(self.fp)-1)
# self.show_frame(0)
#
# def show_frame(self, frame_num):
# frame = self.fp[frame_num]
# self.label_frame.setText(str(frame_num) + ' / ' + str(len(self.fp)-1))
# if hasattr(self, 'global_min') and hasattr(self, 'global_max'):
# self.view.show(frame, self.global_min, self.global_max)
# else:
# self.view.show(frame)
#
# def setup_ui(self):
# vbox = QVBoxLayout()
# self.view = MyGraphicsView(self.project)
# vbox.addWidget(self.view)
# hbox = QHBoxLayout()
# self.slider = QSlider(Qt.Horizontal)
# self.slider.valueChanged.connect(self.slider_moved)
# hbox.addWidget(self.slider)
# self.label_frame = QLabel('- / -')
# hbox.addWidget(self.label_frame)
# vbox.addLayout(hbox)
# self.setLayout(vbox)
#
# def slider_moved(self, value):
# self.show_frame(value)
#
# Path: src/plugins/util/file_io.py
# def load_reference_frame(filename, offset=0):
# if filename.endswith('.npy'):
# frame = load_reference_frame_npy(filename, offset)
# else:
# raise UnknownFileFormatError()
# return frame
. Output only the next line. | }) |
Continue the code snippet: <|code_start|> required to allow ROIs to be drawn over the top of each other """
def __init__(self, radius, typ=None, pen=(200, 200, 220), parent=None, deletable=False):
pgROI.Handle.__init__(self,radius, typ, pen, parent, deletable)
self.setSelectable(True)
def setSelectable(self,isActive):
self.isActive = isActive
def raiseContextMenu(self, ev):
menu = self.getMenu()
## Make sure it is still ok to remove this handle
removeAllowed = all([r.checkRemoveHandle(self) for r in self.rois])
self.removeAction.setEnabled(removeAllowed)
pos = ev.screenPos()
menu.popup(QtCore.QPoint(pos.x(), pos.y()))
def hoverEvent(self, ev):
# Ignore events if handle is not active
if not self.isActive: return
hover = False
if not ev.isExit():
if ev.acceptDrags(QtCore.Qt.LeftButton):
hover=True
for btn in [QtCore.Qt.LeftButton, QtCore.Qt.RightButton, QtCore.Qt.MidButton]:
if int(self.acceptedMouseButtons() & btn) > 0 and ev.acceptClicks(btn):
hover=True
if hover:
self.currentPen = fn.mkPen(255, 255,0)
<|code_end|>
. Use current file imports:
import uuid
import numpy as np
import pyqtgraph.functions as fn
import pyqtgraph.graphicsItems.ROI as pgROI
from pyqtgraph.Point import Point
from pyqtgraph.Qt import QtCore, QtGui, USE_PYSIDE
from .custom_pyqtgraph_items import QMenuCustom
and context (classes, functions, or code) from other files:
# Path: src/plugins/util/custom_pyqtgraph_items.py
# class QMenuCustom(QtGui.QMenu):
# """ Custum QMenu that closes on leaveEvent """
# def __init__(self,parent=None):
# QtGui.QMenu.__init__(self, parent)
#
# def leaveEvent(self,ev):
# self.hide()
. Output only the next line. | else: |
Given the code snippet: <|code_start|> def callback(value):
progress.setValue(int(value * 100))
QApplication.processEvents()
try:
fileconverter.raw2npy(filename, path, dtype, width, height, channels, channel, callback)
except:
warn_msg = "Continue trying to convert raw to npy despite problems? Your data might be corrupt."
reply = QMessageBox.question(self, 'Import Issues Detected',
warn_msg, QMessageBox.Yes, QMessageBox.No)
if reply == QMessageBox.Yes:
try:
fileconverter.raw2npy(filename, path, dtype, width, height, channels, channel, callback,
ignore_shape_error=True)
except:
qtutil.critical('Converting raw to npy still fails.')
progress.close()
return
if reply == QMessageBox.No:
return
ret_filename = path
if rescale_value != 1.00:
unscaled = np.load(path)
no_frames = len(unscaled)
try:
scaled = self.bin_ndarray(unscaled, (no_frames, rescale_height,
rescale_width), callback, operation='mean')
np.save(path, scaled)
except:
<|code_end|>
, generate the next line using the imports in this file:
import functools
import os
import sys
import traceback
import numpy as np
import psutil
import qtutil
import tifffile as tiff
from shutil import copyfile
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from .util.plugin import PluginDefault
from .util import file_io, fileconverter
from .util import custom_qt_items as cqt
and context (functions, classes, or occasionally code) from other files:
# Path: src/plugins/util/plugin.py
# class PluginDefault:
# def __init__(self, widget, widget_labels_class, name):
# self.name = name
# self.widget = widget
# if hasattr(self.widget, 'project') and hasattr(self.widget, 'plugin_position'):
# self.widget.params = self.widget.project.pipeline[self.widget.plugin_position]
# self.widget_labels = widget_labels_class
#
# def run(self, input_paths=None):
# return self.widget.execute_primary_function(input_paths)
#
# def get_input_paths(self):
# return self.widget.selected_videos
#
# def output_number_expected(self, expected_input_number=None):
# if expected_input_number:
# return expected_input_number
# else:
# return len(self.get_input_paths())
#
# def check_ready_for_automation(self, expected_input_number):
# return False
#
# def automation_error_message(self):
# return "Plugin " + self.name + " is not suitable for automation."
#
# Path: src/plugins/util/file_io.py
# class UnknownFileFormatError(Exception):
# def load_npy(filename, progress_callback=None, segment=None):
# def get_name_after_no_overwrite(name_before, manip, project):
# def save_file(path, data):
# def load_file(filename, progress_callback=None, segment=None):
# def load_reference_frame_npy(filename, offset):
# def load_reference_frame(filename, offset=0):
#
# Path: src/plugins/util/fileconverter.py
# class RawToNpyConvertError(Exception):
# def error_msg(self):
# def tif2npy(filename_from, filename_to, progress_callback):
# def raw2npy(filename_from, filename_to, dtype, width, height, num_channels, channel, progress_callback,
# ignore_shape_error=False):
#
# Path: src/plugins/util/custom_qt_items.py
# class JSObjectModel(QAbstractTableModel):
# class FileTableModel(JSObjectModel):
# class FileTable(QTableView):
# class ImageStackListView(QListView):
# class MyProgressDialog(QProgressDialog):
# class InfoWidget(QFrame):
# class MyListView(QListView):
# class RoiModel(QStandardItemModel):
# class RoiItemModel(QAbstractListModel):
# class RoiList(QListView):
# class Labels(object):
# class Defaults(object):
# class WarningWidget(QFrame):
# class CheckableComboBox(QtGui.QComboBox):
# class MyTableWidget(QTableWidget):
# class PlayerDialog(QDialog):
# def __init__(self, data, parent=None):
# def rowCount(self, parent):
# def columnCount(self, parent):
# def data(self, index, role):
# def headerData(self, section, orientation, role):
# def retrieve(self, row, key=None):
# def __init__(self, data, parent=None):
# def get_path(self, index):
# def get_entry(self, index):
# def __init__(self, project=None, parent=None):
# def selected_paths(self):
# def __init__(self, parent=None):
# def contextMenuEvent(self, event):
# def __init__(self, title, desc, parent=None):
# def __init__(self, text, parent=None):
# def setup_ui(self, text):
# def __init__(self, parent=None):
# def currentChanged(self, current, previous):
# def __init__(self, parent=None):
# def supportedDropActions(self):
# def dropMimeData(self, data, action, row, column, parent):
# def flags(self, index):
# def removeRows(self, row, count, parent):
# def insertRows(self, row, count, parent):
# def __init__(self, parent=None):
# def appendRoi(self, name):
# def edit_roi_name(self, name, index):
# def rowCount(self, parent):
# def data(self, index, role):
# def setData(self, index, value, role):
# def flags(self, index):
# def removeRow(self, roi_to_remove):
# def __init__(self, widget, roi_types, standard_model=False):
# def selected_roi_changed(self, selection):
# def remove_all_rois(self):
# def setup_params(self, reset=False):
# def setup_param_signals(self):
# def prepare_roi_list_for_update(self, selected, deselected):
# def __init__(self, text, parent=None):
# def setup_ui(self, text):
# def __init__(self):
# def handleItemPressed(self, index):
# def __init__(self, data=None, *args):
# def setmydata(self):
# def update(self, data):
# def __init__(self, project, filename, parent=None, scaling=True):
# def show_frame(self, frame_num):
# def setup_ui(self):
# def slider_moved(self, value):
. Output only the next line. | qtutil.critical("Rebinning raw failed. Please check your scale factor. Use the Help -> 'Whats this' feature" |
Continue the code snippet: <|code_start|>
def get_size(self, path):
"""Method to get the size
"""
raise NotImplementedError(
"You must implement get_size(self, path) on your storage %s" %
self.__class__.__name__)
def fetch(name):
try:
# XXX The noqa below is because of hacking being non-sensical on this
module = __import__('docker_registry.drivers.%s' % name, globals(),
locals(), ['Storage'], 0) # noqa
logger.debug("Will return docker-registry.drivers.%s.Storage" % name)
except ImportError as e:
logger.warn("Got exception: %s" % e)
raise NotImplementedError(
"""You requested storage driver docker_registry.drivers.%s
which is not installed. Try `pip install docker-registry-driver-%s`
or check your configuration. The following are currently
available on your system: %s. Exception was: %s"""
% (name, name, available(), e)
)
module.Storage.scheme = name
return module.Storage
def available():
return [modname for importer, modname, ispkg
<|code_end|>
. Use current file imports:
import functools
import logging
import pkgutil
import urllib
import docker_registry.drivers
from .compat import json
from .exceptions import NotImplementedError
and context (classes, functions, or code) from other files:
# Path: depends/docker-registry-core/docker_registry/core/exceptions.py
# class NotImplementedError(UsageError):
#
# """The requested feature is not supported / not implemented."""
. Output only the next line. | in pkgutil.iter_modules(docker_registry.drivers.__path__)] |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import print_function
# this must happen before anything else
gevent.monkey.patch_all()
cfg = config.load()
if cfg.standalone:
# If standalone mode is enabled, load the fake Index routes
logger = logging.getLogger(__name__)
DESCRIPTION = """run the docker-registry with gunicorn, honoring the following
environment variables:
REGISTRY_HOST: TCP host or ip to bind to; default is 0.0.0.0
REGISTRY_PORT: TCP port to bind to; default is 5000
GUNICORN_WORKERS: number of worker processes gunicorn should start
<|code_end|>
. Use current file imports:
import gevent.monkey
import distutils.spawn
import getpass
import logging
import os
import sys
from argparse import ArgumentParser # noqa
from argparse import RawTextHelpFormatter # noqa
from .app import app # noqa
from .tags import * # noqa
from .images import * # noqa
from .lib import config
from .server import env
from .status import * # noqa
from .search import * # noqa
from .index import * # noqa
and context (classes, functions, or code) from other files:
# Path: docker_registry/app.py
# def ping():
# def root():
# def after_request(response):
# def init():
# def _adapt_smtp_secure(value):
#
# Path: docker_registry/lib/config.py
# class Config(object):
# def __init__(self, config=''):
# def __repr__(self):
# def __dir__(self):
# def keys(self):
# def __members__(self):
# def __methods__(self):
# def __getattr__(self, key):
# def __getitem__(self, key):
# def __contains__(self, key):
# def load():
#
# Path: docker_registry/server/env.py
# _DEFAULT = {
# 'REGISTRY_PORT': '5000',
# 'REGISTRY_HOST': '0.0.0.0',
# 'SETTINGS_FLAVOR': 'dev',
# 'GUNICORN_WORKERS': '4',
# 'GUNICORN_GRACEFUL_TIMEOUT': '3600',
# 'GUNICORN_SILENT_TIMEOUT': '3600',
# 'GUNICORN_ACCESS_LOG_FILE': '"-"',
# 'GUNICORN_ERROR_LOG_FILE': '"-"',
# 'GUNICORN_OPTS': '[]',
# 'NEW_RELIC_INI': '',
# 'NEW_RELIC_STAGE': 'dev'
# }
# def source(key, override=''):
. Output only the next line. | GUNICORN_GRACEFUL_TIMEOUT: timeout in seconds for graceful worker restart |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import print_function
# this must happen before anything else
gevent.monkey.patch_all()
cfg = config.load()
if cfg.standalone:
# If standalone mode is enabled, load the fake Index routes
logger = logging.getLogger(__name__)
DESCRIPTION = """run the docker-registry with gunicorn, honoring the following
environment variables:
REGISTRY_HOST: TCP host or ip to bind to; default is 0.0.0.0
REGISTRY_PORT: TCP port to bind to; default is 5000
GUNICORN_WORKERS: number of worker processes gunicorn should start
GUNICORN_GRACEFUL_TIMEOUT: timeout in seconds for graceful worker restart
GUNICORN_SILENT_TIMEOUT: timeout in seconds for restarting silent workers
GUNICORN_USER: unix user to downgrade priviledges to
<|code_end|>
. Write the next line using the current file imports:
import gevent.monkey
import distutils.spawn
import getpass
import logging
import os
import sys
from argparse import ArgumentParser # noqa
from argparse import RawTextHelpFormatter # noqa
from .app import app # noqa
from .tags import * # noqa
from .images import * # noqa
from .lib import config
from .server import env
from .status import * # noqa
from .search import * # noqa
from .index import * # noqa
and context from other files:
# Path: docker_registry/app.py
# def ping():
# def root():
# def after_request(response):
# def init():
# def _adapt_smtp_secure(value):
#
# Path: docker_registry/lib/config.py
# class Config(object):
# def __init__(self, config=''):
# def __repr__(self):
# def __dir__(self):
# def keys(self):
# def __members__(self):
# def __methods__(self):
# def __getattr__(self, key):
# def __getitem__(self, key):
# def __contains__(self, key):
# def load():
#
# Path: docker_registry/server/env.py
# _DEFAULT = {
# 'REGISTRY_PORT': '5000',
# 'REGISTRY_HOST': '0.0.0.0',
# 'SETTINGS_FLAVOR': 'dev',
# 'GUNICORN_WORKERS': '4',
# 'GUNICORN_GRACEFUL_TIMEOUT': '3600',
# 'GUNICORN_SILENT_TIMEOUT': '3600',
# 'GUNICORN_ACCESS_LOG_FILE': '"-"',
# 'GUNICORN_ERROR_LOG_FILE': '"-"',
# 'GUNICORN_OPTS': '[]',
# 'NEW_RELIC_INI': '',
# 'NEW_RELIC_STAGE': 'dev'
# }
# def source(key, override=''):
, which may include functions, classes, or code. Output only the next line. | GUNICORN_GROUP: unix group to downgrade priviledges to |
Based on the 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 specific language governing permissions and
# limitations under the License.
class Query(object):
def __init__(self, scheme=None):
self.scheme = scheme
def testDriverIsAvailable(self):
drvs = driver.available()
assert self.scheme in drvs
def testFetchingDriver(self):
resultdriver = driver.fetch(self.scheme)
# XXX hacking is sick
storage = __import__('docker_registry.drivers.%s' % self.scheme,
globals(), locals(), ['Storage'], 0) # noqa
assert resultdriver == storage.Storage
assert issubclass(resultdriver, driver.Base)
<|code_end|>
, predict the immediate next line with the help of imports:
from nose import tools
from ..core import driver
from ..core import exceptions
and context (classes, functions, sometimes code) from other files:
# Path: depends/docker-registry-core/docker_registry/core/driver.py
# def check(value):
# def filter_args(f):
# def wrapper(*args, **kwargs):
# def _repository_path(self, namespace, repository):
# def __init__(self, path=None, config=None):
# def images_list_path(self, namespace, repository):
# def image_json_path(self, image_id):
# def image_mark_path(self, image_id):
# def image_checksum_path(self, image_id):
# def image_layer_path(self, image_id):
# def image_ancestry_path(self, image_id):
# def image_files_path(self, image_id):
# def image_diff_path(self, image_id):
# def repository_path(self, namespace, repository):
# def tag_path(self, namespace, repository, tagname=None):
# def repository_json_path(self, namespace, repository):
# def repository_tag_json_path(self, namespace, repository, tag):
# def index_images_path(self, namespace, repository):
# def private_flag_path(self, namespace, repository):
# def is_private(self, namespace, repository):
# def content_redirect_url(self, path):
# def get_json(self, path):
# def put_json(self, path, content):
# def get_unicode(self, path):
# def put_unicode(self, path, content):
# def get_bytes(self, path):
# def put_bytes(self, path, content):
# def get_content(self, path):
# def put_content(self, path, content):
# def stream_read(self, path, bytes_range=None):
# def stream_write(self, path, fp):
# def list_directory(self, path=None):
# def exists(self, path):
# def remove(self, path):
# def get_size(self, path):
# def fetch(name):
# def available():
# class Base(object):
#
# Path: depends/docker-registry-core/docker_registry/core/exceptions.py
# class UnspecifiedError(Exception):
# class UsageError(UnspecifiedError):
# class NotImplementedError(UsageError):
# class FileNotFoundError(UsageError):
# class WrongArgumentsError(UsageError):
# class ConfigError(UsageError):
# class ConnectionError(UnspecifiedError):
# class UnreachableError(ConnectionError):
# class MissingError(ConnectionError):
# class BrokenError(ConnectionError):
# def __init__(self, *args, **kwargs):
. Output only the next line. | assert resultdriver.scheme == self.scheme |
Next line prediction: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
_new_relic_ini = env.source('NEW_RELIC_INI')
if _new_relic_ini:
try:
newrelic.agent.initialize(
_new_relic_ini,
env.source('NEW_RELIC_STAGE'))
except Exception as e:
raise(Exception('Failed to init new relic agent %s' % e))
if __name__ == '__main__':
# Bind to PORT if defined, otherwise default to 5000.
host = env.source('REGISTRY_HOST')
port = env.source('REGISTRY_PORT')
app.debug = True
app.run(host=host, port=port)
# Or you can run:
# gunicorn --access-logfile - --log-level debug --debug -b 0.0.0.0:5000 \
# -w 1 wsgi:application
else:
# For uwsgi
app.logger.setLevel(logging.INFO)
stderr_logger = logging.StreamHandler()
stderr_logger.setLevel(logging.INFO)
<|code_end|>
. Use current file imports:
(from .server import env
from .run import app
import logging
import newrelic.agent)
and context including class names, function names, or small code snippets from other files:
# Path: docker_registry/server/env.py
# _DEFAULT = {
# 'REGISTRY_PORT': '5000',
# 'REGISTRY_HOST': '0.0.0.0',
# 'SETTINGS_FLAVOR': 'dev',
# 'GUNICORN_WORKERS': '4',
# 'GUNICORN_GRACEFUL_TIMEOUT': '3600',
# 'GUNICORN_SILENT_TIMEOUT': '3600',
# 'GUNICORN_ACCESS_LOG_FILE': '"-"',
# 'GUNICORN_ERROR_LOG_FILE': '"-"',
# 'GUNICORN_OPTS': '[]',
# 'NEW_RELIC_INI': '',
# 'NEW_RELIC_STAGE': 'dev'
# }
# def source(key, override=''):
#
# Path: docker_registry/run.py
# DESCRIPTION = """run the docker-registry with gunicorn, honoring the following
# environment variables:
# REGISTRY_HOST: TCP host or ip to bind to; default is 0.0.0.0
# REGISTRY_PORT: TCP port to bind to; default is 5000
# GUNICORN_WORKERS: number of worker processes gunicorn should start
# GUNICORN_GRACEFUL_TIMEOUT: timeout in seconds for graceful worker restart
# GUNICORN_SILENT_TIMEOUT: timeout in seconds for restarting silent workers
# GUNICORN_USER: unix user to downgrade priviledges to
# GUNICORN_GROUP: unix group to downgrade priviledges to
# GUNICORN_ACCESS_LOG_FILE: File to log access to
# GUNICORN_ERROR_LOG_FILE: File to log errors to
# """
# def run_gunicorn():
. Output only the next line. | stderr_logger.setFormatter( |
Continue the code snippet: <|code_start|>
class UserProfileTest(TestCase):
def setUp(self):
self.u1 = User.objects.create_user('username', 'email@email.com', 'password')
self.u2 = User.objects.create_user('dickweed', 'email2@email.com', 'password')
self.up1 = UserProfile.objects.create(user=self.u1, name="Lil Jon")
self.up2 = UserProfile.objects.create(user=self.u2, name="dan", steamid="dyladan")
<|code_end|>
. Use current file imports:
from django.test import Client, TestCase
from whatistheplan.models import UserProfile
from django.contrib.auth.models import User
and context (classes, functions, or code) from other files:
# Path: whatistheplan/models/userprofile.py
# class UserProfile(models.Model):
# """
# user -> (Django built-in User class)
# name -> Eugene M'TnDew
# steamid -> dyladan
# """
# user = models.OneToOneField(User, primary_key=True)
# name = models.CharField(max_length=256, unique=False)
# steamid = models.CharField(max_length=256)
# irc = models.CharField(max_length=256, unique=False)
# mac_address = models.CharField(max_length=256, unique=False)
. Output only the next line. | def test_user_profile_ownership(self): |
Continue the code snippet: <|code_start|>
class TeamTest(TestCase):
def setUp(self):
self.g1 = Game.objects.create(game_name='Counter Strike Source')
self.g1.save()
self.u1 = User.objects.create_user('username', 'email@email.com', 'password')
self.u2 = User.objects.create_user('dickweed', 'email2@email.com', 'password')
self.u1.save()
self.u2.save()
self.up1 = UserProfile.objects.create(user=self.u1, name="Lil Jon")
self.up2 = UserProfile.objects.create(user=self.u2, name="dan", steamid="dyladan")
self.up1.save()
self.up2.save()
self.t1 = Team.objects.create(team_name='The Crows', game=self.g1)
self.t2 = Team.objects.create(team_name='Wildlings', game=self.g1)
<|code_end|>
. Use current file imports:
from django.test import Client, TestCase
from whatistheplan.models import Team, Game, UserProfile
from django.contrib.auth.models import User
and context (classes, functions, or code) from other files:
# Path: whatistheplan/models/userprofile.py
# class UserProfile(models.Model):
# """
# user -> (Django built-in User class)
# name -> Eugene M'TnDew
# steamid -> dyladan
# """
# user = models.OneToOneField(User, primary_key=True)
# name = models.CharField(max_length=256, unique=False)
# steamid = models.CharField(max_length=256)
# irc = models.CharField(max_length=256, unique=False)
# mac_address = models.CharField(max_length=256, unique=False)
#
# Path: whatistheplan/models/game.py
# class Game(models.Model):
# """
# game_name -> Counter Strike Source
# """
# # game_name = models.CharField(max_length=256)
# # game_time = models.CharField(max_length=256)
# # game_room = models.CharField(max_length=256)
# # game_1st_prize = models.Charfield(max_length=256)
# # game_2nd_prize = models.Charfield(max_length=256)
# # game_3rd_prize = models.Charfield(max_length=256)
# # game_details = models.Charfield(max_length=1024)
# #
# # game_image = models.ImageField()
#
# Path: whatistheplan/models/team.py
# class Team(models.Model):
# """
# team_name -> The Crows
# game -> (instance of Game class)
# """
# team_name = models.CharField(max_length=256)
# game = models.ForeignKey('Game')
# userprofiles = models.ManyToManyField('UserProfile')
. Output only the next line. | self.t1.save() |
Predict the next line for this snippet: <|code_start|>
class TeamTest(TestCase):
def setUp(self):
self.g1 = Game.objects.create(game_name='Counter Strike Source')
self.g1.save()
self.u1 = User.objects.create_user('username', 'email@email.com', 'password')
self.u2 = User.objects.create_user('dickweed', 'email2@email.com', 'password')
self.u1.save()
self.u2.save()
self.up1 = UserProfile.objects.create(user=self.u1, name="Lil Jon")
self.up2 = UserProfile.objects.create(user=self.u2, name="dan", steamid="dyladan")
self.up1.save()
self.up2.save()
self.t1 = Team.objects.create(team_name='The Crows', game=self.g1)
self.t2 = Team.objects.create(team_name='Wildlings', game=self.g1)
self.t1.save()
self.t2.save()
<|code_end|>
with the help of current file imports:
from django.test import Client, TestCase
from whatistheplan.models import Team, Game, UserProfile
from django.contrib.auth.models import User
and context from other files:
# Path: whatistheplan/models/userprofile.py
# class UserProfile(models.Model):
# """
# user -> (Django built-in User class)
# name -> Eugene M'TnDew
# steamid -> dyladan
# """
# user = models.OneToOneField(User, primary_key=True)
# name = models.CharField(max_length=256, unique=False)
# steamid = models.CharField(max_length=256)
# irc = models.CharField(max_length=256, unique=False)
# mac_address = models.CharField(max_length=256, unique=False)
#
# Path: whatistheplan/models/game.py
# class Game(models.Model):
# """
# game_name -> Counter Strike Source
# """
# # game_name = models.CharField(max_length=256)
# # game_time = models.CharField(max_length=256)
# # game_room = models.CharField(max_length=256)
# # game_1st_prize = models.Charfield(max_length=256)
# # game_2nd_prize = models.Charfield(max_length=256)
# # game_3rd_prize = models.Charfield(max_length=256)
# # game_details = models.Charfield(max_length=1024)
# #
# # game_image = models.ImageField()
#
# Path: whatistheplan/models/team.py
# class Team(models.Model):
# """
# team_name -> The Crows
# game -> (instance of Game class)
# """
# team_name = models.CharField(max_length=256)
# game = models.ForeignKey('Game')
# userprofiles = models.ManyToManyField('UserProfile')
, which may contain function names, class names, or code. Output only the next line. | def test_team_game_relationship(self): |
Predict the next line for this snippet: <|code_start|>
class TeamTest(TestCase):
def setUp(self):
self.g1 = Game.objects.create(game_name='Counter Strike Source')
self.g1.save()
self.u1 = User.objects.create_user('username', 'email@email.com', 'password')
self.u2 = User.objects.create_user('dickweed', 'email2@email.com', 'password')
self.u1.save()
self.u2.save()
self.up1 = UserProfile.objects.create(user=self.u1, name="Lil Jon")
self.up2 = UserProfile.objects.create(user=self.u2, name="dan", steamid="dyladan")
self.up1.save()
self.up2.save()
self.t1 = Team.objects.create(team_name='The Crows', game=self.g1)
self.t2 = Team.objects.create(team_name='Wildlings', game=self.g1)
self.t1.save()
self.t2.save()
<|code_end|>
with the help of current file imports:
from django.test import Client, TestCase
from whatistheplan.models import Team, Game, UserProfile
from django.contrib.auth.models import User
and context from other files:
# Path: whatistheplan/models/userprofile.py
# class UserProfile(models.Model):
# """
# user -> (Django built-in User class)
# name -> Eugene M'TnDew
# steamid -> dyladan
# """
# user = models.OneToOneField(User, primary_key=True)
# name = models.CharField(max_length=256, unique=False)
# steamid = models.CharField(max_length=256)
# irc = models.CharField(max_length=256, unique=False)
# mac_address = models.CharField(max_length=256, unique=False)
#
# Path: whatistheplan/models/game.py
# class Game(models.Model):
# """
# game_name -> Counter Strike Source
# """
# # game_name = models.CharField(max_length=256)
# # game_time = models.CharField(max_length=256)
# # game_room = models.CharField(max_length=256)
# # game_1st_prize = models.Charfield(max_length=256)
# # game_2nd_prize = models.Charfield(max_length=256)
# # game_3rd_prize = models.Charfield(max_length=256)
# # game_details = models.Charfield(max_length=1024)
# #
# # game_image = models.ImageField()
#
# Path: whatistheplan/models/team.py
# class Team(models.Model):
# """
# team_name -> The Crows
# game -> (instance of Game class)
# """
# team_name = models.CharField(max_length=256)
# game = models.ForeignKey('Game')
# userprofiles = models.ManyToManyField('UserProfile')
, which may contain function names, class names, or code. Output only the next line. | def test_team_game_relationship(self): |
Predict the next line after this snippet: <|code_start|>
class UserFormTest(TestCase):
def setUp(self):
self.user_form_data = {
'username': 'sn1par_eugene',
'password': 'bloxwich',
'email': 'h00bastankR0x@aol.com'
}
self.user_profile_form_data = {
<|code_end|>
using the current file's imports:
from django.test import TestCase, Client
from whatistheplan.forms import UserForm, UserProfileForm
and any relevant context from other files:
# Path: whatistheplan/forms.py
# class UserForm(forms.ModelForm):
# """Form for user signup"""
# password = forms.CharField(widget=forms.PasswordInput())
# class Meta: #pylint: disable=missing-docstring
# model = User
# fields = (
# 'username',
# 'password',
# 'email'
# )
#
# class UserProfileForm(forms.ModelForm):
# """Form for user profile"""
# class Meta: #pylint: disable=missing-docstring
# model = UserProfile
# fields = (
# 'name',
# 'irc',
# 'steamid',
# 'mac_address'
# )
. Output only the next line. | 'name': "Eugene M'TnDew", |
Given snippet: <|code_start|>
class UserFormTest(TestCase):
def setUp(self):
self.user_form_data = {
'username': 'sn1par_eugene',
'password': 'bloxwich',
'email': 'h00bastankR0x@aol.com'
}
self.user_profile_form_data = {
'name': "Eugene M'TnDew",
'mac_address': '00:00:00:00:00:00',
'steamid': 'xXx_sn1par_eugene_420_xXx',
'irc': 'eugene'
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.test import TestCase, Client
from whatistheplan.forms import UserForm, UserProfileForm
and context:
# Path: whatistheplan/forms.py
# class UserForm(forms.ModelForm):
# """Form for user signup"""
# password = forms.CharField(widget=forms.PasswordInput())
# class Meta: #pylint: disable=missing-docstring
# model = User
# fields = (
# 'username',
# 'password',
# 'email'
# )
#
# class UserProfileForm(forms.ModelForm):
# """Form for user profile"""
# class Meta: #pylint: disable=missing-docstring
# model = UserProfile
# fields = (
# 'name',
# 'irc',
# 'steamid',
# 'mac_address'
# )
which might include code, classes, or functions. Output only the next line. | } |
Next line prediction: <|code_start|> ast = data_tools.bash_parser(cmd)
if ast:
command = get_command(cmd)
print('extracted: {}'.format(cmd))
url.commands.add(command)
url.save()
def populate_command_tags():
for cmd in Command.objects.all():
if len(cmd.str) > 600:
cmd.delete()
else:
cmd.tags.clear()
print(cmd.str)
ast = data_tools.bash_parser(cmd.str)
for utility in data_tools.get_utilities(ast):
print(utility)
cmd.tags.add(get_tag(utility))
cmd.save()
def populate_command_template():
for cmd in Command.objects.all():
if len(cmd.str) > 600:
cmd.delete()
else:
ast = data_tools.bash_parser(cmd.str)
template = data_tools.ast2template(ast, loose_constraints=True)
cmd.template = template
cmd.save()
<|code_end|>
. Use current file imports:
(import html
import os, sys
import pickle
import re
import sqlite3
from website.models import Annotation, AnnotationUpdate, Command, \
Notification, URL, URLTag
from website.utils import get_tag, get_command, get_url
from bashlint import data_tools)
and context including class names, function names, or small code snippets from other files:
# Path: website/models.py
# class Annotation(models.Model):
# """
# Each record is a natural language <-> code translation annotated by a
# programmer.
# """
# url = models.ForeignKey(URL, on_delete=models.CASCADE)
# nl = models.ForeignKey(NL, on_delete=models.CASCADE)
# cmd = models.ForeignKey(Command, on_delete=models.CASCADE)
# annotator = models.ForeignKey(User, on_delete=models.CASCADE)
# submission_time = models.DateTimeField(default=timezone.now)
#
# class AnnotationUpdate(models.Model):
# """
# Each record is an update of an annotation submitted by a judger.
# """
# annotation = models.ForeignKey(Annotation, on_delete=models.CASCADE)
# judger = models.ForeignKey(User, on_delete=models.CASCADE)
# update_str = models.TextField()
# update_type = models.TextField(default='nl')
# comment = models.ForeignKey(Comment, on_delete=models.CASCADE)
# submission_time = models.DateTimeField(default=timezone.now)
# status = models.TextField(default='open')
#
# class Command(models.Model):
# """
# Command line.
# """
# str = models.TextField(primary_key=True)
# template = models.TextField(default='')
# language = models.TextField(default='bash')
# tags = models.ManyToManyField('Tag')
#
# class Notification(models.Model):
# """
# Each record is a certain type of message issued from one annotator to
# another.
# """
# sender = models.ForeignKey(User, related_name='notification_sender',
# on_delete=models.CASCADE)
# receiver = models.ForeignKey(User, related_name='notification_receiver',
# on_delete=models.CASCADE)
# type = models.TextField(default='comment')
# annotation_update = models.ForeignKey('AnnotationUpdate', null=True,
# on_delete=models.CASCADE)
# comment = models.ForeignKey('Comment', null=True, on_delete=models.CASCADE)
# url = models.ForeignKey('URL', on_delete=models.CASCADE)
# creation_time = models.DateTimeField(default=timezone.now)
# status = models.TextField(default='issued')
#
# class URL(models.Model):
# """
# URL.
#
# :member str: url address.
# :member html_content: snapshot of the URL content at the time of annotation.
# :member commands: commands in the URL (automatically extracted)
# :member tags: tags of the URL (assigned based on user annotations)
# """
# str = models.TextField(primary_key=True)
# html_content = models.TextField(default='')
# commands = models.ManyToManyField('Command')
# tags = models.ManyToManyField('Tag')
#
# class URLTag(models.Model):
# """
# Each record stores a (url, tag) pair.
# """
# url = models.ForeignKey(URL, on_delete=models.CASCADE)
# tag = models.TextField()
#
# Path: website/utils.py
# def get_tag(tag_str):
# tag, _ = Tag.objects.get_or_create(str=tag_str.strip())
# return tag
#
# def get_command(command_str):
# command_str=command_str.strip()
# if Command.objects.filter(str=command_str).exists():
# cmd = Command.objects.get(str=command_str)
# else:
# cmd = Command.objects.create(str=command_str)
# ast = data_tools.bash_parser(command_str)
# for utility in data_tools.get_utilities(ast):
# cmd.tags.add(get_tag(utility))
# template = data_tools.ast2template(
# ast, loose_constraints=True)
# cmd.template = template
# cmd.save()
# return cmd
#
# def get_url(url_str):
# url_str = url_str.strip()
# try:
# url = URL.objects.get(str=url_str)
# except ObjectDoesNotExist:
# html = extract_html(url_str)
# if html is None:
# url = URL.objects.create(str=url_str)
# else:
# url = URL.objects.create(str=url_str, html_content=html)
# return url
. Output only the next line. | def populate_tag_commands(): |
Predict the next line for this snippet: <|code_start|> if not URLTag.objects.filter(url__str=url, tag=utility):
URLTag.objects.create(url=get_url(url), tag=utility)
print("Add {}, {}".format(url, utility))
def load_commands_in_url(stackoverflow_dump_path):
url_prefix = 'https://stackoverflow.com/questions/'
with sqlite3.connect(stackoverflow_dump_path,
detect_types=sqlite3.PARSE_DECLTYPES) as db:
for url in URL.objects.all():
# url = URL.objects.get(str='https://stackoverflow.com/questions/127669')
url.commands.clear()
print(url.str)
for answer_body, in db.cursor().execute("""
SELECT answers.Body FROM answers
WHERE answers.ParentId = ?""", (url.str[len(url_prefix):],)):
url.html_content = answer_body
for code_block in extract_code(url.html_content):
for cmd in extract_oneliners_from_code(code_block):
ast = data_tools.bash_parser(cmd)
if ast:
command = get_command(cmd)
print('extracted: {}'.format(cmd))
url.commands.add(command)
url.save()
def populate_command_tags():
for cmd in Command.objects.all():
if len(cmd.str) > 600:
cmd.delete()
else:
<|code_end|>
with the help of current file imports:
import html
import os, sys
import pickle
import re
import sqlite3
from website.models import Annotation, AnnotationUpdate, Command, \
Notification, URL, URLTag
from website.utils import get_tag, get_command, get_url
from bashlint import data_tools
and context from other files:
# Path: website/models.py
# class Annotation(models.Model):
# """
# Each record is a natural language <-> code translation annotated by a
# programmer.
# """
# url = models.ForeignKey(URL, on_delete=models.CASCADE)
# nl = models.ForeignKey(NL, on_delete=models.CASCADE)
# cmd = models.ForeignKey(Command, on_delete=models.CASCADE)
# annotator = models.ForeignKey(User, on_delete=models.CASCADE)
# submission_time = models.DateTimeField(default=timezone.now)
#
# class AnnotationUpdate(models.Model):
# """
# Each record is an update of an annotation submitted by a judger.
# """
# annotation = models.ForeignKey(Annotation, on_delete=models.CASCADE)
# judger = models.ForeignKey(User, on_delete=models.CASCADE)
# update_str = models.TextField()
# update_type = models.TextField(default='nl')
# comment = models.ForeignKey(Comment, on_delete=models.CASCADE)
# submission_time = models.DateTimeField(default=timezone.now)
# status = models.TextField(default='open')
#
# class Command(models.Model):
# """
# Command line.
# """
# str = models.TextField(primary_key=True)
# template = models.TextField(default='')
# language = models.TextField(default='bash')
# tags = models.ManyToManyField('Tag')
#
# class Notification(models.Model):
# """
# Each record is a certain type of message issued from one annotator to
# another.
# """
# sender = models.ForeignKey(User, related_name='notification_sender',
# on_delete=models.CASCADE)
# receiver = models.ForeignKey(User, related_name='notification_receiver',
# on_delete=models.CASCADE)
# type = models.TextField(default='comment')
# annotation_update = models.ForeignKey('AnnotationUpdate', null=True,
# on_delete=models.CASCADE)
# comment = models.ForeignKey('Comment', null=True, on_delete=models.CASCADE)
# url = models.ForeignKey('URL', on_delete=models.CASCADE)
# creation_time = models.DateTimeField(default=timezone.now)
# status = models.TextField(default='issued')
#
# class URL(models.Model):
# """
# URL.
#
# :member str: url address.
# :member html_content: snapshot of the URL content at the time of annotation.
# :member commands: commands in the URL (automatically extracted)
# :member tags: tags of the URL (assigned based on user annotations)
# """
# str = models.TextField(primary_key=True)
# html_content = models.TextField(default='')
# commands = models.ManyToManyField('Command')
# tags = models.ManyToManyField('Tag')
#
# class URLTag(models.Model):
# """
# Each record stores a (url, tag) pair.
# """
# url = models.ForeignKey(URL, on_delete=models.CASCADE)
# tag = models.TextField()
#
# Path: website/utils.py
# def get_tag(tag_str):
# tag, _ = Tag.objects.get_or_create(str=tag_str.strip())
# return tag
#
# def get_command(command_str):
# command_str=command_str.strip()
# if Command.objects.filter(str=command_str).exists():
# cmd = Command.objects.get(str=command_str)
# else:
# cmd = Command.objects.create(str=command_str)
# ast = data_tools.bash_parser(command_str)
# for utility in data_tools.get_utilities(ast):
# cmd.tags.add(get_tag(utility))
# template = data_tools.ast2template(
# ast, loose_constraints=True)
# cmd.template = template
# cmd.save()
# return cmd
#
# def get_url(url_str):
# url_str = url_str.strip()
# try:
# url = URL.objects.get(str=url_str)
# except ObjectDoesNotExist:
# html = extract_html(url_str)
# if html is None:
# url = URL.objects.create(str=url_str)
# else:
# url = URL.objects.create(str=url_str, html_content=html)
# return url
, which may contain function names, class names, or code. Output only the next line. | cmd.tags.clear() |
Using the snippet: <|code_start|> url.commands.clear()
print(url.str)
for answer_body, in db.cursor().execute("""
SELECT answers.Body FROM answers
WHERE answers.ParentId = ?""", (url.str[len(url_prefix):],)):
url.html_content = answer_body
for code_block in extract_code(url.html_content):
for cmd in extract_oneliners_from_code(code_block):
ast = data_tools.bash_parser(cmd)
if ast:
command = get_command(cmd)
print('extracted: {}'.format(cmd))
url.commands.add(command)
url.save()
def populate_command_tags():
for cmd in Command.objects.all():
if len(cmd.str) > 600:
cmd.delete()
else:
cmd.tags.clear()
print(cmd.str)
ast = data_tools.bash_parser(cmd.str)
for utility in data_tools.get_utilities(ast):
print(utility)
cmd.tags.add(get_tag(utility))
cmd.save()
def populate_command_template():
for cmd in Command.objects.all():
<|code_end|>
, determine the next line of code. You have imports:
import html
import os, sys
import pickle
import re
import sqlite3
from website.models import Annotation, AnnotationUpdate, Command, \
Notification, URL, URLTag
from website.utils import get_tag, get_command, get_url
from bashlint import data_tools
and context (class names, function names, or code) available:
# Path: website/models.py
# class Annotation(models.Model):
# """
# Each record is a natural language <-> code translation annotated by a
# programmer.
# """
# url = models.ForeignKey(URL, on_delete=models.CASCADE)
# nl = models.ForeignKey(NL, on_delete=models.CASCADE)
# cmd = models.ForeignKey(Command, on_delete=models.CASCADE)
# annotator = models.ForeignKey(User, on_delete=models.CASCADE)
# submission_time = models.DateTimeField(default=timezone.now)
#
# class AnnotationUpdate(models.Model):
# """
# Each record is an update of an annotation submitted by a judger.
# """
# annotation = models.ForeignKey(Annotation, on_delete=models.CASCADE)
# judger = models.ForeignKey(User, on_delete=models.CASCADE)
# update_str = models.TextField()
# update_type = models.TextField(default='nl')
# comment = models.ForeignKey(Comment, on_delete=models.CASCADE)
# submission_time = models.DateTimeField(default=timezone.now)
# status = models.TextField(default='open')
#
# class Command(models.Model):
# """
# Command line.
# """
# str = models.TextField(primary_key=True)
# template = models.TextField(default='')
# language = models.TextField(default='bash')
# tags = models.ManyToManyField('Tag')
#
# class Notification(models.Model):
# """
# Each record is a certain type of message issued from one annotator to
# another.
# """
# sender = models.ForeignKey(User, related_name='notification_sender',
# on_delete=models.CASCADE)
# receiver = models.ForeignKey(User, related_name='notification_receiver',
# on_delete=models.CASCADE)
# type = models.TextField(default='comment')
# annotation_update = models.ForeignKey('AnnotationUpdate', null=True,
# on_delete=models.CASCADE)
# comment = models.ForeignKey('Comment', null=True, on_delete=models.CASCADE)
# url = models.ForeignKey('URL', on_delete=models.CASCADE)
# creation_time = models.DateTimeField(default=timezone.now)
# status = models.TextField(default='issued')
#
# class URL(models.Model):
# """
# URL.
#
# :member str: url address.
# :member html_content: snapshot of the URL content at the time of annotation.
# :member commands: commands in the URL (automatically extracted)
# :member tags: tags of the URL (assigned based on user annotations)
# """
# str = models.TextField(primary_key=True)
# html_content = models.TextField(default='')
# commands = models.ManyToManyField('Command')
# tags = models.ManyToManyField('Tag')
#
# class URLTag(models.Model):
# """
# Each record stores a (url, tag) pair.
# """
# url = models.ForeignKey(URL, on_delete=models.CASCADE)
# tag = models.TextField()
#
# Path: website/utils.py
# def get_tag(tag_str):
# tag, _ = Tag.objects.get_or_create(str=tag_str.strip())
# return tag
#
# def get_command(command_str):
# command_str=command_str.strip()
# if Command.objects.filter(str=command_str).exists():
# cmd = Command.objects.get(str=command_str)
# else:
# cmd = Command.objects.create(str=command_str)
# ast = data_tools.bash_parser(command_str)
# for utility in data_tools.get_utilities(ast):
# cmd.tags.add(get_tag(utility))
# template = data_tools.ast2template(
# ast, loose_constraints=True)
# cmd.template = template
# cmd.save()
# return cmd
#
# def get_url(url_str):
# url_str = url_str.strip()
# try:
# url = URL.objects.get(str=url_str)
# except ObjectDoesNotExist:
# html = extract_html(url_str)
# if html is None:
# url = URL.objects.create(str=url_str)
# else:
# url = URL.objects.create(str=url_str, html_content=html)
# return url
. Output only the next line. | if len(cmd.str) > 600: |
Given the following code snippet before the placeholder: <|code_start|> cmd.tags.add(get_tag(utility))
cmd.save()
def populate_command_template():
for cmd in Command.objects.all():
if len(cmd.str) > 600:
cmd.delete()
else:
ast = data_tools.bash_parser(cmd.str)
template = data_tools.ast2template(ast, loose_constraints=True)
cmd.template = template
cmd.save()
def populate_tag_commands():
for tag in Tag.objects.all():
tag.commands.clear()
for url_tag in URLTag.objects.all():
print(url_tag.url.str)
tag = get_tag(url_tag.tag)
for cmd in url_tag.url.commands.all():
if tag in cmd.tags.all():
tag.commands.add(cmd)
tag.save()
def populate_url_tags():
for url in URL.objects.all():
for annotation in Annotation.objects.filter(url=url):
for tag in annotation.cmd.tags.all():
url.tags.add(tag)
<|code_end|>
, predict the next line using imports from the current file:
import html
import os, sys
import pickle
import re
import sqlite3
from website.models import Annotation, AnnotationUpdate, Command, \
Notification, URL, URLTag
from website.utils import get_tag, get_command, get_url
from bashlint import data_tools
and context including class names, function names, and sometimes code from other files:
# Path: website/models.py
# class Annotation(models.Model):
# """
# Each record is a natural language <-> code translation annotated by a
# programmer.
# """
# url = models.ForeignKey(URL, on_delete=models.CASCADE)
# nl = models.ForeignKey(NL, on_delete=models.CASCADE)
# cmd = models.ForeignKey(Command, on_delete=models.CASCADE)
# annotator = models.ForeignKey(User, on_delete=models.CASCADE)
# submission_time = models.DateTimeField(default=timezone.now)
#
# class AnnotationUpdate(models.Model):
# """
# Each record is an update of an annotation submitted by a judger.
# """
# annotation = models.ForeignKey(Annotation, on_delete=models.CASCADE)
# judger = models.ForeignKey(User, on_delete=models.CASCADE)
# update_str = models.TextField()
# update_type = models.TextField(default='nl')
# comment = models.ForeignKey(Comment, on_delete=models.CASCADE)
# submission_time = models.DateTimeField(default=timezone.now)
# status = models.TextField(default='open')
#
# class Command(models.Model):
# """
# Command line.
# """
# str = models.TextField(primary_key=True)
# template = models.TextField(default='')
# language = models.TextField(default='bash')
# tags = models.ManyToManyField('Tag')
#
# class Notification(models.Model):
# """
# Each record is a certain type of message issued from one annotator to
# another.
# """
# sender = models.ForeignKey(User, related_name='notification_sender',
# on_delete=models.CASCADE)
# receiver = models.ForeignKey(User, related_name='notification_receiver',
# on_delete=models.CASCADE)
# type = models.TextField(default='comment')
# annotation_update = models.ForeignKey('AnnotationUpdate', null=True,
# on_delete=models.CASCADE)
# comment = models.ForeignKey('Comment', null=True, on_delete=models.CASCADE)
# url = models.ForeignKey('URL', on_delete=models.CASCADE)
# creation_time = models.DateTimeField(default=timezone.now)
# status = models.TextField(default='issued')
#
# class URL(models.Model):
# """
# URL.
#
# :member str: url address.
# :member html_content: snapshot of the URL content at the time of annotation.
# :member commands: commands in the URL (automatically extracted)
# :member tags: tags of the URL (assigned based on user annotations)
# """
# str = models.TextField(primary_key=True)
# html_content = models.TextField(default='')
# commands = models.ManyToManyField('Command')
# tags = models.ManyToManyField('Tag')
#
# class URLTag(models.Model):
# """
# Each record stores a (url, tag) pair.
# """
# url = models.ForeignKey(URL, on_delete=models.CASCADE)
# tag = models.TextField()
#
# Path: website/utils.py
# def get_tag(tag_str):
# tag, _ = Tag.objects.get_or_create(str=tag_str.strip())
# return tag
#
# def get_command(command_str):
# command_str=command_str.strip()
# if Command.objects.filter(str=command_str).exists():
# cmd = Command.objects.get(str=command_str)
# else:
# cmd = Command.objects.create(str=command_str)
# ast = data_tools.bash_parser(command_str)
# for utility in data_tools.get_utilities(ast):
# cmd.tags.add(get_tag(utility))
# template = data_tools.ast2template(
# ast, loose_constraints=True)
# cmd.template = template
# cmd.save()
# return cmd
#
# def get_url(url_str):
# url_str = url_str.strip()
# try:
# url = URL.objects.get(str=url_str)
# except ObjectDoesNotExist:
# html = extract_html(url_str)
# if html is None:
# url = URL.objects.create(str=url_str)
# else:
# url = URL.objects.create(str=url_str, html_content=html)
# return url
. Output only the next line. | def populate_tag_annotations(): |
Using the snippet: <|code_start|> "tellina_learning_module")
sys.path.append(learning_module_dir)
CODE_REGEX = re.compile(r"<pre><code>([^<]+\n[^<]*)<\/code><\/pre>")
def extract_code(text):
for match in CODE_REGEX.findall(text):
if match.strip():
yield html.unescape(match.replace("<br>", "\n"))
def extract_oneliners_from_code(code_block):
for cmd in code_block.splitlines():
if cmd.startswith('$ '):
cmd = cmd[2:]
if cmd.startswith('# '):
cmd = cmd[2:]
comment = re.search(r'\s+#\s+', cmd)
if comment:
old_cmd = cmd
cmd = cmd[:comment.start()]
print('Remove comment: {} -> {}'.format(old_cmd, cmd))
cmd = cmd.strip()
# discard code block opening line
if cmd and not cmd[-1] in ['{', '[', '(']:
yield cmd
def load_urls(input_file_path):
<|code_end|>
, determine the next line of code. You have imports:
import html
import os, sys
import pickle
import re
import sqlite3
from website.models import Annotation, AnnotationUpdate, Command, \
Notification, URL, URLTag
from website.utils import get_tag, get_command, get_url
from bashlint import data_tools
and context (class names, function names, or code) available:
# Path: website/models.py
# class Annotation(models.Model):
# """
# Each record is a natural language <-> code translation annotated by a
# programmer.
# """
# url = models.ForeignKey(URL, on_delete=models.CASCADE)
# nl = models.ForeignKey(NL, on_delete=models.CASCADE)
# cmd = models.ForeignKey(Command, on_delete=models.CASCADE)
# annotator = models.ForeignKey(User, on_delete=models.CASCADE)
# submission_time = models.DateTimeField(default=timezone.now)
#
# class AnnotationUpdate(models.Model):
# """
# Each record is an update of an annotation submitted by a judger.
# """
# annotation = models.ForeignKey(Annotation, on_delete=models.CASCADE)
# judger = models.ForeignKey(User, on_delete=models.CASCADE)
# update_str = models.TextField()
# update_type = models.TextField(default='nl')
# comment = models.ForeignKey(Comment, on_delete=models.CASCADE)
# submission_time = models.DateTimeField(default=timezone.now)
# status = models.TextField(default='open')
#
# class Command(models.Model):
# """
# Command line.
# """
# str = models.TextField(primary_key=True)
# template = models.TextField(default='')
# language = models.TextField(default='bash')
# tags = models.ManyToManyField('Tag')
#
# class Notification(models.Model):
# """
# Each record is a certain type of message issued from one annotator to
# another.
# """
# sender = models.ForeignKey(User, related_name='notification_sender',
# on_delete=models.CASCADE)
# receiver = models.ForeignKey(User, related_name='notification_receiver',
# on_delete=models.CASCADE)
# type = models.TextField(default='comment')
# annotation_update = models.ForeignKey('AnnotationUpdate', null=True,
# on_delete=models.CASCADE)
# comment = models.ForeignKey('Comment', null=True, on_delete=models.CASCADE)
# url = models.ForeignKey('URL', on_delete=models.CASCADE)
# creation_time = models.DateTimeField(default=timezone.now)
# status = models.TextField(default='issued')
#
# class URL(models.Model):
# """
# URL.
#
# :member str: url address.
# :member html_content: snapshot of the URL content at the time of annotation.
# :member commands: commands in the URL (automatically extracted)
# :member tags: tags of the URL (assigned based on user annotations)
# """
# str = models.TextField(primary_key=True)
# html_content = models.TextField(default='')
# commands = models.ManyToManyField('Command')
# tags = models.ManyToManyField('Tag')
#
# class URLTag(models.Model):
# """
# Each record stores a (url, tag) pair.
# """
# url = models.ForeignKey(URL, on_delete=models.CASCADE)
# tag = models.TextField()
#
# Path: website/utils.py
# def get_tag(tag_str):
# tag, _ = Tag.objects.get_or_create(str=tag_str.strip())
# return tag
#
# def get_command(command_str):
# command_str=command_str.strip()
# if Command.objects.filter(str=command_str).exists():
# cmd = Command.objects.get(str=command_str)
# else:
# cmd = Command.objects.create(str=command_str)
# ast = data_tools.bash_parser(command_str)
# for utility in data_tools.get_utilities(ast):
# cmd.tags.add(get_tag(utility))
# template = data_tools.ast2template(
# ast, loose_constraints=True)
# cmd.template = template
# cmd.save()
# return cmd
#
# def get_url(url_str):
# url_str = url_str.strip()
# try:
# url = URL.objects.get(str=url_str)
# except ObjectDoesNotExist:
# html = extract_html(url_str)
# if html is None:
# url = URL.objects.create(str=url_str)
# else:
# url = URL.objects.create(str=url_str, html_content=html)
# return url
. Output only the next line. | with open(input_file_path, 'rb') as f: |
Given the following code snippet before the placeholder: <|code_start|>
learning_module_dir = os.path.join(os.path.dirname(__file__), '..', '..',
"tellina_learning_module")
sys.path.append(learning_module_dir)
CODE_REGEX = re.compile(r"<pre><code>([^<]+\n[^<]*)<\/code><\/pre>")
def extract_code(text):
for match in CODE_REGEX.findall(text):
if match.strip():
yield html.unescape(match.replace("<br>", "\n"))
def extract_oneliners_from_code(code_block):
for cmd in code_block.splitlines():
if cmd.startswith('$ '):
cmd = cmd[2:]
if cmd.startswith('# '):
cmd = cmd[2:]
comment = re.search(r'\s+#\s+', cmd)
if comment:
old_cmd = cmd
<|code_end|>
, predict the next line using imports from the current file:
import html
import os, sys
import pickle
import re
import sqlite3
from website.models import Annotation, AnnotationUpdate, Command, \
Notification, URL, URLTag
from website.utils import get_tag, get_command, get_url
from bashlint import data_tools
and context including class names, function names, and sometimes code from other files:
# Path: website/models.py
# class Annotation(models.Model):
# """
# Each record is a natural language <-> code translation annotated by a
# programmer.
# """
# url = models.ForeignKey(URL, on_delete=models.CASCADE)
# nl = models.ForeignKey(NL, on_delete=models.CASCADE)
# cmd = models.ForeignKey(Command, on_delete=models.CASCADE)
# annotator = models.ForeignKey(User, on_delete=models.CASCADE)
# submission_time = models.DateTimeField(default=timezone.now)
#
# class AnnotationUpdate(models.Model):
# """
# Each record is an update of an annotation submitted by a judger.
# """
# annotation = models.ForeignKey(Annotation, on_delete=models.CASCADE)
# judger = models.ForeignKey(User, on_delete=models.CASCADE)
# update_str = models.TextField()
# update_type = models.TextField(default='nl')
# comment = models.ForeignKey(Comment, on_delete=models.CASCADE)
# submission_time = models.DateTimeField(default=timezone.now)
# status = models.TextField(default='open')
#
# class Command(models.Model):
# """
# Command line.
# """
# str = models.TextField(primary_key=True)
# template = models.TextField(default='')
# language = models.TextField(default='bash')
# tags = models.ManyToManyField('Tag')
#
# class Notification(models.Model):
# """
# Each record is a certain type of message issued from one annotator to
# another.
# """
# sender = models.ForeignKey(User, related_name='notification_sender',
# on_delete=models.CASCADE)
# receiver = models.ForeignKey(User, related_name='notification_receiver',
# on_delete=models.CASCADE)
# type = models.TextField(default='comment')
# annotation_update = models.ForeignKey('AnnotationUpdate', null=True,
# on_delete=models.CASCADE)
# comment = models.ForeignKey('Comment', null=True, on_delete=models.CASCADE)
# url = models.ForeignKey('URL', on_delete=models.CASCADE)
# creation_time = models.DateTimeField(default=timezone.now)
# status = models.TextField(default='issued')
#
# class URL(models.Model):
# """
# URL.
#
# :member str: url address.
# :member html_content: snapshot of the URL content at the time of annotation.
# :member commands: commands in the URL (automatically extracted)
# :member tags: tags of the URL (assigned based on user annotations)
# """
# str = models.TextField(primary_key=True)
# html_content = models.TextField(default='')
# commands = models.ManyToManyField('Command')
# tags = models.ManyToManyField('Tag')
#
# class URLTag(models.Model):
# """
# Each record stores a (url, tag) pair.
# """
# url = models.ForeignKey(URL, on_delete=models.CASCADE)
# tag = models.TextField()
#
# Path: website/utils.py
# def get_tag(tag_str):
# tag, _ = Tag.objects.get_or_create(str=tag_str.strip())
# return tag
#
# def get_command(command_str):
# command_str=command_str.strip()
# if Command.objects.filter(str=command_str).exists():
# cmd = Command.objects.get(str=command_str)
# else:
# cmd = Command.objects.create(str=command_str)
# ast = data_tools.bash_parser(command_str)
# for utility in data_tools.get_utilities(ast):
# cmd.tags.add(get_tag(utility))
# template = data_tools.ast2template(
# ast, loose_constraints=True)
# cmd.template = template
# cmd.save()
# return cmd
#
# def get_url(url_str):
# url_str = url_str.strip()
# try:
# url = URL.objects.get(str=url_str)
# except ObjectDoesNotExist:
# html = extract_html(url_str)
# if html is None:
# url = URL.objects.create(str=url_str)
# else:
# url = URL.objects.create(str=url_str, html_content=html)
# return url
. Output only the next line. | cmd = cmd[:comment.start()] |
Using the snippet: <|code_start|> if cmd.startswith('# '):
cmd = cmd[2:]
comment = re.search(r'\s+#\s+', cmd)
if comment:
old_cmd = cmd
cmd = cmd[:comment.start()]
print('Remove comment: {} -> {}'.format(old_cmd, cmd))
cmd = cmd.strip()
# discard code block opening line
if cmd and not cmd[-1] in ['{', '[', '(']:
yield cmd
def load_urls(input_file_path):
with open(input_file_path, 'rb') as f:
urls_by_utility = pickle.load(f)
for utility in urls_by_utility:
for url in urls_by_utility[utility]:
if not URLTag.objects.filter(url__str=url, tag=utility):
URLTag.objects.create(url=get_url(url), tag=utility)
print("Add {}, {}".format(url, utility))
def load_commands_in_url(stackoverflow_dump_path):
url_prefix = 'https://stackoverflow.com/questions/'
with sqlite3.connect(stackoverflow_dump_path,
detect_types=sqlite3.PARSE_DECLTYPES) as db:
for url in URL.objects.all():
# url = URL.objects.get(str='https://stackoverflow.com/questions/127669')
url.commands.clear()
<|code_end|>
, determine the next line of code. You have imports:
import html
import os, sys
import pickle
import re
import sqlite3
from website.models import Annotation, AnnotationUpdate, Command, \
Notification, URL, URLTag
from website.utils import get_tag, get_command, get_url
from bashlint import data_tools
and context (class names, function names, or code) available:
# Path: website/models.py
# class Annotation(models.Model):
# """
# Each record is a natural language <-> code translation annotated by a
# programmer.
# """
# url = models.ForeignKey(URL, on_delete=models.CASCADE)
# nl = models.ForeignKey(NL, on_delete=models.CASCADE)
# cmd = models.ForeignKey(Command, on_delete=models.CASCADE)
# annotator = models.ForeignKey(User, on_delete=models.CASCADE)
# submission_time = models.DateTimeField(default=timezone.now)
#
# class AnnotationUpdate(models.Model):
# """
# Each record is an update of an annotation submitted by a judger.
# """
# annotation = models.ForeignKey(Annotation, on_delete=models.CASCADE)
# judger = models.ForeignKey(User, on_delete=models.CASCADE)
# update_str = models.TextField()
# update_type = models.TextField(default='nl')
# comment = models.ForeignKey(Comment, on_delete=models.CASCADE)
# submission_time = models.DateTimeField(default=timezone.now)
# status = models.TextField(default='open')
#
# class Command(models.Model):
# """
# Command line.
# """
# str = models.TextField(primary_key=True)
# template = models.TextField(default='')
# language = models.TextField(default='bash')
# tags = models.ManyToManyField('Tag')
#
# class Notification(models.Model):
# """
# Each record is a certain type of message issued from one annotator to
# another.
# """
# sender = models.ForeignKey(User, related_name='notification_sender',
# on_delete=models.CASCADE)
# receiver = models.ForeignKey(User, related_name='notification_receiver',
# on_delete=models.CASCADE)
# type = models.TextField(default='comment')
# annotation_update = models.ForeignKey('AnnotationUpdate', null=True,
# on_delete=models.CASCADE)
# comment = models.ForeignKey('Comment', null=True, on_delete=models.CASCADE)
# url = models.ForeignKey('URL', on_delete=models.CASCADE)
# creation_time = models.DateTimeField(default=timezone.now)
# status = models.TextField(default='issued')
#
# class URL(models.Model):
# """
# URL.
#
# :member str: url address.
# :member html_content: snapshot of the URL content at the time of annotation.
# :member commands: commands in the URL (automatically extracted)
# :member tags: tags of the URL (assigned based on user annotations)
# """
# str = models.TextField(primary_key=True)
# html_content = models.TextField(default='')
# commands = models.ManyToManyField('Command')
# tags = models.ManyToManyField('Tag')
#
# class URLTag(models.Model):
# """
# Each record stores a (url, tag) pair.
# """
# url = models.ForeignKey(URL, on_delete=models.CASCADE)
# tag = models.TextField()
#
# Path: website/utils.py
# def get_tag(tag_str):
# tag, _ = Tag.objects.get_or_create(str=tag_str.strip())
# return tag
#
# def get_command(command_str):
# command_str=command_str.strip()
# if Command.objects.filter(str=command_str).exists():
# cmd = Command.objects.get(str=command_str)
# else:
# cmd = Command.objects.create(str=command_str)
# ast = data_tools.bash_parser(command_str)
# for utility in data_tools.get_utilities(ast):
# cmd.tags.add(get_tag(utility))
# template = data_tools.ast2template(
# ast, loose_constraints=True)
# cmd.template = template
# cmd.save()
# return cmd
#
# def get_url(url_str):
# url_str = url_str.strip()
# try:
# url = URL.objects.get(str=url_str)
# except ObjectDoesNotExist:
# html = extract_html(url_str)
# if html is None:
# url = URL.objects.create(str=url_str)
# else:
# url = URL.objects.create(str=url_str, html_content=html)
# return url
. Output only the next line. | print(url.str) |
Given the following code snippet before the placeholder: <|code_start|> url.html_content = answer_body
for code_block in extract_code(url.html_content):
for cmd in extract_oneliners_from_code(code_block):
ast = data_tools.bash_parser(cmd)
if ast:
command = get_command(cmd)
print('extracted: {}'.format(cmd))
url.commands.add(command)
url.save()
def populate_command_tags():
for cmd in Command.objects.all():
if len(cmd.str) > 600:
cmd.delete()
else:
cmd.tags.clear()
print(cmd.str)
ast = data_tools.bash_parser(cmd.str)
for utility in data_tools.get_utilities(ast):
print(utility)
cmd.tags.add(get_tag(utility))
cmd.save()
def populate_command_template():
for cmd in Command.objects.all():
if len(cmd.str) > 600:
cmd.delete()
else:
ast = data_tools.bash_parser(cmd.str)
template = data_tools.ast2template(ast, loose_constraints=True)
<|code_end|>
, predict the next line using imports from the current file:
import html
import os, sys
import pickle
import re
import sqlite3
from website.models import Annotation, AnnotationUpdate, Command, \
Notification, URL, URLTag
from website.utils import get_tag, get_command, get_url
from bashlint import data_tools
and context including class names, function names, and sometimes code from other files:
# Path: website/models.py
# class Annotation(models.Model):
# """
# Each record is a natural language <-> code translation annotated by a
# programmer.
# """
# url = models.ForeignKey(URL, on_delete=models.CASCADE)
# nl = models.ForeignKey(NL, on_delete=models.CASCADE)
# cmd = models.ForeignKey(Command, on_delete=models.CASCADE)
# annotator = models.ForeignKey(User, on_delete=models.CASCADE)
# submission_time = models.DateTimeField(default=timezone.now)
#
# class AnnotationUpdate(models.Model):
# """
# Each record is an update of an annotation submitted by a judger.
# """
# annotation = models.ForeignKey(Annotation, on_delete=models.CASCADE)
# judger = models.ForeignKey(User, on_delete=models.CASCADE)
# update_str = models.TextField()
# update_type = models.TextField(default='nl')
# comment = models.ForeignKey(Comment, on_delete=models.CASCADE)
# submission_time = models.DateTimeField(default=timezone.now)
# status = models.TextField(default='open')
#
# class Command(models.Model):
# """
# Command line.
# """
# str = models.TextField(primary_key=True)
# template = models.TextField(default='')
# language = models.TextField(default='bash')
# tags = models.ManyToManyField('Tag')
#
# class Notification(models.Model):
# """
# Each record is a certain type of message issued from one annotator to
# another.
# """
# sender = models.ForeignKey(User, related_name='notification_sender',
# on_delete=models.CASCADE)
# receiver = models.ForeignKey(User, related_name='notification_receiver',
# on_delete=models.CASCADE)
# type = models.TextField(default='comment')
# annotation_update = models.ForeignKey('AnnotationUpdate', null=True,
# on_delete=models.CASCADE)
# comment = models.ForeignKey('Comment', null=True, on_delete=models.CASCADE)
# url = models.ForeignKey('URL', on_delete=models.CASCADE)
# creation_time = models.DateTimeField(default=timezone.now)
# status = models.TextField(default='issued')
#
# class URL(models.Model):
# """
# URL.
#
# :member str: url address.
# :member html_content: snapshot of the URL content at the time of annotation.
# :member commands: commands in the URL (automatically extracted)
# :member tags: tags of the URL (assigned based on user annotations)
# """
# str = models.TextField(primary_key=True)
# html_content = models.TextField(default='')
# commands = models.ManyToManyField('Command')
# tags = models.ManyToManyField('Tag')
#
# class URLTag(models.Model):
# """
# Each record stores a (url, tag) pair.
# """
# url = models.ForeignKey(URL, on_delete=models.CASCADE)
# tag = models.TextField()
#
# Path: website/utils.py
# def get_tag(tag_str):
# tag, _ = Tag.objects.get_or_create(str=tag_str.strip())
# return tag
#
# def get_command(command_str):
# command_str=command_str.strip()
# if Command.objects.filter(str=command_str).exists():
# cmd = Command.objects.get(str=command_str)
# else:
# cmd = Command.objects.create(str=command_str)
# ast = data_tools.bash_parser(command_str)
# for utility in data_tools.get_utilities(ast):
# cmd.tags.add(get_tag(utility))
# template = data_tools.ast2template(
# ast, loose_constraints=True)
# cmd.template = template
# cmd.save()
# return cmd
#
# def get_url(url_str):
# url_str = url_str.strip()
# try:
# url = URL.objects.get(str=url_str)
# except ObjectDoesNotExist:
# html = extract_html(url_str)
# if html is None:
# url = URL.objects.create(str=url_str)
# else:
# url = URL.objects.create(str=url_str, html_content=html)
# return url
. Output only the next line. | cmd.template = template |
Here is a snippet: <|code_start|> cmd.tags.add(get_tag(utility))
cmd.save()
def populate_command_template():
for cmd in Command.objects.all():
if len(cmd.str) > 600:
cmd.delete()
else:
ast = data_tools.bash_parser(cmd.str)
template = data_tools.ast2template(ast, loose_constraints=True)
cmd.template = template
cmd.save()
def populate_tag_commands():
for tag in Tag.objects.all():
tag.commands.clear()
for url_tag in URLTag.objects.all():
print(url_tag.url.str)
tag = get_tag(url_tag.tag)
for cmd in url_tag.url.commands.all():
if tag in cmd.tags.all():
tag.commands.add(cmd)
tag.save()
def populate_url_tags():
for url in URL.objects.all():
for annotation in Annotation.objects.filter(url=url):
for tag in annotation.cmd.tags.all():
url.tags.add(tag)
<|code_end|>
. Write the next line using the current file imports:
import html
import os, sys
import pickle
import re
import sqlite3
from website.models import Annotation, AnnotationUpdate, Command, \
Notification, URL, URLTag
from website.utils import get_tag, get_command, get_url
from bashlint import data_tools
and context from other files:
# Path: website/models.py
# class Annotation(models.Model):
# """
# Each record is a natural language <-> code translation annotated by a
# programmer.
# """
# url = models.ForeignKey(URL, on_delete=models.CASCADE)
# nl = models.ForeignKey(NL, on_delete=models.CASCADE)
# cmd = models.ForeignKey(Command, on_delete=models.CASCADE)
# annotator = models.ForeignKey(User, on_delete=models.CASCADE)
# submission_time = models.DateTimeField(default=timezone.now)
#
# class AnnotationUpdate(models.Model):
# """
# Each record is an update of an annotation submitted by a judger.
# """
# annotation = models.ForeignKey(Annotation, on_delete=models.CASCADE)
# judger = models.ForeignKey(User, on_delete=models.CASCADE)
# update_str = models.TextField()
# update_type = models.TextField(default='nl')
# comment = models.ForeignKey(Comment, on_delete=models.CASCADE)
# submission_time = models.DateTimeField(default=timezone.now)
# status = models.TextField(default='open')
#
# class Command(models.Model):
# """
# Command line.
# """
# str = models.TextField(primary_key=True)
# template = models.TextField(default='')
# language = models.TextField(default='bash')
# tags = models.ManyToManyField('Tag')
#
# class Notification(models.Model):
# """
# Each record is a certain type of message issued from one annotator to
# another.
# """
# sender = models.ForeignKey(User, related_name='notification_sender',
# on_delete=models.CASCADE)
# receiver = models.ForeignKey(User, related_name='notification_receiver',
# on_delete=models.CASCADE)
# type = models.TextField(default='comment')
# annotation_update = models.ForeignKey('AnnotationUpdate', null=True,
# on_delete=models.CASCADE)
# comment = models.ForeignKey('Comment', null=True, on_delete=models.CASCADE)
# url = models.ForeignKey('URL', on_delete=models.CASCADE)
# creation_time = models.DateTimeField(default=timezone.now)
# status = models.TextField(default='issued')
#
# class URL(models.Model):
# """
# URL.
#
# :member str: url address.
# :member html_content: snapshot of the URL content at the time of annotation.
# :member commands: commands in the URL (automatically extracted)
# :member tags: tags of the URL (assigned based on user annotations)
# """
# str = models.TextField(primary_key=True)
# html_content = models.TextField(default='')
# commands = models.ManyToManyField('Command')
# tags = models.ManyToManyField('Tag')
#
# class URLTag(models.Model):
# """
# Each record stores a (url, tag) pair.
# """
# url = models.ForeignKey(URL, on_delete=models.CASCADE)
# tag = models.TextField()
#
# Path: website/utils.py
# def get_tag(tag_str):
# tag, _ = Tag.objects.get_or_create(str=tag_str.strip())
# return tag
#
# def get_command(command_str):
# command_str=command_str.strip()
# if Command.objects.filter(str=command_str).exists():
# cmd = Command.objects.get(str=command_str)
# else:
# cmd = Command.objects.create(str=command_str)
# ast = data_tools.bash_parser(command_str)
# for utility in data_tools.get_utilities(ast):
# cmd.tags.add(get_tag(utility))
# template = data_tools.ast2template(
# ast, loose_constraints=True)
# cmd.template = template
# cmd.save()
# return cmd
#
# def get_url(url_str):
# url_str = url_str.strip()
# try:
# url = URL.objects.get(str=url_str)
# except ObjectDoesNotExist:
# html = extract_html(url_str)
# if html is None:
# url = URL.objects.create(str=url_str)
# else:
# url = URL.objects.create(str=url_str, html_content=html)
# return url
, which may include functions, classes, or code. Output only the next line. | def populate_tag_annotations(): |
Here is a snippet: <|code_start|> if Command.objects.filter(str=command_str).exists():
cmd = Command.objects.get(str=command_str)
else:
cmd = Command.objects.create(str=command_str)
ast = data_tools.bash_parser(command_str)
for utility in data_tools.get_utilities(ast):
cmd.tags.add(get_tag(utility))
template = data_tools.ast2template(
ast, loose_constraints=True)
cmd.template = template
cmd.save()
return cmd
def get_tag(tag_str):
tag, _ = Tag.objects.get_or_create(str=tag_str.strip())
return tag
def get_url(url_str):
url_str = url_str.strip()
try:
url = URL.objects.get(str=url_str)
except ObjectDoesNotExist:
html = extract_html(url_str)
if html is None:
url = URL.objects.create(str=url_str)
else:
url = URL.objects.create(str=url_str, html_content=html)
return url
def json_response(d={}, status='SUCCESS'):
<|code_end|>
. Write the next line using the current file imports:
import os, sys
import socket
import ssl
import time
import urllib
from django.core.exceptions import ObjectDoesNotExist
from django.http import JsonResponse
from website.models import NL, Command, Tag, URL
from bashlint import data_tools
and context from other files:
# Path: website/models.py
# class NL(models.Model):
# """
# Natural language command.
# """
# str = models.TextField(primary_key=True)
#
# class Command(models.Model):
# """
# Command line.
# """
# str = models.TextField(primary_key=True)
# template = models.TextField(default='')
# language = models.TextField(default='bash')
# tags = models.ManyToManyField('Tag')
#
# class Tag(models.Model):
# """
# Tag.
# """
# str = models.TextField(primary_key=True)
# commands = models.ManyToManyField('Command')
# annotations = models.ManyToManyField('Annotation')
#
# class URL(models.Model):
# """
# URL.
#
# :member str: url address.
# :member html_content: snapshot of the URL content at the time of annotation.
# :member commands: commands in the URL (automatically extracted)
# :member tags: tags of the URL (assigned based on user annotations)
# """
# str = models.TextField(primary_key=True)
# html_content = models.TextField(default='')
# commands = models.ManyToManyField('Command')
# tags = models.ManyToManyField('Tag')
, which may include functions, classes, or code. Output only the next line. | d.update({'status': status}) |
Predict the next line for this snippet: <|code_start|> html = urllib.request.urlopen(hypothes_prefix + url, timeout=2)
except urllib.error.URLError:
print("Error: extract_text_from_url() urllib2.URLError")
# return "", randomstr(180)
return None, None
except socket.timeout:
print("Error: extract_text_from_url() socket.timeout")
# return "", randomstr(180)
return None, None
except ssl.SSLError:
print("Error: extract_text_from_url() ssl.SSLError")
# return "", randomstr(180)
return None, None
return html.read()
def get_nl(nl_str):
nl, _ = NL.objects.get_or_create(str=nl_str.strip())
return nl
def get_command(command_str):
command_str=command_str.strip()
if Command.objects.filter(str=command_str).exists():
cmd = Command.objects.get(str=command_str)
else:
cmd = Command.objects.create(str=command_str)
ast = data_tools.bash_parser(command_str)
for utility in data_tools.get_utilities(ast):
cmd.tags.add(get_tag(utility))
template = data_tools.ast2template(
ast, loose_constraints=True)
<|code_end|>
with the help of current file imports:
import os, sys
import socket
import ssl
import time
import urllib
from django.core.exceptions import ObjectDoesNotExist
from django.http import JsonResponse
from website.models import NL, Command, Tag, URL
from bashlint import data_tools
and context from other files:
# Path: website/models.py
# class NL(models.Model):
# """
# Natural language command.
# """
# str = models.TextField(primary_key=True)
#
# class Command(models.Model):
# """
# Command line.
# """
# str = models.TextField(primary_key=True)
# template = models.TextField(default='')
# language = models.TextField(default='bash')
# tags = models.ManyToManyField('Tag')
#
# class Tag(models.Model):
# """
# Tag.
# """
# str = models.TextField(primary_key=True)
# commands = models.ManyToManyField('Command')
# annotations = models.ManyToManyField('Annotation')
#
# class URL(models.Model):
# """
# URL.
#
# :member str: url address.
# :member html_content: snapshot of the URL content at the time of annotation.
# :member commands: commands in the URL (automatically extracted)
# :member tags: tags of the URL (assigned based on user annotations)
# """
# str = models.TextField(primary_key=True)
# html_content = models.TextField(default='')
# commands = models.ManyToManyField('Command')
# tags = models.ManyToManyField('Tag')
, which may contain function names, class names, or code. Output only the next line. | cmd.template = template |
Continue the code snippet: <|code_start|> return None, None
except ssl.SSLError:
print("Error: extract_text_from_url() ssl.SSLError")
# return "", randomstr(180)
return None, None
return html.read()
def get_nl(nl_str):
nl, _ = NL.objects.get_or_create(str=nl_str.strip())
return nl
def get_command(command_str):
command_str=command_str.strip()
if Command.objects.filter(str=command_str).exists():
cmd = Command.objects.get(str=command_str)
else:
cmd = Command.objects.create(str=command_str)
ast = data_tools.bash_parser(command_str)
for utility in data_tools.get_utilities(ast):
cmd.tags.add(get_tag(utility))
template = data_tools.ast2template(
ast, loose_constraints=True)
cmd.template = template
cmd.save()
return cmd
def get_tag(tag_str):
tag, _ = Tag.objects.get_or_create(str=tag_str.strip())
return tag
<|code_end|>
. Use current file imports:
import os, sys
import socket
import ssl
import time
import urllib
from django.core.exceptions import ObjectDoesNotExist
from django.http import JsonResponse
from website.models import NL, Command, Tag, URL
from bashlint import data_tools
and context (classes, functions, or code) from other files:
# Path: website/models.py
# class NL(models.Model):
# """
# Natural language command.
# """
# str = models.TextField(primary_key=True)
#
# class Command(models.Model):
# """
# Command line.
# """
# str = models.TextField(primary_key=True)
# template = models.TextField(default='')
# language = models.TextField(default='bash')
# tags = models.ManyToManyField('Tag')
#
# class Tag(models.Model):
# """
# Tag.
# """
# str = models.TextField(primary_key=True)
# commands = models.ManyToManyField('Command')
# annotations = models.ManyToManyField('Annotation')
#
# class URL(models.Model):
# """
# URL.
#
# :member str: url address.
# :member html_content: snapshot of the URL content at the time of annotation.
# :member commands: commands in the URL (automatically extracted)
# :member tags: tags of the URL (assigned based on user annotations)
# """
# str = models.TextField(primary_key=True)
# html_content = models.TextField(default='')
# commands = models.ManyToManyField('Command')
# tags = models.ManyToManyField('Tag')
. Output only the next line. | def get_url(url_str): |
Predict the next line for this snippet: <|code_start|>
sys.path.append(os.path.join(
os.path.dirname(__file__), "..", "tellina_learning_module"))
# Number of translations to show
NUM_TRANSLATIONS = 20
def extract_html(url):
hypothes_prefix = "https://via.hypothes.is/"
<|code_end|>
with the help of current file imports:
import os, sys
import socket
import ssl
import time
import urllib
from django.core.exceptions import ObjectDoesNotExist
from django.http import JsonResponse
from website.models import NL, Command, Tag, URL
from bashlint import data_tools
and context from other files:
# Path: website/models.py
# class NL(models.Model):
# """
# Natural language command.
# """
# str = models.TextField(primary_key=True)
#
# class Command(models.Model):
# """
# Command line.
# """
# str = models.TextField(primary_key=True)
# template = models.TextField(default='')
# language = models.TextField(default='bash')
# tags = models.ManyToManyField('Tag')
#
# class Tag(models.Model):
# """
# Tag.
# """
# str = models.TextField(primary_key=True)
# commands = models.ManyToManyField('Command')
# annotations = models.ManyToManyField('Annotation')
#
# class URL(models.Model):
# """
# URL.
#
# :member str: url address.
# :member html_content: snapshot of the URL content at the time of annotation.
# :member commands: commands in the URL (automatically extracted)
# :member tags: tags of the URL (assigned based on user annotations)
# """
# str = models.TextField(primary_key=True)
# html_content = models.TextField(default='')
# commands = models.ManyToManyField('Command')
# tags = models.ManyToManyField('Tag')
, which may contain function names, class names, or code. Output only the next line. | try: |
Based on the snippet: <|code_start|>
@view_config(route_name='crash_investigate', renderer='views/crash.mako', request_method='GET')
def investigate_crash(request):
intersections = _get_intersections(request, False)
return {
'intersections': json.dumps([i for i in intersections if 'loc' in i])
}
@view_config(route_name='accidents', renderer='bson')
def get_accident_near_json(request):
args = request.matchdict
request.response.content_type = 'application/json'
intersection, time_start, time_end = args['intersection'], du(args['time_start']), du(args['time_end'])
radius = int(args['radius'])
return get_accident_near(time_start, time_end, intersection, radius, request)
@view_config(route_name='crash_investigate', renderer='bson', request_method='POST')
<|code_end|>
, predict the immediate next line with the help of imports:
import json
from datetime import timedelta, datetime
from geopy.distance import geodesic
from .util import du, get_accident_near
from .intersection import _get_intersections
from pluck import pluck
from pyramid.view import view_config
and context (classes, functions, sometimes code) from other files:
# Path: htm-site/htmsite/util.py
# def du(unix):
# return datetime.utcfromtimestamp(float(unix))
#
# def get_accident_near(time_start, time_end, intersection, radius=150, request=None):
# """
# Return any accidents at this time,
# should probably be listed in the app
# :param time:
# :param intersection:
# :return:
# """
#
# crashes = request.db.crashes
# locations = request.db.locations
# location = locations.find_one({'site_no': intersection})
# # timestamp = datetime.utcfromtimestamp(float(time))
# # delta = timedelta(minutes=30)
# query = {
# 'loc': {
# '$geoNear': {
# '$geometry': location['loc'],
# '$maxDistance': radius
# }
# },
# }
# if time_start is not None:
# query['datetime'] = {
# '$gte': time_start,
# '$lte': time_end
# }
#
# return list(crashes.find(query).sort('datetime', pymongo.ASCENDING)), radius
#
# Path: htm-site/htmsite/intersection.py
# def _get_intersections(request, images=True):
# """
# Get the signalised intersections for Adelaide
# :return: a cursor of documents of signalised intersections
# """
# exclude = {'_id': False}
# if not images:
# exclude['scats_diagram'] = False
# return request.db.locations.find({'site_no': {'$exists': True}}, exclude)
. Output only the next line. | def crash_in_polygon(request): |
Given snippet: <|code_start|>
@view_config(route_name='crash_investigate', renderer='views/crash.mako', request_method='GET')
def investigate_crash(request):
intersections = _get_intersections(request, False)
return {
'intersections': json.dumps([i for i in intersections if 'loc' in i])
}
@view_config(route_name='accidents', renderer='bson')
def get_accident_near_json(request):
args = request.matchdict
request.response.content_type = 'application/json'
intersection, time_start, time_end = args['intersection'], du(args['time_start']), du(args['time_end'])
radius = int(args['radius'])
return get_accident_near(time_start, time_end, intersection, radius, request)
@view_config(route_name='crash_investigate', renderer='bson', request_method='POST')
def crash_in_polygon(request):
readings_coll = request.db.scats_readings
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import json
from datetime import timedelta, datetime
from geopy.distance import geodesic
from .util import du, get_accident_near
from .intersection import _get_intersections
from pluck import pluck
from pyramid.view import view_config
and context:
# Path: htm-site/htmsite/util.py
# def du(unix):
# return datetime.utcfromtimestamp(float(unix))
#
# def get_accident_near(time_start, time_end, intersection, radius=150, request=None):
# """
# Return any accidents at this time,
# should probably be listed in the app
# :param time:
# :param intersection:
# :return:
# """
#
# crashes = request.db.crashes
# locations = request.db.locations
# location = locations.find_one({'site_no': intersection})
# # timestamp = datetime.utcfromtimestamp(float(time))
# # delta = timedelta(minutes=30)
# query = {
# 'loc': {
# '$geoNear': {
# '$geometry': location['loc'],
# '$maxDistance': radius
# }
# },
# }
# if time_start is not None:
# query['datetime'] = {
# '$gte': time_start,
# '$lte': time_end
# }
#
# return list(crashes.find(query).sort('datetime', pymongo.ASCENDING)), radius
#
# Path: htm-site/htmsite/intersection.py
# def _get_intersections(request, images=True):
# """
# Get the signalised intersections for Adelaide
# :return: a cursor of documents of signalised intersections
# """
# exclude = {'_id': False}
# if not images:
# exclude['scats_diagram'] = False
# return request.db.locations.find({'site_no': {'$exists': True}}, exclude)
which might include code, classes, or functions. Output only the next line. | crashes_coll = request.db.crashes |
Based on the snippet: <|code_start|>
@view_config(route_name='crash_investigate', renderer='views/crash.mako', request_method='GET')
def investigate_crash(request):
intersections = _get_intersections(request, False)
return {
'intersections': json.dumps([i for i in intersections if 'loc' in i])
}
@view_config(route_name='accidents', renderer='bson')
def get_accident_near_json(request):
args = request.matchdict
<|code_end|>
, predict the immediate next line with the help of imports:
import json
from datetime import timedelta, datetime
from geopy.distance import geodesic
from .util import du, get_accident_near
from .intersection import _get_intersections
from pluck import pluck
from pyramid.view import view_config
and context (classes, functions, sometimes code) from other files:
# Path: htm-site/htmsite/util.py
# def du(unix):
# return datetime.utcfromtimestamp(float(unix))
#
# def get_accident_near(time_start, time_end, intersection, radius=150, request=None):
# """
# Return any accidents at this time,
# should probably be listed in the app
# :param time:
# :param intersection:
# :return:
# """
#
# crashes = request.db.crashes
# locations = request.db.locations
# location = locations.find_one({'site_no': intersection})
# # timestamp = datetime.utcfromtimestamp(float(time))
# # delta = timedelta(minutes=30)
# query = {
# 'loc': {
# '$geoNear': {
# '$geometry': location['loc'],
# '$maxDistance': radius
# }
# },
# }
# if time_start is not None:
# query['datetime'] = {
# '$gte': time_start,
# '$lte': time_end
# }
#
# return list(crashes.find(query).sort('datetime', pymongo.ASCENDING)), radius
#
# Path: htm-site/htmsite/intersection.py
# def _get_intersections(request, images=True):
# """
# Get the signalised intersections for Adelaide
# :return: a cursor of documents of signalised intersections
# """
# exclude = {'_id': False}
# if not images:
# exclude['scats_diagram'] = False
# return request.db.locations.find({'site_no': {'$exists': True}}, exclude)
. Output only the next line. | request.response.content_type = 'application/json' |
Predict the next line for this snippet: <|code_start|> http403.status = 403
return http403
form = EditUserForm(request.POST or None, user=request.user)
if form.is_valid():
for key, value in form.cleaned_data.iteritems():
if key in ['gittip']:
continue
if key in ['email']:
# send verification email
domain = get_current_site(request).domain
if value is not None:
send_verify_email(value, user.pk, domain)
# Don't actually add email to user model.
continue
if key == 'team':
# slugify the team to allow easy lookups
setattr(user, 'team_slug', slugify(value))
setattr(user, key, value)
user.save()
return HttpResponseRedirect(
reverse('member-profile', kwargs={'username': user.username}))
ctx = {
'form': form,
'profile': user,
'active': 'edit',
}
<|code_end|>
with the help of current file imports:
import logging
import json
from django.http import Http404, HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.shortcuts import render_to_response, render, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.template.context import RequestContext
from django.template.defaultfilters import slugify
from django.views.generic import detail
from django.utils.crypto import salted_hmac
from django.utils.translation import ugettext_lazy as _
from django.utils.http import int_to_base36
from django.utils.html import strip_tags
from django.core.mail import EmailMultiAlternatives, mail_admins
from django.template import loader
from django.contrib.sites.models import get_current_site
from social_auth.models import UserSocialAuth
from july.settings import SECRET_KEY as SECRET
from july.models import User
from forms import EditUserForm
from forms import EditAddressForm
and context from other files:
# Path: july/settings.py
# SECRET_KEY = 'foobar'
#
# Path: july/models.py
# class User(AbstractUser):
# location = models.ForeignKey(Location, blank=True, null=True,
# related_name='location_members')
# team = models.ForeignKey(Team, blank=True, null=True,
# related_name='team_members')
# projects = models.ManyToManyField(Project, blank=True, null=True)
# description = models.TextField(blank=True)
# url = models.URLField(blank=True, null=True)
# picture_url = models.URLField(blank=True, null=True)
#
# def __unicode__(self):
# return self.get_full_name() or self.username
#
# def add_auth_id(self, auth_str):
# """
# Add a social auth identifier for this user.
#
# The `auth_str` should be in the format '{provider}:{uid}'
# this is useful for adding multiple unique email addresses.
#
# Example::
#
# user = User.objects.get(username='foo')
# user.add_auth_id('email:foo@example.com')
# """
# provider, uid = auth_str.split(':')
# return UserSocialAuth.create_social_auth(self, uid, provider)
#
# def add_auth_email(self, email, request=None):
# """
# Adds a new, non verified email address, and sends a verification email.
# """
# auth_email = self.add_auth_id('email:%s' % email)
# auth_email.extra_data = {'verified': False}
# auth_email.save()
# return auth_email
#
# def get_provider(self, provider):
# """Return the uid of the provider or None if not set."""
# try:
# return self.social_auth.filter(provider=provider).get()
# except UserSocialAuth.DoesNotExist:
# return None
#
# def find_valid_email(self, token):
# result = None
# for email_auth in self.social_auth.filter(provider="email"):
# email = email_auth.uid
# expected = salted_hmac(settings.SECRET_KEY, email).hexdigest()
# if expected == token:
# result = email_auth
# return result
#
# @property
# def gittip(self):
# return self.get_provider('gittip')
#
# @property
# def twitter(self):
# return self.get_provider('twitter')
#
# @property
# def github(self):
# return self.get_provider('github')
#
# @classmethod
# def get_by_auth_id(cls, auth_str):
# """
# Return the user identified by the auth id.
#
# Example::
#
# user = User.get_by_auth_id('twitter:julython')
# """
# provider, uid = auth_str.split(':')
# sa = UserSocialAuth.get_social_auth(provider, uid)
# if sa is None:
# return None
# return sa.user
#
# @property
# def auth_ids(self):
# auths = self.social_auth.all()
# return [':'.join([a.provider, a.uid]) for a in auths]
#
# @property
# def points(self):
# try:
# player = self.player_set.latest()
# except:
# return 0
# return player.points
#
# @property
# def total(self):
# return self.points
, which may contain function names, class names, or code. Output only the next line. | return render(request, template_name, |
Here is a snippet: <|code_start|>
if user.key != request.user.key:
http403 = HttpResponse("This ain't you!")
http403.status = 403
return http403
form = EditAddressForm(request.POST or None, user=user)
if form.is_valid():
for key, value in form.cleaned_data.iteritems():
setattr(user, key, value)
user.put()
return HttpResponseRedirect(
reverse('member-profile', kwargs={'username': user.username})
)
ctx = {
'form': form,
'profile': user,
'active': 'edit',
}
return render(request, template_name, ctx,
context_instance=RequestContext(request))
@login_required
def delete_email(request, username, email):
# the ID we are to delete
user = User.objects.get(username=username)
<|code_end|>
. Write the next line using the current file imports:
import logging
import json
from django.http import Http404, HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.shortcuts import render_to_response, render, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.template.context import RequestContext
from django.template.defaultfilters import slugify
from django.views.generic import detail
from django.utils.crypto import salted_hmac
from django.utils.translation import ugettext_lazy as _
from django.utils.http import int_to_base36
from django.utils.html import strip_tags
from django.core.mail import EmailMultiAlternatives, mail_admins
from django.template import loader
from django.contrib.sites.models import get_current_site
from social_auth.models import UserSocialAuth
from july.settings import SECRET_KEY as SECRET
from july.models import User
from forms import EditUserForm
from forms import EditAddressForm
and context from other files:
# Path: july/settings.py
# SECRET_KEY = 'foobar'
#
# Path: july/models.py
# class User(AbstractUser):
# location = models.ForeignKey(Location, blank=True, null=True,
# related_name='location_members')
# team = models.ForeignKey(Team, blank=True, null=True,
# related_name='team_members')
# projects = models.ManyToManyField(Project, blank=True, null=True)
# description = models.TextField(blank=True)
# url = models.URLField(blank=True, null=True)
# picture_url = models.URLField(blank=True, null=True)
#
# def __unicode__(self):
# return self.get_full_name() or self.username
#
# def add_auth_id(self, auth_str):
# """
# Add a social auth identifier for this user.
#
# The `auth_str` should be in the format '{provider}:{uid}'
# this is useful for adding multiple unique email addresses.
#
# Example::
#
# user = User.objects.get(username='foo')
# user.add_auth_id('email:foo@example.com')
# """
# provider, uid = auth_str.split(':')
# return UserSocialAuth.create_social_auth(self, uid, provider)
#
# def add_auth_email(self, email, request=None):
# """
# Adds a new, non verified email address, and sends a verification email.
# """
# auth_email = self.add_auth_id('email:%s' % email)
# auth_email.extra_data = {'verified': False}
# auth_email.save()
# return auth_email
#
# def get_provider(self, provider):
# """Return the uid of the provider or None if not set."""
# try:
# return self.social_auth.filter(provider=provider).get()
# except UserSocialAuth.DoesNotExist:
# return None
#
# def find_valid_email(self, token):
# result = None
# for email_auth in self.social_auth.filter(provider="email"):
# email = email_auth.uid
# expected = salted_hmac(settings.SECRET_KEY, email).hexdigest()
# if expected == token:
# result = email_auth
# return result
#
# @property
# def gittip(self):
# return self.get_provider('gittip')
#
# @property
# def twitter(self):
# return self.get_provider('twitter')
#
# @property
# def github(self):
# return self.get_provider('github')
#
# @classmethod
# def get_by_auth_id(cls, auth_str):
# """
# Return the user identified by the auth id.
#
# Example::
#
# user = User.get_by_auth_id('twitter:julython')
# """
# provider, uid = auth_str.split(':')
# sa = UserSocialAuth.get_social_auth(provider, uid)
# if sa is None:
# return None
# return sa.user
#
# @property
# def auth_ids(self):
# auths = self.social_auth.all()
# return [':'.join([a.provider, a.uid]) for a in auths]
#
# @property
# def points(self):
# try:
# player = self.player_set.latest()
# except:
# return 0
# return player.points
#
# @property
# def total(self):
# return self.points
, which may include functions, classes, or code. Output only the next line. | auth = UserSocialAuth.objects.get(provider="email", uid=email) |
Based on the snippet: <|code_start|>
class Command(BaseCommand):
args = '<project.json>'
help = 'Load projects from json file'
def handle(self, *args, **options):
if len(args) != 1:
raise CommandError('Must supply a JSON file of projects.')
with open(args[0], 'r') as project_file:
<|code_end|>
, predict the immediate next line with the help of imports:
import json
import logging
from django.core.management.base import BaseCommand, CommandError
from july.people.models import Project
and context (classes, functions, sometimes code) from other files:
# Path: july/people/models.py
# class Project(models.Model):
# """
# Project Model:
#
# This is either a brand new project or an already existing project
# such as #django, #fabric, #tornado, #pip, etc.
#
# When a user Tweets a url we can automatically create anew project
# for any of the repo host we know already. (github, bitbucket)
# """
#
# url = models.CharField(max_length=255)
# description = models.TextField(blank=True)
# name = models.CharField(max_length=255, blank=True)
# forked = models.BooleanField(default=False)
# forks = models.IntegerField(default=0)
# watchers = models.IntegerField(default=0)
# parent_url = models.CharField(max_length=255, blank=True)
# created_on = models.DateTimeField(auto_now_add=True)
# updated_on = models.DateTimeField(auto_now=True)
# slug = models.SlugField()
# service = models.CharField(max_length=30, blank=True, default='')
# repo_id = models.IntegerField(blank=True, null=True)
# active = models.BooleanField(default=True)
#
# def __unicode__(self):
# if self.name:
# return self.name
# else:
# return self.slug
#
# def save(self, *args, **kwargs):
# self.slug = self.project_name
# super(Project, self).save(*args, **kwargs)
#
# @property
# def points(self):
# try:
# board = self.board_set.latest()
# except:
# return 0
# return board.points
#
# @property
# def total(self):
# return self.points
#
# @property
# def project_name(self):
# return self.parse_project_name(self.url)
#
# def get_absolute_url(self):
# return reverse('project-details', args=[self.slug])
#
# @classmethod
# def create(cls, **kwargs):
# """Get or create shortcut."""
# repo_id = kwargs.get('repo_id')
# url = kwargs.get('url')
# slug = cls.parse_project_name(url)
# service = kwargs.get('service')
#
# # If the repo is on a service with no repo id, we can't handle renames.
# if not repo_id:
# project, created = cls.objects.get_or_create(
# slug=slug, defaults=kwargs)
#
# # Catch renaming of the repo.
# else:
# defaults = kwargs.copy()
# defaults['slug'] = slug
# project, created = cls.objects.get_or_create(
# service=service, repo_id=repo_id,
# defaults=defaults)
# if created and cls.objects.filter(slug=slug).count() > 1:
# # This is an old project that was created without a repo_id.
# project.delete() # Delete the duplicate project
# project = cls.objects.get(slug=slug)
#
# if not project.active:
# # Don't bother updating this project and don't add commits.
# return None
#
# # Update stale project information.
# project.update(slug, created, **kwargs)
# return project
#
# @classmethod
# def _get_bitbucket_data(cls, **kwargs):
# """Update info from bitbucket if needed."""
# url = kwargs.get('url', '')
# parsed = urlparse(url)
# if parsed.netloc == 'bitbucket.org':
# # grab data from the bitbucket api
# # TODO: (rmyers) authenticate with oauth?
# api = 'https://bitbucket.org/api/1.0/repositories%s'
# try:
# r = requests.get(api % parsed.path)
# data = r.json()
# kwargs['description'] = data.get('description') or ''
# kwargs['forks'] = data.get('forks_count') or 0
# kwargs['watchers'] = data.get('followers_count') or 0
# except:
# logging.exception("Unable to parse: %s", url)
# return kwargs.iteritems()
#
# def update(self, slug, created, **kwargs):
# old = (now() - self.updated_on).seconds >= 21600
# if created or old or slug != self.slug:
# for key, value in self._get_bitbucket_data(**kwargs):
# setattr(self, key, value)
# self.slug = slug
# self.save()
#
# @classmethod
# def parse_project_name(cls, url):
# """
# Parse a project url and return a name for it.
#
# Example::
#
# Given:
# http://github.com/julython/julython.org
# Return:
# gh-julython-julython.org
#
# This is used as the Key name in order to speed lookups during
# api requests.
# """
# if not url:
# return
# hosts_lookup = {
# 'github.com': 'gh',
# 'bitbucket.org': 'bb',
# }
# parsed = urlparse(url)
# path = parsed.path
# if path.startswith('/'):
# path = path[1:]
# tokens = path.split('/')
# netloc_slug = parsed.netloc.replace('.', '-')
# host_abbr = hosts_lookup.get(parsed.netloc, netloc_slug)
# name = '-'.join(tokens)
# if name.endswith('-'):
# name = name[:-1]
# name = name.replace('.', '_')
# return '%s-%s' % (host_abbr, name)
. Output only the next line. | projects = json.loads(project_file.read()) |
Based on the snippet: <|code_start|>
urlpatterns = patterns(
'',
url(r'^blog/$', ListView.as_view(model=Blog),
name="blog"),
url(r'^blog/(?P<slug>[-_\w]+)/$', DetailView.as_view(model=Blog),
<|code_end|>
, predict the immediate next line with the help of imports:
from django.conf.urls import patterns, url
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
from july.blog.models import Blog
and context (classes, functions, sometimes code) from other files:
# Path: july/blog/models.py
# class Blog(models.Model):
# title = models.CharField(max_length=100, unique=True)
# user = models.ForeignKey(settings.AUTH_USER_MODEL)
# slug = models.SlugField(max_length=100, unique=True)
# body = models.TextField()
# posted = models.DateTimeField(db_index=True)
# active = models.BooleanField(default=True)
# category = models.ForeignKey('blog.Category')
#
# def __unicode__(self):
# return '%s' % self.title
#
# @permalink
# def get_absolute_url(self):
# return ('view_blog_post', None, {'slug': self.slug})
. Output only the next line. | name="view_blog_post"), |
Given the code snippet: <|code_start|>
urlpatterns = patterns(
'july.game.views',
url(r'^leaders/$',
views.GameBoard.as_view(),
name='leaders'),
url(r'^leaders/(?P<year>\d{4})/(?P<month>\d{1,2})/((?P<day>\d{1,2})/)?$',
views.GameBoard.as_view(),
name='leaders'),
url(r'^people/$',
views.PlayerList.as_view(),
name='leaderboard'),
url(r'^people/(?P<year>\d{4})/(?P<month>\d{1,2})/((?P<day>\d{1,2})/)?$',
views.PlayerList.as_view(),
name='leaderboard'),
url(r'^teams/$',
views.TeamCollection.as_view(),
name='teams'),
url(r'^teams/(?P<year>\d{4})/(?P<month>\d{1,2})/((?P<day>\d{1,2})/)?$',
views.TeamCollection.as_view(),
name='teams'),
url(r'^teams/(?P<slug>[a-zA-Z0-9\-]+)/$',
views.TeamView.as_view(),
name='team-details'),
url(r'^location/$',
views.LocationCollection.as_view(),
<|code_end|>
, generate the next line using the imports in this file:
from django.conf.urls import patterns, url
from july.game import views
and context (functions, classes, or occasionally code) from other files:
# Path: july/game/views.py
# class GameMixin(object):
# class GameBoard(View, GameMixin):
# class PlayerList(ListView, GameMixin):
# class BoardList(View, GameMixin):
# class LanguageBoardList(list.ListView, GameMixin):
# class ProjectView(detail.DetailView):
# class LanguageView(detail.DetailView):
# class LocationCollection(ListView, GameMixin):
# class LocationView(detail.DetailView):
# class TeamCollection(ListView, GameMixin):
# class TeamView(detail.DetailView):
# def get_game(self):
# def get(self, request, *args, **kwargs):
# def get_queryset(self):
# def get(self, request, *args, **kwargs):
# def get_queryset(self):
# def get_queryset(self):
# def get_object(self):
# def get_queryset(self):
# def get_object(self):
# def events(request, action, channel):
. Output only the next line. | name='locations'), |
Based on the snippet: <|code_start|>
class BlogAdmin(admin.ModelAdmin):
list_display = ['title', 'user', 'slug', 'posted', 'category']
raw_id_fields = ['user']
prepopulated_fields = {'slug': ['title']}
def get_changeform_initial_data(self, request):
# For Django 1.7
initial = {}
<|code_end|>
, predict the immediate next line with the help of imports:
from django.contrib import admin
from july.blog.models import Blog, Category
and context (classes, functions, sometimes code) from other files:
# Path: july/blog/models.py
# class Blog(models.Model):
# title = models.CharField(max_length=100, unique=True)
# user = models.ForeignKey(settings.AUTH_USER_MODEL)
# slug = models.SlugField(max_length=100, unique=True)
# body = models.TextField()
# posted = models.DateTimeField(db_index=True)
# active = models.BooleanField(default=True)
# category = models.ForeignKey('blog.Category')
#
# def __unicode__(self):
# return '%s' % self.title
#
# @permalink
# def get_absolute_url(self):
# return ('view_blog_post', None, {'slug': self.slug})
#
# class Category(models.Model):
# title = models.CharField(max_length=100, db_index=True)
# slug = models.SlugField(max_length=100, db_index=True)
#
# def __unicode__(self):
# return '%s' % self.title
#
# @permalink
# def get_absolute_url(self):
# return ('view_blog_category', None, {'slug': self.slug})
. Output only the next line. | initial['user'] = request.user.pk |
Using the snippet: <|code_start|>
class BlogAdmin(admin.ModelAdmin):
list_display = ['title', 'user', 'slug', 'posted', 'category']
raw_id_fields = ['user']
prepopulated_fields = {'slug': ['title']}
def get_changeform_initial_data(self, request):
# For Django 1.7
initial = {}
initial['user'] = request.user.pk
return initial
class CategoryAdmin(admin.ModelAdmin):
<|code_end|>
, determine the next line of code. You have imports:
from django.contrib import admin
from july.blog.models import Blog, Category
and context (class names, function names, or code) available:
# Path: july/blog/models.py
# class Blog(models.Model):
# title = models.CharField(max_length=100, unique=True)
# user = models.ForeignKey(settings.AUTH_USER_MODEL)
# slug = models.SlugField(max_length=100, unique=True)
# body = models.TextField()
# posted = models.DateTimeField(db_index=True)
# active = models.BooleanField(default=True)
# category = models.ForeignKey('blog.Category')
#
# def __unicode__(self):
# return '%s' % self.title
#
# @permalink
# def get_absolute_url(self):
# return ('view_blog_post', None, {'slug': self.slug})
#
# class Category(models.Model):
# title = models.CharField(max_length=100, db_index=True)
# slug = models.SlugField(max_length=100, db_index=True)
#
# def __unicode__(self):
# return '%s' % self.title
#
# @permalink
# def get_absolute_url(self):
# return ('view_blog_category', None, {'slug': self.slug})
. Output only the next line. | list_display = ['title', 'slug'] |
Next line prediction: <|code_start|>
v1_api = Api(api_name='v1')
v1_api.register(api.CommitResource())
v1_api.register(api.ProjectResource())
v1_api.register(api.UserResource())
v1_api.register(api.LocationResource())
v1_api.register(api.TeamResource())
admin.autodiscover()
urlpatterns = patterns(
'',
# This line should only be active during maintenance!
# url(r'^.*', 'july.views.maintenance'),
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^_admin/', admin.site.urls),
# bitbucket and github are special apis
url(r'^api/v1/bitbucket$', api.BitbucketHandler.as_view()),
url(r'^api/v1/github$', api.GithubHandler.as_view()),
url(r'^api/v1/github/(?P<path>.*)$', api.GithubAPIHandler.as_view()),
url(r'^api/v1/vegas/$', api.VegasHandler.as_view()),
# Tasty Pie apis
url(r'^api/', include(v1_api.urls)),
url(r'^$', 'july.views.index', name='index'),
url(r'^live/', 'july.views.live', name='julython-live'),
url(r'^help/', 'july.views.help_view', name='help'),
url(r'^signin/$', auth_views.login, name="signin"),
<|code_end|>
. Use current file imports:
(from django.conf.urls import patterns, include, url
from django.contrib.auth import views as auth_views
from django.contrib import admin
from tastypie.api import Api
from july import api
from july.forms import PasswordResetForm)
and context including class names, function names, or small code snippets from other files:
# Path: july/api.py
# EMAIL_MATCH = re.compile('<(.+?)>')
# HOOKS_MATCH = re.compile('repos/[^/]+/[^/]+/hooks.*')
# HELP = """
# _help_: Show Help
# _craps_: Play craps
# _fear_: Show a fear and loathing quote
# _weather_: Show the current weather in Vegas
# """
# def sub_resource(request, obj, resource, queryset):
# def create_response(self, *args, **kwargs):
# def method_check(self, request, allowed=None):
# def get_projects(self, request, **kwargs):
# def get_badges(self, request, **kwargs):
# def prepend_urls(self):
# def get_users(self, request, **kwargs):
# def prepend_urls(self):
# def prepend_urls(self):
# def get_calendar(self, request, **kwargs):
# def gravatar(self, email):
# def dehydrate(self, bundle):
# def dispatch(self, request, *args, **kwargs):
# def respond_json(self, data, **kwargs):
# def get(self, request, path):
# def post(self, request, path):
# def add_language(file_dict):
# def parse_commits(self, commits, project):
# def _parse_repo(self, repository):
# def _parse_commit(self, commit, project):
# def parse_payload(self, request):
# def _publish_commits(self, commits):
# def dispatch(self, *args, **kwargs):
# def post(self, request):
# def _parse_repo(self, data):
# def _parse_email(self, raw_email):
# def parse_extensions(data):
# def _parse_commit(self, data, project):
# def parse_payload(self, request):
# def _parse_repo(self, data):
# def _parse_files(self, data):
# def wrapper(key, data):
# def _parse_commit(self, data, project):
# def roll_dice():
# def dispatch(self, *args, **kwargs):
# def weather(self, terms):
# def craps(self, terms):
# def help(self, terms):
# def fear(self, terms):
# def post(self, request):
# class CORSResource(ModelResource):
# class UserResource(CORSResource):
# class Meta:
# class ProjectResource(CORSResource):
# class Meta:
# class LocationResource(CORSResource):
# class Meta:
# class TeamResource(CORSResource):
# class Meta:
# class LanguageResource(CORSResource):
# class Meta:
# class CommitResource(CORSResource):
# class Meta:
# class LoginRequiredMixin(object):
# class JSONMixin(object):
# class GithubAPIHandler(LoginRequiredMixin, View):
# class PostCallbackHandler(View, JSONMixin):
# class BitbucketHandler(PostCallbackHandler):
# class GithubHandler(PostCallbackHandler):
# class VegasHandler(View, JSONMixin):
#
# Path: july/forms.py
# class PasswordResetForm(forms.Form):
# email = forms.EmailField(max_length=254)
#
# def save(self, domain_override=None,
# subject_template_name='registration/password_reset_subject.txt',
# email_template_name='registration/password_reset_email.html',
# use_https=False, token_generator=default_token_generator,
# from_email=None, request=None, html_email_template_name=None):
# """
# Generates a one-use only link for resetting password and sends to the
# user.
# """
# email = self.cleaned_data["email"]
# user = User.get_by_auth_id("email:%s" % email)
# if not user:
# return
# current_site = get_current_site(request)
# site_name = current_site.name
# domain = current_site.domain
# c = {
# 'email': email,
# 'domain': domain,
# 'site_name': site_name,
# 'uid': urlsafe_base64_encode(force_bytes(user.pk)),
# 'user': user,
# 'token': token_generator.make_token(user),
# 'protocol': 'https' if use_https else 'http',
# }
# subject = loader.render_to_string(subject_template_name, c)
# # Email subject *must not* contain newlines
# subject = ''.join(subject.splitlines())
# mail = loader.render_to_string(email_template_name, c)
#
# if html_email_template_name:
# html_email = loader.render_to_string(html_email_template_name, c)
# else:
# html_email = None
# send_mail(subject, mail, from_email, [email])
. Output only the next line. | url(r'^register/$', 'july.views.register', name="register"), |
Continue the code snippet: <|code_start|>
urlpatterns = patterns(
'july.people.views',
url(r'^(?P<username>[\w.@+-]+)/$',
views.UserProfile.as_view(),
name='member-profile'),
url(r'^(?P<username>[\w.@+-]+)/edit/$',
'edit_profile', name='edit-profile'),
url(r'^(?P<username>[\w.@+-]+)/address/$',
'edit_address', name='edit-address'),
url(r'^(?P<username>[\w.@+-]+)/email/(?P<email>.*)$',
<|code_end|>
. Use current file imports:
from django.conf.urls import patterns, url
from july.people import views
and context (classes, functions, or code) from other files:
# Path: july/people/views.py
# class UserProfile(detail.DetailView):
# def get_object(self):
# def people_projects(request, username):
# def send_verify_email(email, user_id, domain):
# def edit_profile(request, username, template_name='people/edit.html'):
# def edit_address(request, username, template_name='people/edit_address.html'):
# def delete_email(request, username, email):
# def delete_project(request, username, slug):
. Output only the next line. | 'delete_email', name='delete-email'), |
Predict the next line for this snippet: <|code_start|>
class Command(BaseCommand):
help = 'fix locations'
option_list = BaseCommand.option_list + (
make_option(
'--commit',
<|code_end|>
with the help of current file imports:
import logging
from django.core.management.base import BaseCommand
from django.template.defaultfilters import slugify
from july.models import User
from july.people.models import Location
from july.utils import check_location
from optparse import make_option
and context from other files:
# Path: july/models.py
# class User(AbstractUser):
# location = models.ForeignKey(Location, blank=True, null=True,
# related_name='location_members')
# team = models.ForeignKey(Team, blank=True, null=True,
# related_name='team_members')
# projects = models.ManyToManyField(Project, blank=True, null=True)
# description = models.TextField(blank=True)
# url = models.URLField(blank=True, null=True)
# picture_url = models.URLField(blank=True, null=True)
#
# def __unicode__(self):
# return self.get_full_name() or self.username
#
# def add_auth_id(self, auth_str):
# """
# Add a social auth identifier for this user.
#
# The `auth_str` should be in the format '{provider}:{uid}'
# this is useful for adding multiple unique email addresses.
#
# Example::
#
# user = User.objects.get(username='foo')
# user.add_auth_id('email:foo@example.com')
# """
# provider, uid = auth_str.split(':')
# return UserSocialAuth.create_social_auth(self, uid, provider)
#
# def add_auth_email(self, email, request=None):
# """
# Adds a new, non verified email address, and sends a verification email.
# """
# auth_email = self.add_auth_id('email:%s' % email)
# auth_email.extra_data = {'verified': False}
# auth_email.save()
# return auth_email
#
# def get_provider(self, provider):
# """Return the uid of the provider or None if not set."""
# try:
# return self.social_auth.filter(provider=provider).get()
# except UserSocialAuth.DoesNotExist:
# return None
#
# def find_valid_email(self, token):
# result = None
# for email_auth in self.social_auth.filter(provider="email"):
# email = email_auth.uid
# expected = salted_hmac(settings.SECRET_KEY, email).hexdigest()
# if expected == token:
# result = email_auth
# return result
#
# @property
# def gittip(self):
# return self.get_provider('gittip')
#
# @property
# def twitter(self):
# return self.get_provider('twitter')
#
# @property
# def github(self):
# return self.get_provider('github')
#
# @classmethod
# def get_by_auth_id(cls, auth_str):
# """
# Return the user identified by the auth id.
#
# Example::
#
# user = User.get_by_auth_id('twitter:julython')
# """
# provider, uid = auth_str.split(':')
# sa = UserSocialAuth.get_social_auth(provider, uid)
# if sa is None:
# return None
# return sa.user
#
# @property
# def auth_ids(self):
# auths = self.social_auth.all()
# return [':'.join([a.provider, a.uid]) for a in auths]
#
# @property
# def points(self):
# try:
# player = self.player_set.latest()
# except:
# return 0
# return player.points
#
# @property
# def total(self):
# return self.points
#
# Path: july/people/models.py
# class Location(Group):
# """Simple model for holding point totals and projects for a location"""
# template = 'registration/location.html'
# rel_lookup = 'user__location'
# lookup = 'location'
# auto_verify = True
#
# def get_absolute_url(self):
# from django.core.urlresolvers import reverse
# return reverse('location-detail', kwargs={'slug': self.slug})
#
# Path: july/utils.py
# def check_location(location):
# resp = requests.get(
# 'http://maps.googleapis.com/maps/api/geocode/json',
# params={'address': location, 'sensor': 'false'})
# resp.raise_for_status()
#
# data = resp.json()
# if data['status'] == 'ZERO_RESULTS':
# return None
# try:
# return data['results'][0]['formatted_address']
# except (KeyError, IndexError):
# return None
, which may contain function names, class names, or code. Output only the next line. | action='store_true', |
Based on the snippet: <|code_start|>
class Command(BaseCommand):
help = 'fix locations'
option_list = BaseCommand.option_list + (
make_option(
'--commit',
action='store_true',
dest='commit',
default=False,
help='Actually move the items.'),
)
def handle(self, *args, **options):
commit = options['commit']
empty = 0
<|code_end|>
, predict the immediate next line with the help of imports:
import logging
from django.core.management.base import BaseCommand
from django.template.defaultfilters import slugify
from july.models import User
from july.people.models import Location
from july.utils import check_location
from optparse import make_option
and context (classes, functions, sometimes code) from other files:
# Path: july/models.py
# class User(AbstractUser):
# location = models.ForeignKey(Location, blank=True, null=True,
# related_name='location_members')
# team = models.ForeignKey(Team, blank=True, null=True,
# related_name='team_members')
# projects = models.ManyToManyField(Project, blank=True, null=True)
# description = models.TextField(blank=True)
# url = models.URLField(blank=True, null=True)
# picture_url = models.URLField(blank=True, null=True)
#
# def __unicode__(self):
# return self.get_full_name() or self.username
#
# def add_auth_id(self, auth_str):
# """
# Add a social auth identifier for this user.
#
# The `auth_str` should be in the format '{provider}:{uid}'
# this is useful for adding multiple unique email addresses.
#
# Example::
#
# user = User.objects.get(username='foo')
# user.add_auth_id('email:foo@example.com')
# """
# provider, uid = auth_str.split(':')
# return UserSocialAuth.create_social_auth(self, uid, provider)
#
# def add_auth_email(self, email, request=None):
# """
# Adds a new, non verified email address, and sends a verification email.
# """
# auth_email = self.add_auth_id('email:%s' % email)
# auth_email.extra_data = {'verified': False}
# auth_email.save()
# return auth_email
#
# def get_provider(self, provider):
# """Return the uid of the provider or None if not set."""
# try:
# return self.social_auth.filter(provider=provider).get()
# except UserSocialAuth.DoesNotExist:
# return None
#
# def find_valid_email(self, token):
# result = None
# for email_auth in self.social_auth.filter(provider="email"):
# email = email_auth.uid
# expected = salted_hmac(settings.SECRET_KEY, email).hexdigest()
# if expected == token:
# result = email_auth
# return result
#
# @property
# def gittip(self):
# return self.get_provider('gittip')
#
# @property
# def twitter(self):
# return self.get_provider('twitter')
#
# @property
# def github(self):
# return self.get_provider('github')
#
# @classmethod
# def get_by_auth_id(cls, auth_str):
# """
# Return the user identified by the auth id.
#
# Example::
#
# user = User.get_by_auth_id('twitter:julython')
# """
# provider, uid = auth_str.split(':')
# sa = UserSocialAuth.get_social_auth(provider, uid)
# if sa is None:
# return None
# return sa.user
#
# @property
# def auth_ids(self):
# auths = self.social_auth.all()
# return [':'.join([a.provider, a.uid]) for a in auths]
#
# @property
# def points(self):
# try:
# player = self.player_set.latest()
# except:
# return 0
# return player.points
#
# @property
# def total(self):
# return self.points
#
# Path: july/people/models.py
# class Location(Group):
# """Simple model for holding point totals and projects for a location"""
# template = 'registration/location.html'
# rel_lookup = 'user__location'
# lookup = 'location'
# auto_verify = True
#
# def get_absolute_url(self):
# from django.core.urlresolvers import reverse
# return reverse('location-detail', kwargs={'slug': self.slug})
#
# Path: july/utils.py
# def check_location(location):
# resp = requests.get(
# 'http://maps.googleapis.com/maps/api/geocode/json',
# params={'address': location, 'sensor': 'false'})
# resp.raise_for_status()
#
# data = resp.json()
# if data['status'] == 'ZERO_RESULTS':
# return None
# try:
# return data['results'][0]['formatted_address']
# except (KeyError, IndexError):
# return None
. Output only the next line. | fine = 0 |
Predict the next line after this snippet: <|code_start|>
class Command(BaseCommand):
help = 'fix locations'
option_list = BaseCommand.option_list + (
make_option(
'--commit',
action='store_true',
<|code_end|>
using the current file's imports:
import logging
from django.core.management.base import BaseCommand
from django.template.defaultfilters import slugify
from july.models import User
from july.people.models import Location
from july.utils import check_location
from optparse import make_option
and any relevant context from other files:
# Path: july/models.py
# class User(AbstractUser):
# location = models.ForeignKey(Location, blank=True, null=True,
# related_name='location_members')
# team = models.ForeignKey(Team, blank=True, null=True,
# related_name='team_members')
# projects = models.ManyToManyField(Project, blank=True, null=True)
# description = models.TextField(blank=True)
# url = models.URLField(blank=True, null=True)
# picture_url = models.URLField(blank=True, null=True)
#
# def __unicode__(self):
# return self.get_full_name() or self.username
#
# def add_auth_id(self, auth_str):
# """
# Add a social auth identifier for this user.
#
# The `auth_str` should be in the format '{provider}:{uid}'
# this is useful for adding multiple unique email addresses.
#
# Example::
#
# user = User.objects.get(username='foo')
# user.add_auth_id('email:foo@example.com')
# """
# provider, uid = auth_str.split(':')
# return UserSocialAuth.create_social_auth(self, uid, provider)
#
# def add_auth_email(self, email, request=None):
# """
# Adds a new, non verified email address, and sends a verification email.
# """
# auth_email = self.add_auth_id('email:%s' % email)
# auth_email.extra_data = {'verified': False}
# auth_email.save()
# return auth_email
#
# def get_provider(self, provider):
# """Return the uid of the provider or None if not set."""
# try:
# return self.social_auth.filter(provider=provider).get()
# except UserSocialAuth.DoesNotExist:
# return None
#
# def find_valid_email(self, token):
# result = None
# for email_auth in self.social_auth.filter(provider="email"):
# email = email_auth.uid
# expected = salted_hmac(settings.SECRET_KEY, email).hexdigest()
# if expected == token:
# result = email_auth
# return result
#
# @property
# def gittip(self):
# return self.get_provider('gittip')
#
# @property
# def twitter(self):
# return self.get_provider('twitter')
#
# @property
# def github(self):
# return self.get_provider('github')
#
# @classmethod
# def get_by_auth_id(cls, auth_str):
# """
# Return the user identified by the auth id.
#
# Example::
#
# user = User.get_by_auth_id('twitter:julython')
# """
# provider, uid = auth_str.split(':')
# sa = UserSocialAuth.get_social_auth(provider, uid)
# if sa is None:
# return None
# return sa.user
#
# @property
# def auth_ids(self):
# auths = self.social_auth.all()
# return [':'.join([a.provider, a.uid]) for a in auths]
#
# @property
# def points(self):
# try:
# player = self.player_set.latest()
# except:
# return 0
# return player.points
#
# @property
# def total(self):
# return self.points
#
# Path: july/people/models.py
# class Location(Group):
# """Simple model for holding point totals and projects for a location"""
# template = 'registration/location.html'
# rel_lookup = 'user__location'
# lookup = 'location'
# auto_verify = True
#
# def get_absolute_url(self):
# from django.core.urlresolvers import reverse
# return reverse('location-detail', kwargs={'slug': self.slug})
#
# Path: july/utils.py
# def check_location(location):
# resp = requests.get(
# 'http://maps.googleapis.com/maps/api/geocode/json',
# params={'address': location, 'sensor': 'false'})
# resp.raise_for_status()
#
# data = resp.json()
# if data['status'] == 'ZERO_RESULTS':
# return None
# try:
# return data['results'][0]['formatted_address']
# except (KeyError, IndexError):
# return None
. Output only the next line. | dest='commit', |
Predict the next line for this snippet: <|code_start|>
register = template.Library()
@register.filter(is_safe=True)
@stringfilter
def markup(value):
extensions = ["markdown.extensions.nl2br"]
val = force_unicode(value)
html = markdown(val, extensions=extensions, enable_attributes=False)
return mark_safe(html)
@register.inclusion_tag('blog/blog_roll.html', takes_context=True)
def blog_roll(context):
<|code_end|>
with the help of current file imports:
from markdown import markdown
from django import template
from django.template.defaultfilters import stringfilter
from django.utils.encoding import force_unicode
from django.utils.safestring import mark_safe
from july.blog.models import Blog
and context from other files:
# Path: july/blog/models.py
# class Blog(models.Model):
# title = models.CharField(max_length=100, unique=True)
# user = models.ForeignKey(settings.AUTH_USER_MODEL)
# slug = models.SlugField(max_length=100, unique=True)
# body = models.TextField()
# posted = models.DateTimeField(db_index=True)
# active = models.BooleanField(default=True)
# category = models.ForeignKey('blog.Category')
#
# def __unicode__(self):
# return '%s' % self.title
#
# @permalink
# def get_absolute_url(self):
# return ('view_blog_post', None, {'slug': self.slug})
, which may contain function names, class names, or code. Output only the next line. | return { |
Given the code snippet: <|code_start|> dom = ET.parse(path)
if dom.find('stitle') != None and dom.find('stitle').text != None: #don't die if no title
title = dom.find('stitle').text
else:
title = 'No title'
print 'NO TITLE:', path
if dom.find('author') != None and dom.find('author').text != None: #don't die if no author
author = dom.find('author').text
else:
author = ''
if dom.find('categories') != None and dom.find('categories').text != None: #don't die if no categories
categories = dom.find('categories').text
else:
categories = ''
if dom.find('copyright') != None and dom.find('copyright').text != None: #don't die if no copyright
copyright = dom.find('copyright').text
else:
copyright = ''
#this code is direct copy from db.py song_save
if dom.find('chunk/line') != None: #don't die if no content
content = ''
for line in dom.findall('chunk/line'):
content += re.sub('<c.*?c>', '', ET.tostring(line).replace('<line>',' ').replace('</line>',' '))
else:
content = ''
except xml.parsers.expat.ExpatError:
title = 'No title'
author = ''
categories = ''
<|code_end|>
, generate the next line using the imports in this file:
import os
import re
import cgi
import glob
import time
import shelve
import dumbdbm
import whichdb
import posixpath
import mono2song
import xml.sax.saxutils
import xml.parsers.expat
import webapp.c_utilities as c
import xml.etree.cElementTree as ET
import xml.etree.ElementTree as ET
from webapp.model import Song, Songbook, User, bootstrap_model
and context (functions, classes, or occasionally code) from other files:
# Path: webapp/model.py
# class Song(SQLObject):
# # _connection = hub
#
# # doesn't have to be alt ID ... but perhaps we don't want dupes? (ALSO used
# # as alt ID for index method)
# # I changed it to False, b/c it causes problems with importing
# path = StringCol(alternateID=True)
# title = StringCol(alternateID=False)
# author = StringCol(alternateID=False)
# categories = StringCol(alternateID=False)
# content = StringCol(alternateID=False)
# copyright = StringCol(alternateID=False)
#
# class Songbook(SQLObject):
# # _connection = hub
#
# path = StringCol(alternateID=True)
# title = StringCol(alternateID=False)
#
# class User(SQLObject):
# """Reasonably basic User definition.
#
# Probably would want additional attributes.
#
# """
# # names like "Group", "Order" and "User" are reserved words in SQL
# # so we set the name to something safe for SQL
# class sqlmeta:
# table = 'tg_user'
#
# user_name = UnicodeCol(length=16, alternateID=True,
# alternateMethodName='by_user_name')
# email_address = UnicodeCol(length=255, alternateID=True,
# alternateMethodName='by_email_address')
# display_name = UnicodeCol(length=255)
# password = UnicodeCol(length=40)
# created = DateTimeCol(default=datetime.now)
#
# # groups this user belongs to
# groups = RelatedJoin('Group', intermediateTable='user_group',
# joinColumn='user_id', otherColumn='group_id')
#
# def _get_permissions(self):
# perms = set()
# for g in self.groups:
# perms |= set(g.permissions)
# return perms
#
# def _set_password(self, cleartext_password):
# """Run cleartext_password through the hash algorithm before saving."""
# password_hash = identity.encrypt_password(cleartext_password)
# self._SO_set_password(password_hash)
#
# def set_password_raw(self, password):
# """Saves the password as-is to the database."""
# self._SO_set_password(password)
#
# def bootstrap_model(clean=False, user=None):
# """Create all database tables and fill them with default data.
#
# This function is run by the 'bootstrap' function from the commands module.
# By default is calls two functions to create all database tables for your
# model and optionally create a user.
#
# You can add more functions as you like to add more boostrap data to the
# database or enhance the functions below.
#
# If 'clean' is True, all tables defined by you model will dropped before
# creating them again. If 'user' is not None, 'create_user' will be called
# with the given username.
#
# """
# create_tables(clean)
# if user:
# create_default_user(user)
. Output only the next line. | print 'MALFORMED:', path |
Based on the snippet: <|code_start|> copyright = ''
#this code is direct copy from db.py song_save
if dom.find('chunk/line') != None: #don't die if no content
content = ''
for line in dom.findall('chunk/line'):
content += re.sub('<c.*?c>', '', ET.tostring(line).replace('<line>',' ').replace('</line>',' '))
else:
content = ''
except xml.parsers.expat.ExpatError:
title = 'No title'
author = ''
categories = ''
print 'MALFORMED:', path
Song(title=c.fix_encoding(title), path=path, author=c.fix_encoding(author),
categories=c.fix_encoding(categories), content=c.fix_encoding(content),
copyright=c.fix_encoding(copyright))
def sync_songbooks():
songbooklist = glob.glob('songbooks/*')
for songbook in songbooklist:
if songbook.endswith('.comment') or songbook.endswith('.comment.dat') or songbook.endswith('.comment.dir') or songbook.endswith('.bak'):
continue # .comment files are not songbooks
#print 'Songbook:', songbook
path = songbook.replace('\\', '/')
try:
if Songbook.byPath(path): #skip existing songbooks in the db
continue
except:
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import re
import cgi
import glob
import time
import shelve
import dumbdbm
import whichdb
import posixpath
import mono2song
import xml.sax.saxutils
import xml.parsers.expat
import webapp.c_utilities as c
import xml.etree.cElementTree as ET
import xml.etree.ElementTree as ET
from webapp.model import Song, Songbook, User, bootstrap_model
and context (classes, functions, sometimes code) from other files:
# Path: webapp/model.py
# class Song(SQLObject):
# # _connection = hub
#
# # doesn't have to be alt ID ... but perhaps we don't want dupes? (ALSO used
# # as alt ID for index method)
# # I changed it to False, b/c it causes problems with importing
# path = StringCol(alternateID=True)
# title = StringCol(alternateID=False)
# author = StringCol(alternateID=False)
# categories = StringCol(alternateID=False)
# content = StringCol(alternateID=False)
# copyright = StringCol(alternateID=False)
#
# class Songbook(SQLObject):
# # _connection = hub
#
# path = StringCol(alternateID=True)
# title = StringCol(alternateID=False)
#
# class User(SQLObject):
# """Reasonably basic User definition.
#
# Probably would want additional attributes.
#
# """
# # names like "Group", "Order" and "User" are reserved words in SQL
# # so we set the name to something safe for SQL
# class sqlmeta:
# table = 'tg_user'
#
# user_name = UnicodeCol(length=16, alternateID=True,
# alternateMethodName='by_user_name')
# email_address = UnicodeCol(length=255, alternateID=True,
# alternateMethodName='by_email_address')
# display_name = UnicodeCol(length=255)
# password = UnicodeCol(length=40)
# created = DateTimeCol(default=datetime.now)
#
# # groups this user belongs to
# groups = RelatedJoin('Group', intermediateTable='user_group',
# joinColumn='user_id', otherColumn='group_id')
#
# def _get_permissions(self):
# perms = set()
# for g in self.groups:
# perms |= set(g.permissions)
# return perms
#
# def _set_password(self, cleartext_password):
# """Run cleartext_password through the hash algorithm before saving."""
# password_hash = identity.encrypt_password(cleartext_password)
# self._SO_set_password(password_hash)
#
# def set_password_raw(self, password):
# """Saves the password as-is to the database."""
# self._SO_set_password(password)
#
# def bootstrap_model(clean=False, user=None):
# """Create all database tables and fill them with default data.
#
# This function is run by the 'bootstrap' function from the commands module.
# By default is calls two functions to create all database tables for your
# model and optionally create a user.
#
# You can add more functions as you like to add more boostrap data to the
# database or enhance the functions below.
#
# If 'clean' is True, all tables defined by you model will dropped before
# creating them again. If 'user' is not None, 'create_user' will be called
# with the given username.
#
# """
# create_tables(clean)
# if user:
# create_default_user(user)
. Output only the next line. | pass #songbook not found, error thrown, lets add it to the db! |
Given the code snippet: <|code_start|> break # we found it and removed it -- done.
return songbooks
def sync_songs():
songlist = glob.glob('songs/*')
for song in songlist:
#print 'Song:', song
path = song.replace('\\', '/')
try:
if Song.byPath(path): #skip existing songs in the db
continue
except:
pass #song not found, error thrown, lets add it to the db!
try:
dom = ET.parse(path)
if dom.find('stitle') != None and dom.find('stitle').text != None: #don't die if no title
title = dom.find('stitle').text
else:
title = 'No title'
print 'NO TITLE:', path
if dom.find('author') != None and dom.find('author').text != None: #don't die if no author
author = dom.find('author').text
else:
author = ''
if dom.find('categories') != None and dom.find('categories').text != None: #don't die if no categories
categories = dom.find('categories').text
else:
categories = ''
if dom.find('copyright') != None and dom.find('copyright').text != None: #don't die if no copyright
<|code_end|>
, generate the next line using the imports in this file:
import os
import re
import cgi
import glob
import time
import shelve
import dumbdbm
import whichdb
import posixpath
import mono2song
import xml.sax.saxutils
import xml.parsers.expat
import webapp.c_utilities as c
import xml.etree.cElementTree as ET
import xml.etree.ElementTree as ET
from webapp.model import Song, Songbook, User, bootstrap_model
and context (functions, classes, or occasionally code) from other files:
# Path: webapp/model.py
# class Song(SQLObject):
# # _connection = hub
#
# # doesn't have to be alt ID ... but perhaps we don't want dupes? (ALSO used
# # as alt ID for index method)
# # I changed it to False, b/c it causes problems with importing
# path = StringCol(alternateID=True)
# title = StringCol(alternateID=False)
# author = StringCol(alternateID=False)
# categories = StringCol(alternateID=False)
# content = StringCol(alternateID=False)
# copyright = StringCol(alternateID=False)
#
# class Songbook(SQLObject):
# # _connection = hub
#
# path = StringCol(alternateID=True)
# title = StringCol(alternateID=False)
#
# class User(SQLObject):
# """Reasonably basic User definition.
#
# Probably would want additional attributes.
#
# """
# # names like "Group", "Order" and "User" are reserved words in SQL
# # so we set the name to something safe for SQL
# class sqlmeta:
# table = 'tg_user'
#
# user_name = UnicodeCol(length=16, alternateID=True,
# alternateMethodName='by_user_name')
# email_address = UnicodeCol(length=255, alternateID=True,
# alternateMethodName='by_email_address')
# display_name = UnicodeCol(length=255)
# password = UnicodeCol(length=40)
# created = DateTimeCol(default=datetime.now)
#
# # groups this user belongs to
# groups = RelatedJoin('Group', intermediateTable='user_group',
# joinColumn='user_id', otherColumn='group_id')
#
# def _get_permissions(self):
# perms = set()
# for g in self.groups:
# perms |= set(g.permissions)
# return perms
#
# def _set_password(self, cleartext_password):
# """Run cleartext_password through the hash algorithm before saving."""
# password_hash = identity.encrypt_password(cleartext_password)
# self._SO_set_password(password_hash)
#
# def set_password_raw(self, password):
# """Saves the password as-is to the database."""
# self._SO_set_password(password)
#
# def bootstrap_model(clean=False, user=None):
# """Create all database tables and fill them with default data.
#
# This function is run by the 'bootstrap' function from the commands module.
# By default is calls two functions to create all database tables for your
# model and optionally create a user.
#
# You can add more functions as you like to add more boostrap data to the
# database or enhance the functions below.
#
# If 'clean' is True, all tables defined by you model will dropped before
# creating them again. If 'user' is not None, 'create_user' will be called
# with the given username.
#
# """
# create_tables(clean)
# if user:
# create_default_user(user)
. Output only the next line. | copyright = dom.find('copyright').text |
Next line prediction: <|code_start|>
def songbooks():
songbooks = [songbooks for songbooks in Songbook.select(orderBy=Songbook.q.title)]
songbooks.sort(key=lambda x: x.title.lower() or 'No Title')
# save and the remove the all songs songbook from the songbook list
for i in range(len(songbooks)):
if songbooks[i].path == ALL_SONGS_PATH:
del songbooks[i]
break # we found it and removed it -- done.
return songbooks
def sync_songs():
songlist = glob.glob('songs/*')
for song in songlist:
#print 'Song:', song
path = song.replace('\\', '/')
try:
if Song.byPath(path): #skip existing songs in the db
continue
except:
pass #song not found, error thrown, lets add it to the db!
try:
dom = ET.parse(path)
if dom.find('stitle') != None and dom.find('stitle').text != None: #don't die if no title
title = dom.find('stitle').text
else:
title = 'No title'
print 'NO TITLE:', path
<|code_end|>
. Use current file imports:
(import os
import re
import cgi
import glob
import time
import shelve
import dumbdbm
import whichdb
import posixpath
import mono2song
import xml.sax.saxutils
import xml.parsers.expat
import webapp.c_utilities as c
import xml.etree.cElementTree as ET
import xml.etree.ElementTree as ET
from webapp.model import Song, Songbook, User, bootstrap_model)
and context including class names, function names, or small code snippets from other files:
# Path: webapp/model.py
# class Song(SQLObject):
# # _connection = hub
#
# # doesn't have to be alt ID ... but perhaps we don't want dupes? (ALSO used
# # as alt ID for index method)
# # I changed it to False, b/c it causes problems with importing
# path = StringCol(alternateID=True)
# title = StringCol(alternateID=False)
# author = StringCol(alternateID=False)
# categories = StringCol(alternateID=False)
# content = StringCol(alternateID=False)
# copyright = StringCol(alternateID=False)
#
# class Songbook(SQLObject):
# # _connection = hub
#
# path = StringCol(alternateID=True)
# title = StringCol(alternateID=False)
#
# class User(SQLObject):
# """Reasonably basic User definition.
#
# Probably would want additional attributes.
#
# """
# # names like "Group", "Order" and "User" are reserved words in SQL
# # so we set the name to something safe for SQL
# class sqlmeta:
# table = 'tg_user'
#
# user_name = UnicodeCol(length=16, alternateID=True,
# alternateMethodName='by_user_name')
# email_address = UnicodeCol(length=255, alternateID=True,
# alternateMethodName='by_email_address')
# display_name = UnicodeCol(length=255)
# password = UnicodeCol(length=40)
# created = DateTimeCol(default=datetime.now)
#
# # groups this user belongs to
# groups = RelatedJoin('Group', intermediateTable='user_group',
# joinColumn='user_id', otherColumn='group_id')
#
# def _get_permissions(self):
# perms = set()
# for g in self.groups:
# perms |= set(g.permissions)
# return perms
#
# def _set_password(self, cleartext_password):
# """Run cleartext_password through the hash algorithm before saving."""
# password_hash = identity.encrypt_password(cleartext_password)
# self._SO_set_password(password_hash)
#
# def set_password_raw(self, password):
# """Saves the password as-is to the database."""
# self._SO_set_password(password)
#
# def bootstrap_model(clean=False, user=None):
# """Create all database tables and fill them with default data.
#
# This function is run by the 'bootstrap' function from the commands module.
# By default is calls two functions to create all database tables for your
# model and optionally create a user.
#
# You can add more functions as you like to add more boostrap data to the
# database or enhance the functions below.
#
# If 'clean' is True, all tables defined by you model will dropped before
# creating them again. If 'user' is not None, 'create_user' will be called
# with the given username.
#
# """
# create_tables(clean)
# if user:
# create_default_user(user)
. Output only the next line. | if dom.find('author') != None and dom.find('author').text != None: #don't die if no author |
Continue the code snippet: <|code_start|>except ImportError:
if exists('song.db'):
os.system('rm song.db')
print '\nREMOVED EXISTING DATABASE\n'
os.system('tg-admin -c prod.cfg sql create')
if exists(join(dirname(__file__), "setup.py")):
turbogears.update_config(configfile="dev.cfg",
modulename="webapp.config")
# grab all songs and songbooks from directories
songlist = glob.glob('songs/*')
songbooklist = glob.glob('songbooks/*')
# enter songs into database
hub.begin() #open connection to database
print '\n'
for song in songlist:
print 'Song:', song
path = song.replace('\\', '/')
try:
dom = ET.parse(path)
if dom.find('stitle') != None and dom.find('stitle').text != None: #don't die if no title
title = dom.find('stitle').text
else:
<|code_end|>
. Use current file imports:
from webapp.model import Song, Songbook, hub
from posixpath import *
import xml.etree.cElementTree as ET
import xml.etree.ElementTree as ET
import xml.parsers.expat
import webapp.c_utilities as c
import turbogears
import glob
import sys
import os
import re
and context (classes, functions, or code) from other files:
# Path: webapp/model.py
# class Song(SQLObject):
# class Songbook(SQLObject):
# class Visit(SQLObject):
# class sqlmeta:
# class VisitIdentity(SQLObject):
# class Group(SQLObject):
# class sqlmeta:
# class User(SQLObject):
# class sqlmeta:
# class Permission(SQLObject):
# def lookup_visit(cls, visit_key):
# def _get_permissions(self):
# def _set_password(self, cleartext_password):
# def set_password_raw(self, password):
# def bootstrap_model(clean=False, user=None):
# def create_tables(drop_all=False):
# def create_default_user(user_name):
. Output only the next line. | title = 'No title' |
Given the code snippet: <|code_start|>#!/usr/bin/env python
try: # try c version for speed then fall back to python
except ImportError:
if exists('song.db'):
os.system('rm song.db')
print '\nREMOVED EXISTING DATABASE\n'
os.system('tg-admin -c prod.cfg sql create')
if exists(join(dirname(__file__), "setup.py")):
turbogears.update_config(configfile="dev.cfg",
<|code_end|>
, generate the next line using the imports in this file:
from webapp.model import Song, Songbook, hub
from posixpath import *
import xml.etree.cElementTree as ET
import xml.etree.ElementTree as ET
import xml.parsers.expat
import webapp.c_utilities as c
import turbogears
import glob
import sys
import os
import re
and context (functions, classes, or occasionally code) from other files:
# Path: webapp/model.py
# class Song(SQLObject):
# class Songbook(SQLObject):
# class Visit(SQLObject):
# class sqlmeta:
# class VisitIdentity(SQLObject):
# class Group(SQLObject):
# class sqlmeta:
# class User(SQLObject):
# class sqlmeta:
# class Permission(SQLObject):
# def lookup_visit(cls, visit_key):
# def _get_permissions(self):
# def _set_password(self, cleartext_password):
# def set_password_raw(self, password):
# def bootstrap_model(clean=False, user=None):
# def create_tables(drop_all=False):
# def create_default_user(user_name):
. Output only the next line. | modulename="webapp.config") |
Using the snippet: <|code_start|>try: # try c version for speed then fall back to python
except ImportError:
if exists('song.db'):
os.system('rm song.db')
print '\nREMOVED EXISTING DATABASE\n'
os.system('tg-admin -c prod.cfg sql create')
if exists(join(dirname(__file__), "setup.py")):
turbogears.update_config(configfile="dev.cfg",
modulename="webapp.config")
# grab all songs and songbooks from directories
songlist = glob.glob('songs/*')
songbooklist = glob.glob('songbooks/*')
# enter songs into database
hub.begin() #open connection to database
print '\n'
for song in songlist:
print 'Song:', song
path = song.replace('\\', '/')
try:
dom = ET.parse(path)
if dom.find('stitle') != None and dom.find('stitle').text != None: #don't die if no title
title = dom.find('stitle').text
<|code_end|>
, determine the next line of code. You have imports:
from webapp.model import Song, Songbook, hub
from posixpath import *
import xml.etree.cElementTree as ET
import xml.etree.ElementTree as ET
import xml.parsers.expat
import webapp.c_utilities as c
import turbogears
import glob
import sys
import os
import re
and context (class names, function names, or code) available:
# Path: webapp/model.py
# class Song(SQLObject):
# class Songbook(SQLObject):
# class Visit(SQLObject):
# class sqlmeta:
# class VisitIdentity(SQLObject):
# class Group(SQLObject):
# class sqlmeta:
# class User(SQLObject):
# class sqlmeta:
# class Permission(SQLObject):
# def lookup_visit(cls, visit_key):
# def _get_permissions(self):
# def _set_password(self, cleartext_password):
# def set_password_raw(self, password):
# def bootstrap_model(clean=False, user=None):
# def create_tables(drop_all=False):
# def create_default_user(user_name):
. Output only the next line. | else: |
Next line prediction: <|code_start|>#
# This file is part of casiopeia.
#
# Copyright 2014-2016 Adrian Bürger, Moritz Diehl
#
# casiopeia is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# casiopeia is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warrantime_points of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with casiopeia. If not, see <http://www.gnu.org/licenses/>.
class SetSystem(unittest.TestCase):
def setUp(self):
self.system = "system"
def test_set_system(self):
<|code_end|>
. Use current file imports:
(import numpy as np
import unittest
import mock
from numpy.testing import assert_array_equal
from casiopeia.interfaces import casadi_interface as ci
from casiopeia import inputchecks)
and context including class names, function names, or small code snippets from other files:
# Path: casiopeia/interfaces/casadi_interface.py
# def sx_sym(name, dim1 = 1, dim2 = 1):
# def sx_function(name, inputs, outputs):
# def mx_sym(name, dim1 = 1, dim2 = 1):
# def mx_function(name, inputs, outputs, options = {}):
# def dmatrix(dim1, dim2 = 1):
# def depends_on(b, a):
# def collocation_points(order, scheme):
# def vertcat(inputlist):
# def veccat(inputlist):
# def horzcat(inputlist):
# def repmat(inputobj, dim1, dim2):
# def vec(inputobj):
# def sqrt(inputobj):
# def mul(inputobj):
# def NlpSolver(name, solver, nlp, options):
# def daeIn(t = None, x = None, p = None):
# def daeOut(ode = None, alg = None):
# def Integrator(name, method, dae, options = {}):
# def diag(inputobj):
# def mx(dim1, dim2):
# def blockcat(a, b, c, d):
# def jacobian(a, b):
# def solve(a, b, solver):
# def mx_eye(dim1):
# def trace(inputobj):
# def det(inputobj):
# def diagcat(inputobj):
#
# Path: casiopeia/inputchecks.py
# def set_system(system):
# def check_time_points_input(tp):
# def check_controls_data(udata, nu, number_of_controls):
# def check_constant_controls_data(qdata, nq):
# def check_states_data(xdata, nx, number_of_intervals):
# def check_parameter_data(pdata, n_p):
# def check_measurement_data(ydata, nphi, number_of_measurements):
# def check_measurement_weightings(wv, nphi, number_of_measurements):
# def check_input_error_weightings(weps_u, neps_u, number_of_intervals):
# def check_multi_doe_input(doe_setups):
# def check_multi_lsq_input(pe_setups):
. Output only the next line. | system = "system" |
Given the following code snippet before the placeholder: <|code_start|> n_p = 3
pdata_ref = np.random.rand(n_p, 2)
self.assertRaises(ValueError, \
inputchecks.check_parameter_data, pdata_ref, n_p)
class CheckMeasurementData(unittest.TestCase):
def setUp(self):
self.number_of_measurements = 20
self.nphi = 2
def test_input_rows(self):
ydata_ref = np.random.rand(self.nphi, self.number_of_measurements)
ydata = inputchecks.check_measurement_data(ydata_ref, \
self.nphi, self.number_of_measurements)
assert_array_equal(ydata, ydata_ref)
def test_input_columns(self):
ydata_ref = np.random.rand(self.nphi, self.number_of_measurements)
ydata = inputchecks.check_measurement_data(ydata_ref.T, \
self.nphi, self.number_of_measurements)
<|code_end|>
, predict the next line using imports from the current file:
import numpy as np
import unittest
import mock
from numpy.testing import assert_array_equal
from casiopeia.interfaces import casadi_interface as ci
from casiopeia import inputchecks
and context including class names, function names, and sometimes code from other files:
# Path: casiopeia/interfaces/casadi_interface.py
# def sx_sym(name, dim1 = 1, dim2 = 1):
# def sx_function(name, inputs, outputs):
# def mx_sym(name, dim1 = 1, dim2 = 1):
# def mx_function(name, inputs, outputs, options = {}):
# def dmatrix(dim1, dim2 = 1):
# def depends_on(b, a):
# def collocation_points(order, scheme):
# def vertcat(inputlist):
# def veccat(inputlist):
# def horzcat(inputlist):
# def repmat(inputobj, dim1, dim2):
# def vec(inputobj):
# def sqrt(inputobj):
# def mul(inputobj):
# def NlpSolver(name, solver, nlp, options):
# def daeIn(t = None, x = None, p = None):
# def daeOut(ode = None, alg = None):
# def Integrator(name, method, dae, options = {}):
# def diag(inputobj):
# def mx(dim1, dim2):
# def blockcat(a, b, c, d):
# def jacobian(a, b):
# def solve(a, b, solver):
# def mx_eye(dim1):
# def trace(inputobj):
# def det(inputobj):
# def diagcat(inputobj):
#
# Path: casiopeia/inputchecks.py
# def set_system(system):
# def check_time_points_input(tp):
# def check_controls_data(udata, nu, number_of_controls):
# def check_constant_controls_data(qdata, nq):
# def check_states_data(xdata, nx, number_of_intervals):
# def check_parameter_data(pdata, n_p):
# def check_measurement_data(ydata, nphi, number_of_measurements):
# def check_measurement_weightings(wv, nphi, number_of_measurements):
# def check_input_error_weightings(weps_u, neps_u, number_of_intervals):
# def check_multi_doe_input(doe_setups):
# def check_multi_lsq_input(pe_setups):
. Output only the next line. | assert_array_equal(ydata, ydata_ref) |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python
logging.basicConfig(level=logging.INFO)
START_TIME = time.time()
class RespHandler(object):
@classmethod
def on_open(self, ws):
logging.debug("Client connected")
to_send = {'act': 'login'}
ws.send(json.dumps(to_send))
@classmethod
def on_message(self, ws, message):
logging.debug("Client got: %s" % message)
message = json.loads(message)
if message['act'] == 'login':
<|code_end|>
using the current file's imports:
import sys
import time
import logging
import websocket
import ujson as json
import set_path
from tilde.core.settings import settings
and any relevant context from other files:
# Path: tilde/core/settings.py
# DB_SCHEMA_VERSION = '5.20'
# SETTINGS_FILE = 'settings.json'
# DEFAULT_SQLITE_DB = 'default.db'
# BASE_DIR = os.path.dirname(os.path.realpath(os.path.abspath(__file__)))
# ROOT_DIR = os.path.normpath(BASE_DIR + '/../')
# DATA_DIR = os.path.join(ROOT_DIR, 'data')
# EXAMPLE_DIR = os.path.join(ROOT_DIR, '../tests/data')
# INIT_DATA = os.path.join(DATA_DIR, 'sql/init-data.sql')
# TEST_DBS_FILE = os.path.join(DATA_DIR, 'test_dbs.txt')
# TEST_DBS_REF_FILE = os.path.join(DATA_DIR, 'test_dbs_ref.txt')
# SETTINGS_PATH = DATA_DIR + os.sep + SETTINGS_FILE
# GUI_URL_TPL = 'http://tilde-lab.github.io/berlinium/?http://127.0.0.1:%s' # ?https://db.tilde.pro
# DEFAULT_SETUP = {
#
# # General part
# 'debug_regime': False, # TODO
# 'log_dir': os.path.join(DATA_DIR, "logs"), # TODO
# 'skip_unfinished': False,
# 'skip_notenergy': False,
# 'skip_if_path': [],
#
# # DB part
# 'db': {
# 'default_sqlite_db': DEFAULT_SQLITE_DB,
# 'engine': 'sqlite', # if sqlite is chosen: further info is not used
# 'host': 'localhost',
# 'port': 5432,
# 'user': 'postgres',
# 'password': '',
# 'dbname': 'tilde'
# },
#
# # Server part
# 'webport': 8070,
# 'title': "Tilde GUI"
# }
# def virtualize_path(item):
# def connect_url(settings, named=None):
# def connect_database(settings, named=None, no_pooling=False, default_actions=True, scoped=False):
# def write_settings(settings):
# def get_hierarchy(settings):
. Output only the next line. | to_send = {'act': 'sleep', 'req': 4} |
Given the following code snippet before the placeholder: <|code_start|>
class Test_API(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.sample = API()
def test_count_classifiers(self):
available_classifiers = []
path = os.path.realpath(BASE_DIR + '/../classifiers')
for classifierpath in os.listdir(path):
if os.path.isfile(os.path.join(path, classifierpath)) and classifierpath.endswith('.py') and classifierpath != '__init__.py':
available_classifiers.append(classifierpath)
self.assertEqual(len(self.sample.Classifiers), len(available_classifiers),
"Expected to have %s, but got %s modules. May be unused classifier occured since?" % (len(available_classifiers), len(self.sample.Classifiers)))
def test_formula(self):
self.assertEqual(self.sample.formula(['H', 'O', 'C', 'H', 'H', 'C', 'H', 'H', 'H' ]), 'C2H6O', "Formula was errorneously generated!")
def test_savvyize_simple(self):
path = os.path.join(EXAMPLE_DIR, 'CRYSTAL')
<|code_end|>
, predict the next line using imports from the current file:
import os, sys
import unittest
from tilde.core.api import API
from tilde.core.settings import BASE_DIR, EXAMPLE_DIR
and context including class names, function names, and sometimes code from other files:
# Path: tilde/core/api.py
# API = TildeAPI
#
# Path: tilde/core/settings.py
# BASE_DIR = os.path.dirname(os.path.realpath(os.path.abspath(__file__)))
#
# EXAMPLE_DIR = os.path.join(ROOT_DIR, '../tests/data')
. Output only the next line. | found = self.sample.savvyize(path) |
Predict the next line for this snippet: <|code_start|> cls.sample = API()
def test_count_classifiers(self):
available_classifiers = []
path = os.path.realpath(BASE_DIR + '/../classifiers')
for classifierpath in os.listdir(path):
if os.path.isfile(os.path.join(path, classifierpath)) and classifierpath.endswith('.py') and classifierpath != '__init__.py':
available_classifiers.append(classifierpath)
self.assertEqual(len(self.sample.Classifiers), len(available_classifiers),
"Expected to have %s, but got %s modules. May be unused classifier occured since?" % (len(available_classifiers), len(self.sample.Classifiers)))
def test_formula(self):
self.assertEqual(self.sample.formula(['H', 'O', 'C', 'H', 'H', 'C', 'H', 'H', 'H' ]), 'C2H6O', "Formula was errorneously generated!")
def test_savvyize_simple(self):
path = os.path.join(EXAMPLE_DIR, 'CRYSTAL')
found = self.sample.savvyize(path)
self.assertEqual(len(found), 3,
"Unexpected number of files has been found in %s: %s. May be number of files has been changed since?" % (path, len(found)))
def test_savvyize_recursive(self):
path = os.path.join(EXAMPLE_DIR, 'VASP')
found = self.sample.savvyize(path, recursive=True)
self.assertEqual(len(found), 2,
"Unexpected number of files has been found in %s: %s. May be number of files has been changed since?" % (path, len(found)))
def test_savvyize_stemma(self):
path = os.path.join(BASE_DIR, 'co')
found = self.sample.savvyize(path, recursive=True, stemma=True)
<|code_end|>
with the help of current file imports:
import os, sys
import unittest
from tilde.core.api import API
from tilde.core.settings import BASE_DIR, EXAMPLE_DIR
and context from other files:
# Path: tilde/core/api.py
# API = TildeAPI
#
# Path: tilde/core/settings.py
# BASE_DIR = os.path.dirname(os.path.realpath(os.path.abspath(__file__)))
#
# EXAMPLE_DIR = os.path.join(ROOT_DIR, '../tests/data')
, which may contain function names, class names, or code. Output only the next line. | found = [module for module in found if not module.endswith('.pyc')] # NB Python3 is accounted |
Predict the next line for this snippet: <|code_start|>
class Test_API(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.sample = API()
def test_count_classifiers(self):
available_classifiers = []
path = os.path.realpath(BASE_DIR + '/../classifiers')
for classifierpath in os.listdir(path):
if os.path.isfile(os.path.join(path, classifierpath)) and classifierpath.endswith('.py') and classifierpath != '__init__.py':
available_classifiers.append(classifierpath)
self.assertEqual(len(self.sample.Classifiers), len(available_classifiers),
"Expected to have %s, but got %s modules. May be unused classifier occured since?" % (len(available_classifiers), len(self.sample.Classifiers)))
def test_formula(self):
self.assertEqual(self.sample.formula(['H', 'O', 'C', 'H', 'H', 'C', 'H', 'H', 'H' ]), 'C2H6O', "Formula was errorneously generated!")
def test_savvyize_simple(self):
path = os.path.join(EXAMPLE_DIR, 'CRYSTAL')
<|code_end|>
with the help of current file imports:
import os, sys
import unittest
from tilde.core.api import API
from tilde.core.settings import BASE_DIR, EXAMPLE_DIR
and context from other files:
# Path: tilde/core/api.py
# API = TildeAPI
#
# Path: tilde/core/settings.py
# BASE_DIR = os.path.dirname(os.path.realpath(os.path.abspath(__file__)))
#
# EXAMPLE_DIR = os.path.join(ROOT_DIR, '../tests/data')
, which may contain function names, class names, or code. Output only the next line. | found = self.sample.savvyize(path) |
Next line prediction: <|code_start|>#!/usr/bin/env python
logging.basicConfig(level=logging.DEBUG)
START_TIME = time.time()
class RespHandler(object):
@classmethod
def on_error(self, ws, error):
logging.error(error)
@classmethod
def on_close(self, ws):
logging.debug("Closed")
ws.close()
@classmethod
<|code_end|>
. Use current file imports:
(import sys
import time
import logging
import websocket
import ujson as json
import set_path
from tilde.core.settings import settings)
and context including class names, function names, or small code snippets from other files:
# Path: tilde/core/settings.py
# DB_SCHEMA_VERSION = '5.20'
# SETTINGS_FILE = 'settings.json'
# DEFAULT_SQLITE_DB = 'default.db'
# BASE_DIR = os.path.dirname(os.path.realpath(os.path.abspath(__file__)))
# ROOT_DIR = os.path.normpath(BASE_DIR + '/../')
# DATA_DIR = os.path.join(ROOT_DIR, 'data')
# EXAMPLE_DIR = os.path.join(ROOT_DIR, '../tests/data')
# INIT_DATA = os.path.join(DATA_DIR, 'sql/init-data.sql')
# TEST_DBS_FILE = os.path.join(DATA_DIR, 'test_dbs.txt')
# TEST_DBS_REF_FILE = os.path.join(DATA_DIR, 'test_dbs_ref.txt')
# SETTINGS_PATH = DATA_DIR + os.sep + SETTINGS_FILE
# GUI_URL_TPL = 'http://tilde-lab.github.io/berlinium/?http://127.0.0.1:%s' # ?https://db.tilde.pro
# DEFAULT_SETUP = {
#
# # General part
# 'debug_regime': False, # TODO
# 'log_dir': os.path.join(DATA_DIR, "logs"), # TODO
# 'skip_unfinished': False,
# 'skip_notenergy': False,
# 'skip_if_path': [],
#
# # DB part
# 'db': {
# 'default_sqlite_db': DEFAULT_SQLITE_DB,
# 'engine': 'sqlite', # if sqlite is chosen: further info is not used
# 'host': 'localhost',
# 'port': 5432,
# 'user': 'postgres',
# 'password': '',
# 'dbname': 'tilde'
# },
#
# # Server part
# 'webport': 8070,
# 'title': "Tilde GUI"
# }
# def virtualize_path(item):
# def connect_url(settings, named=None):
# def connect_database(settings, named=None, no_pooling=False, default_actions=True, scoped=False):
# def write_settings(settings):
# def get_hierarchy(settings):
. Output only the next line. | def on_open(self, ws): |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.