Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Predict the next line after this snippet: <|code_start|>
logger = logging.getLogger(__name__)
logging.basicConfig(format='%(levelname)s : %(message)s', level=logging.INFO)
logger.setLevel(logging.DEBUG)
logging.getLogger('inputgeneration').setLevel(logging.DEBUG)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('dir_in', help='directory containing the data '
'(manifesto project csv files)')
parser.add_argument('dir_out', help='the name of the dir where the '
'CPT corpus should be saved.')
args = parser.parse_args()
dir_in = args.dir_in
dir_out = args.dir_out
frogclient = get_frogclient()
if not os.path.exists(dir_out):
os.makedirs(dir_out)
data_files = glob.glob('{}/*.csv'.format(dir_in))
for i, data_file in enumerate(data_files):
if i % 5 == 0:
logger.info('Processing text {} of {}'.format(i + 1,
len(data_files)))
<|code_end|>
using the current file's imports:
import pandas as pd
import logging
import argparse
import os
import glob
from cptm.utils.inputgeneration import Perspective, remove_trailing_digits
from cptm.utils.dutchdata import pos_topic_words, pos_opinion_words, word_types
from cptm.utils.frog import get_frogclient, pos_and_lemmas
and any relevant context from other files:
# Path: cptm/utils/inputgeneration.py
# class Perspective():
# def __init__(self, name, posTopic, posOpinion):
# """Initialize inputgeneration Perspective.
#
# Parameters:
# name : str
# The perspective name. Used as directory name to store the data.
# posTopic : list of strings
# List of strings specifying the pos-tags for topic words.
# posOpinion : list of strings
# List of strings specifying the pos-tags for opinion words.
# """
# self.name = name
# self.wordTypes = posTopic + posOpinion
# self.posTopic = posTopic
# self.posOpinion = posOpinion
# self.words = {}
# for w in self.wordTypes:
# self.words[w] = []
#
# def __str__(self):
# len_topic_words, len_opinion_words = self.word_lengths()
# return 'Perspective: {} - {} topic words; {} opinion words'.format(
# self.name, len_topic_words, len_opinion_words)
#
# def add(self, tag, word):
# self.words[tag].append(word)
#
# def write2file(self, out_dir, file_name):
# # create dir (if not exists)
# directory = os.path.join(out_dir, self.name)
# if not os.path.exists(directory):
# os.makedirs(directory)
#
# # write words to file
# out_file = os.path.join(directory, file_name)
# logger.debug('Writing file {} for perspective {}'.format(out_file,
# self.name))
# with codecs.open(out_file, 'wb', 'utf8') as f:
# for w in self.wordTypes:
# f.write(u'{}\n'.format(' '.join(self.words[w])))
#
# def word_lengths(self):
# len_topic_words = sum([len(self.words[w])
# for w in self.posTopic])
# len_opinion_words = sum([len(self.words[w])
# for w in self.posOpinion])
# return len_topic_words, len_opinion_words
#
# def remove_trailing_digits(word):
# """Convert words like d66 to d.
#
# In the folia files from politicalmashup, words such as d66 have been
# extracted as two words (d and 66) and only d ended up in the data input
# files. The folia files were probably created with an old version of frog,
# because currenly, words like these are parsed correctly.
#
# This function can be used when parsing and lemmatizing new text to match
# the vocabulary used in the old folia files.
# """
# regex = re.compile('^(.+?)(\d+)$', flags=re.UNICODE)
# m = regex.match(word)
# if m:
# return m.group(1)
# return word
#
# Path: cptm/utils/dutchdata.py
# def pos_topic_words():
# return ['N']
#
# def pos_opinion_words():
# return ['ADJ', 'BW', 'WW']
#
# def word_types():
# return pos_topic_words() + pos_opinion_words()
#
# Path: cptm/utils/frog.py
# def get_frogclient(port=8020):
# try:
# frogclient = FrogClient('localhost', port)
# return frogclient
# except:
# logger.error('Cannot connect to the Frog server. '
# 'Is it running at port {}?'.format(port))
# logger.info('Start the Frog server with "docker run -p '
# '127.0.0.1:{}:{} -t -i proycon/lamachine frog '
# '-S {}"'.format(port, port, port))
# sys.exit(1)
#
# def pos_and_lemmas(text, frogclient):
# # add timeout functionality (so frog won't keep parsing faulty text
# # forever)
# signal.signal(signal.SIGALRM, timeout)
# signal.alarm(300)
#
# regex = re.compile(r'\(.*\)')
#
# try:
# for data in frogclient.process(text):
# word, lemma, morph, ext_pos = data[:4]
# if ext_pos: # ext_pos can be None
# pos = regex.sub('', ext_pos)
# yield pos, lemma
# except Exception, e:
# raise e
. Output only the next line. | p = Perspective('', pos_topic_words(), pos_opinion_words()) |
Based on the snippet: <|code_start|>
logger = logging.getLogger(__name__)
logging.basicConfig(format='%(levelname)s : %(message)s', level=logging.INFO)
logger.setLevel(logging.DEBUG)
logging.getLogger('inputgeneration').setLevel(logging.DEBUG)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('dir_in', help='directory containing the data '
'(manifesto project csv files)')
parser.add_argument('dir_out', help='the name of the dir where the '
'CPT corpus should be saved.')
args = parser.parse_args()
dir_in = args.dir_in
dir_out = args.dir_out
frogclient = get_frogclient()
if not os.path.exists(dir_out):
os.makedirs(dir_out)
data_files = glob.glob('{}/*.csv'.format(dir_in))
for i, data_file in enumerate(data_files):
if i % 5 == 0:
logger.info('Processing text {} of {}'.format(i + 1,
len(data_files)))
<|code_end|>
, predict the immediate next line with the help of imports:
import pandas as pd
import logging
import argparse
import os
import glob
from cptm.utils.inputgeneration import Perspective, remove_trailing_digits
from cptm.utils.dutchdata import pos_topic_words, pos_opinion_words, word_types
from cptm.utils.frog import get_frogclient, pos_and_lemmas
and context (classes, functions, sometimes code) from other files:
# Path: cptm/utils/inputgeneration.py
# class Perspective():
# def __init__(self, name, posTopic, posOpinion):
# """Initialize inputgeneration Perspective.
#
# Parameters:
# name : str
# The perspective name. Used as directory name to store the data.
# posTopic : list of strings
# List of strings specifying the pos-tags for topic words.
# posOpinion : list of strings
# List of strings specifying the pos-tags for opinion words.
# """
# self.name = name
# self.wordTypes = posTopic + posOpinion
# self.posTopic = posTopic
# self.posOpinion = posOpinion
# self.words = {}
# for w in self.wordTypes:
# self.words[w] = []
#
# def __str__(self):
# len_topic_words, len_opinion_words = self.word_lengths()
# return 'Perspective: {} - {} topic words; {} opinion words'.format(
# self.name, len_topic_words, len_opinion_words)
#
# def add(self, tag, word):
# self.words[tag].append(word)
#
# def write2file(self, out_dir, file_name):
# # create dir (if not exists)
# directory = os.path.join(out_dir, self.name)
# if not os.path.exists(directory):
# os.makedirs(directory)
#
# # write words to file
# out_file = os.path.join(directory, file_name)
# logger.debug('Writing file {} for perspective {}'.format(out_file,
# self.name))
# with codecs.open(out_file, 'wb', 'utf8') as f:
# for w in self.wordTypes:
# f.write(u'{}\n'.format(' '.join(self.words[w])))
#
# def word_lengths(self):
# len_topic_words = sum([len(self.words[w])
# for w in self.posTopic])
# len_opinion_words = sum([len(self.words[w])
# for w in self.posOpinion])
# return len_topic_words, len_opinion_words
#
# def remove_trailing_digits(word):
# """Convert words like d66 to d.
#
# In the folia files from politicalmashup, words such as d66 have been
# extracted as two words (d and 66) and only d ended up in the data input
# files. The folia files were probably created with an old version of frog,
# because currenly, words like these are parsed correctly.
#
# This function can be used when parsing and lemmatizing new text to match
# the vocabulary used in the old folia files.
# """
# regex = re.compile('^(.+?)(\d+)$', flags=re.UNICODE)
# m = regex.match(word)
# if m:
# return m.group(1)
# return word
#
# Path: cptm/utils/dutchdata.py
# def pos_topic_words():
# return ['N']
#
# def pos_opinion_words():
# return ['ADJ', 'BW', 'WW']
#
# def word_types():
# return pos_topic_words() + pos_opinion_words()
#
# Path: cptm/utils/frog.py
# def get_frogclient(port=8020):
# try:
# frogclient = FrogClient('localhost', port)
# return frogclient
# except:
# logger.error('Cannot connect to the Frog server. '
# 'Is it running at port {}?'.format(port))
# logger.info('Start the Frog server with "docker run -p '
# '127.0.0.1:{}:{} -t -i proycon/lamachine frog '
# '-S {}"'.format(port, port, port))
# sys.exit(1)
#
# def pos_and_lemmas(text, frogclient):
# # add timeout functionality (so frog won't keep parsing faulty text
# # forever)
# signal.signal(signal.SIGALRM, timeout)
# signal.alarm(300)
#
# regex = re.compile(r'\(.*\)')
#
# try:
# for data in frogclient.process(text):
# word, lemma, morph, ext_pos = data[:4]
# if ext_pos: # ext_pos can be None
# pos = regex.sub('', ext_pos)
# yield pos, lemma
# except Exception, e:
# raise e
. Output only the next line. | p = Perspective('', pos_topic_words(), pos_opinion_words()) |
Continue the code snippet: <|code_start|>logging.getLogger('inputgeneration').setLevel(logging.DEBUG)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('dir_in', help='directory containing the data '
'(manifesto project csv files)')
parser.add_argument('dir_out', help='the name of the dir where the '
'CPT corpus should be saved.')
args = parser.parse_args()
dir_in = args.dir_in
dir_out = args.dir_out
frogclient = get_frogclient()
if not os.path.exists(dir_out):
os.makedirs(dir_out)
data_files = glob.glob('{}/*.csv'.format(dir_in))
for i, data_file in enumerate(data_files):
if i % 5 == 0:
logger.info('Processing text {} of {}'.format(i + 1,
len(data_files)))
p = Perspective('', pos_topic_words(), pos_opinion_words())
df = pd.read_csv(data_file, encoding='utf-8')
text = ' '.join([line for line in df['content']])
try:
for pos, lemma in pos_and_lemmas(text, frogclient):
<|code_end|>
. Use current file imports:
import pandas as pd
import logging
import argparse
import os
import glob
from cptm.utils.inputgeneration import Perspective, remove_trailing_digits
from cptm.utils.dutchdata import pos_topic_words, pos_opinion_words, word_types
from cptm.utils.frog import get_frogclient, pos_and_lemmas
and context (classes, functions, or code) from other files:
# Path: cptm/utils/inputgeneration.py
# class Perspective():
# def __init__(self, name, posTopic, posOpinion):
# """Initialize inputgeneration Perspective.
#
# Parameters:
# name : str
# The perspective name. Used as directory name to store the data.
# posTopic : list of strings
# List of strings specifying the pos-tags for topic words.
# posOpinion : list of strings
# List of strings specifying the pos-tags for opinion words.
# """
# self.name = name
# self.wordTypes = posTopic + posOpinion
# self.posTopic = posTopic
# self.posOpinion = posOpinion
# self.words = {}
# for w in self.wordTypes:
# self.words[w] = []
#
# def __str__(self):
# len_topic_words, len_opinion_words = self.word_lengths()
# return 'Perspective: {} - {} topic words; {} opinion words'.format(
# self.name, len_topic_words, len_opinion_words)
#
# def add(self, tag, word):
# self.words[tag].append(word)
#
# def write2file(self, out_dir, file_name):
# # create dir (if not exists)
# directory = os.path.join(out_dir, self.name)
# if not os.path.exists(directory):
# os.makedirs(directory)
#
# # write words to file
# out_file = os.path.join(directory, file_name)
# logger.debug('Writing file {} for perspective {}'.format(out_file,
# self.name))
# with codecs.open(out_file, 'wb', 'utf8') as f:
# for w in self.wordTypes:
# f.write(u'{}\n'.format(' '.join(self.words[w])))
#
# def word_lengths(self):
# len_topic_words = sum([len(self.words[w])
# for w in self.posTopic])
# len_opinion_words = sum([len(self.words[w])
# for w in self.posOpinion])
# return len_topic_words, len_opinion_words
#
# def remove_trailing_digits(word):
# """Convert words like d66 to d.
#
# In the folia files from politicalmashup, words such as d66 have been
# extracted as two words (d and 66) and only d ended up in the data input
# files. The folia files were probably created with an old version of frog,
# because currenly, words like these are parsed correctly.
#
# This function can be used when parsing and lemmatizing new text to match
# the vocabulary used in the old folia files.
# """
# regex = re.compile('^(.+?)(\d+)$', flags=re.UNICODE)
# m = regex.match(word)
# if m:
# return m.group(1)
# return word
#
# Path: cptm/utils/dutchdata.py
# def pos_topic_words():
# return ['N']
#
# def pos_opinion_words():
# return ['ADJ', 'BW', 'WW']
#
# def word_types():
# return pos_topic_words() + pos_opinion_words()
#
# Path: cptm/utils/frog.py
# def get_frogclient(port=8020):
# try:
# frogclient = FrogClient('localhost', port)
# return frogclient
# except:
# logger.error('Cannot connect to the Frog server. '
# 'Is it running at port {}?'.format(port))
# logger.info('Start the Frog server with "docker run -p '
# '127.0.0.1:{}:{} -t -i proycon/lamachine frog '
# '-S {}"'.format(port, port, port))
# sys.exit(1)
#
# def pos_and_lemmas(text, frogclient):
# # add timeout functionality (so frog won't keep parsing faulty text
# # forever)
# signal.signal(signal.SIGALRM, timeout)
# signal.alarm(300)
#
# regex = re.compile(r'\(.*\)')
#
# try:
# for data in frogclient.process(text):
# word, lemma, morph, ext_pos = data[:4]
# if ext_pos: # ext_pos can be None
# pos = regex.sub('', ext_pos)
# yield pos, lemma
# except Exception, e:
# raise e
. Output only the next line. | if pos in word_types(): |
Here is a snippet: <|code_start|>#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Create input files in cptm format from manifesto project csv files.
Usage: python manifestoproject2cptm_input.py <input dir> <output dir>
"""
logger = logging.getLogger(__name__)
logging.basicConfig(format='%(levelname)s : %(message)s', level=logging.INFO)
logger.setLevel(logging.DEBUG)
logging.getLogger('inputgeneration').setLevel(logging.DEBUG)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('dir_in', help='directory containing the data '
'(manifesto project csv files)')
parser.add_argument('dir_out', help='the name of the dir where the '
'CPT corpus should be saved.')
args = parser.parse_args()
dir_in = args.dir_in
dir_out = args.dir_out
<|code_end|>
. Write the next line using the current file imports:
import pandas as pd
import logging
import argparse
import os
import glob
from cptm.utils.inputgeneration import Perspective, remove_trailing_digits
from cptm.utils.dutchdata import pos_topic_words, pos_opinion_words, word_types
from cptm.utils.frog import get_frogclient, pos_and_lemmas
and context from other files:
# Path: cptm/utils/inputgeneration.py
# class Perspective():
# def __init__(self, name, posTopic, posOpinion):
# """Initialize inputgeneration Perspective.
#
# Parameters:
# name : str
# The perspective name. Used as directory name to store the data.
# posTopic : list of strings
# List of strings specifying the pos-tags for topic words.
# posOpinion : list of strings
# List of strings specifying the pos-tags for opinion words.
# """
# self.name = name
# self.wordTypes = posTopic + posOpinion
# self.posTopic = posTopic
# self.posOpinion = posOpinion
# self.words = {}
# for w in self.wordTypes:
# self.words[w] = []
#
# def __str__(self):
# len_topic_words, len_opinion_words = self.word_lengths()
# return 'Perspective: {} - {} topic words; {} opinion words'.format(
# self.name, len_topic_words, len_opinion_words)
#
# def add(self, tag, word):
# self.words[tag].append(word)
#
# def write2file(self, out_dir, file_name):
# # create dir (if not exists)
# directory = os.path.join(out_dir, self.name)
# if not os.path.exists(directory):
# os.makedirs(directory)
#
# # write words to file
# out_file = os.path.join(directory, file_name)
# logger.debug('Writing file {} for perspective {}'.format(out_file,
# self.name))
# with codecs.open(out_file, 'wb', 'utf8') as f:
# for w in self.wordTypes:
# f.write(u'{}\n'.format(' '.join(self.words[w])))
#
# def word_lengths(self):
# len_topic_words = sum([len(self.words[w])
# for w in self.posTopic])
# len_opinion_words = sum([len(self.words[w])
# for w in self.posOpinion])
# return len_topic_words, len_opinion_words
#
# def remove_trailing_digits(word):
# """Convert words like d66 to d.
#
# In the folia files from politicalmashup, words such as d66 have been
# extracted as two words (d and 66) and only d ended up in the data input
# files. The folia files were probably created with an old version of frog,
# because currenly, words like these are parsed correctly.
#
# This function can be used when parsing and lemmatizing new text to match
# the vocabulary used in the old folia files.
# """
# regex = re.compile('^(.+?)(\d+)$', flags=re.UNICODE)
# m = regex.match(word)
# if m:
# return m.group(1)
# return word
#
# Path: cptm/utils/dutchdata.py
# def pos_topic_words():
# return ['N']
#
# def pos_opinion_words():
# return ['ADJ', 'BW', 'WW']
#
# def word_types():
# return pos_topic_words() + pos_opinion_words()
#
# Path: cptm/utils/frog.py
# def get_frogclient(port=8020):
# try:
# frogclient = FrogClient('localhost', port)
# return frogclient
# except:
# logger.error('Cannot connect to the Frog server. '
# 'Is it running at port {}?'.format(port))
# logger.info('Start the Frog server with "docker run -p '
# '127.0.0.1:{}:{} -t -i proycon/lamachine frog '
# '-S {}"'.format(port, port, port))
# sys.exit(1)
#
# def pos_and_lemmas(text, frogclient):
# # add timeout functionality (so frog won't keep parsing faulty text
# # forever)
# signal.signal(signal.SIGALRM, timeout)
# signal.alarm(300)
#
# regex = re.compile(r'\(.*\)')
#
# try:
# for data in frogclient.process(text):
# word, lemma, morph, ext_pos = data[:4]
# if ext_pos: # ext_pos can be None
# pos = regex.sub('', ext_pos)
# yield pos, lemma
# except Exception, e:
# raise e
, which may include functions, classes, or code. Output only the next line. | frogclient = get_frogclient() |
Using the snippet: <|code_start|>logger.setLevel(logging.DEBUG)
logging.getLogger('inputgeneration').setLevel(logging.DEBUG)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('dir_in', help='directory containing the data '
'(manifesto project csv files)')
parser.add_argument('dir_out', help='the name of the dir where the '
'CPT corpus should be saved.')
args = parser.parse_args()
dir_in = args.dir_in
dir_out = args.dir_out
frogclient = get_frogclient()
if not os.path.exists(dir_out):
os.makedirs(dir_out)
data_files = glob.glob('{}/*.csv'.format(dir_in))
for i, data_file in enumerate(data_files):
if i % 5 == 0:
logger.info('Processing text {} of {}'.format(i + 1,
len(data_files)))
p = Perspective('', pos_topic_words(), pos_opinion_words())
df = pd.read_csv(data_file, encoding='utf-8')
text = ' '.join([line for line in df['content']])
try:
<|code_end|>
, determine the next line of code. You have imports:
import pandas as pd
import logging
import argparse
import os
import glob
from cptm.utils.inputgeneration import Perspective, remove_trailing_digits
from cptm.utils.dutchdata import pos_topic_words, pos_opinion_words, word_types
from cptm.utils.frog import get_frogclient, pos_and_lemmas
and context (class names, function names, or code) available:
# Path: cptm/utils/inputgeneration.py
# class Perspective():
# def __init__(self, name, posTopic, posOpinion):
# """Initialize inputgeneration Perspective.
#
# Parameters:
# name : str
# The perspective name. Used as directory name to store the data.
# posTopic : list of strings
# List of strings specifying the pos-tags for topic words.
# posOpinion : list of strings
# List of strings specifying the pos-tags for opinion words.
# """
# self.name = name
# self.wordTypes = posTopic + posOpinion
# self.posTopic = posTopic
# self.posOpinion = posOpinion
# self.words = {}
# for w in self.wordTypes:
# self.words[w] = []
#
# def __str__(self):
# len_topic_words, len_opinion_words = self.word_lengths()
# return 'Perspective: {} - {} topic words; {} opinion words'.format(
# self.name, len_topic_words, len_opinion_words)
#
# def add(self, tag, word):
# self.words[tag].append(word)
#
# def write2file(self, out_dir, file_name):
# # create dir (if not exists)
# directory = os.path.join(out_dir, self.name)
# if not os.path.exists(directory):
# os.makedirs(directory)
#
# # write words to file
# out_file = os.path.join(directory, file_name)
# logger.debug('Writing file {} for perspective {}'.format(out_file,
# self.name))
# with codecs.open(out_file, 'wb', 'utf8') as f:
# for w in self.wordTypes:
# f.write(u'{}\n'.format(' '.join(self.words[w])))
#
# def word_lengths(self):
# len_topic_words = sum([len(self.words[w])
# for w in self.posTopic])
# len_opinion_words = sum([len(self.words[w])
# for w in self.posOpinion])
# return len_topic_words, len_opinion_words
#
# def remove_trailing_digits(word):
# """Convert words like d66 to d.
#
# In the folia files from politicalmashup, words such as d66 have been
# extracted as two words (d and 66) and only d ended up in the data input
# files. The folia files were probably created with an old version of frog,
# because currenly, words like these are parsed correctly.
#
# This function can be used when parsing and lemmatizing new text to match
# the vocabulary used in the old folia files.
# """
# regex = re.compile('^(.+?)(\d+)$', flags=re.UNICODE)
# m = regex.match(word)
# if m:
# return m.group(1)
# return word
#
# Path: cptm/utils/dutchdata.py
# def pos_topic_words():
# return ['N']
#
# def pos_opinion_words():
# return ['ADJ', 'BW', 'WW']
#
# def word_types():
# return pos_topic_words() + pos_opinion_words()
#
# Path: cptm/utils/frog.py
# def get_frogclient(port=8020):
# try:
# frogclient = FrogClient('localhost', port)
# return frogclient
# except:
# logger.error('Cannot connect to the Frog server. '
# 'Is it running at port {}?'.format(port))
# logger.info('Start the Frog server with "docker run -p '
# '127.0.0.1:{}:{} -t -i proycon/lamachine frog '
# '-S {}"'.format(port, port, port))
# sys.exit(1)
#
# def pos_and_lemmas(text, frogclient):
# # add timeout functionality (so frog won't keep parsing faulty text
# # forever)
# signal.signal(signal.SIGALRM, timeout)
# signal.alarm(300)
#
# regex = re.compile(r'\(.*\)')
#
# try:
# for data in frogclient.process(text):
# word, lemma, morph, ext_pos = data[:4]
# if ext_pos: # ext_pos can be None
# pos = regex.sub('', ext_pos)
# yield pos, lemma
# except Exception, e:
# raise e
. Output only the next line. | for pos, lemma in pos_and_lemmas(text, frogclient): |
Based on the snippet: <|code_start|> print '{},{}'.format(year, len(data_files))
years.sort()
min_year = years[0]
print 'min year', min_year
max_year = years[-1]
print 'max year', max_year
data_files = glob.glob('{}data_folia/*.xml.gz'.format(min_year))
for df in data_files:
f = gzip.open(df)
context = etree.iterparse(f, events=('end',), tag=date_tag,
huge_tree=True)
for event, elem in context:
d = datetime.datetime.strptime(elem.text, "%Y-%m-%d").date()
if d < min_date:
min_date = d
data_files = glob.glob('{}data_folia/*.xml.gz'.format(max_year))
for df in data_files:
f = gzip.open(df)
context = etree.iterparse(f, events=('end',), tag=date_tag,
huge_tree=True)
for event, elem in context:
d = datetime.datetime.strptime(elem.text, "%Y-%m-%d").date()
if d > max_date:
max_date = d
print 'time period: ', min_date, max_date
<|code_end|>
, predict the immediate next line with the help of imports:
import logging
import argparse
import glob
import gzip
import datetime
from lxml import etree
from cptm.utils.experiment import load_config, get_corpus
and context (classes, functions, sometimes code) from other files:
# Path: cptm/utils/experiment.py
# def load_config(fName):
# with open(fName) as f:
# config = json.load(f)
#
# logger.debug('configuration of experiment: ')
# params = ['{}: {}'.format(p, v) for p, v in config.iteritems()]
# for p in params:
# logger.debug(p)
#
# params = {}
# params['inputData'] = config.get('inputData')
# params['outDir'] = config.get('outDir', '/{}')
# params['testSplit'] = config.get('testSplit', 20)
# params['minFreq'] = config.get('minFreq')
# params['removeTopTF'] = config.get('removeTopTF')
# params['removeTopDF'] = config.get('removeTopDF')
# params['nIter'] = config.get('nIter', 200)
# params['beta'] = config.get('beta', 0.02)
# params['beta_o'] = config.get('beta_o', 0.02)
# params['expNumTopics'] = config.get('expNumTopics', range(20, 201, 20))
# params['nTopics'] = config.get('nTopics')
# params['nProcesses'] = config.get('nProcesses', None)
# params['topicLines'] = config.get('topicLines', [0])
# params['opinionLines'] = config.get('opinionLines', [1])
# params['sampleEstimateStart'] = config.get('sampleEstimateStart')
# params['sampleEstimateEnd'] = config.get('sampleEstimateEnd')
#
# return params
#
# def get_corpus(params):
# out_dir = params.get('outDir')
# files = glob(params.get('inputData'))
#
# if not os.path.isfile(out_dir.format('corpus.json')):
# corpus = CPTCorpus(files,
# testSplit=params.get('testSplit'),
# topicLines=params.get('topicLines'),
# opinionLines=params.get('opinionLines'))
# minFreq = params.get('minFreq')
# removeTopTF = params.get('removeTopTF')
# removeTopDF = params.get('removeTopDF')
# if (not minFreq is None) or (not removeTopTF is None) or \
# (not removeTopDF is None):
# corpus.filter_dictionaries(minFreq=minFreq,
# removeTopTF=removeTopTF,
# removeTopDF=removeTopDF)
# corpus.save_dictionaries(directory=out_dir.format(''))
# corpus.save(out_dir.format('corpus.json'))
# else:
# corpus = CPTCorpus.load(file_name=out_dir.format('corpus.json'),
# topicLines=params.get('topicLines'),
# opinionLines=params.get('opinionLines'),
# topicDict=out_dir.format('topicDict.dict'),
# opinionDict=out_dir.format('opinionDict.dict'))
# return corpus
. Output only the next line. | config = load_config(args.json) |
Continue the code snippet: <|code_start|>Usage: python cptm/experiment_calculate_perplexity.py /path/to/experiment.json.
"""
def calculate_perplexity(config, corpus, nPerplexity, nTopics):
sampler = get_sampler(config, corpus, nTopics, initialize=False)
results = []
for s in nPerplexity:
logger.info('doing perplexity calculation ({}, {})'.format(nTopics, s))
tw_perp, ow_perp = sampler.perplexity(index=s)
results.append((nTopics, s, tw_perp, ow_perp))
logger.info('finished perplexity calculation for {} topics'.
format(nTopics))
return results
logger = logging.getLogger(__name__)
logging.basicConfig(format='%(levelname)s : %(message)s', level=logging.INFO)
logging.getLogger('gensim').setLevel(logging.ERROR)
logging.getLogger('CPTCorpus').setLevel(logging.ERROR)
logging.getLogger('CPT_Gibbs').setLevel(logging.ERROR)
parser = argparse.ArgumentParser()
parser.add_argument('json', help='json file containing experiment '
'configuration.')
args = parser.parse_args()
<|code_end|>
. Use current file imports:
import pandas as pd
import logging
import argparse
from multiprocessing import Pool
from cptm.utils.experiment import load_config, get_corpus, get_sampler
and context (classes, functions, or code) from other files:
# Path: cptm/utils/experiment.py
# def load_config(fName):
# with open(fName) as f:
# config = json.load(f)
#
# logger.debug('configuration of experiment: ')
# params = ['{}: {}'.format(p, v) for p, v in config.iteritems()]
# for p in params:
# logger.debug(p)
#
# params = {}
# params['inputData'] = config.get('inputData')
# params['outDir'] = config.get('outDir', '/{}')
# params['testSplit'] = config.get('testSplit', 20)
# params['minFreq'] = config.get('minFreq')
# params['removeTopTF'] = config.get('removeTopTF')
# params['removeTopDF'] = config.get('removeTopDF')
# params['nIter'] = config.get('nIter', 200)
# params['beta'] = config.get('beta', 0.02)
# params['beta_o'] = config.get('beta_o', 0.02)
# params['expNumTopics'] = config.get('expNumTopics', range(20, 201, 20))
# params['nTopics'] = config.get('nTopics')
# params['nProcesses'] = config.get('nProcesses', None)
# params['topicLines'] = config.get('topicLines', [0])
# params['opinionLines'] = config.get('opinionLines', [1])
# params['sampleEstimateStart'] = config.get('sampleEstimateStart')
# params['sampleEstimateEnd'] = config.get('sampleEstimateEnd')
#
# return params
#
# def get_corpus(params):
# out_dir = params.get('outDir')
# files = glob(params.get('inputData'))
#
# if not os.path.isfile(out_dir.format('corpus.json')):
# corpus = CPTCorpus(files,
# testSplit=params.get('testSplit'),
# topicLines=params.get('topicLines'),
# opinionLines=params.get('opinionLines'))
# minFreq = params.get('minFreq')
# removeTopTF = params.get('removeTopTF')
# removeTopDF = params.get('removeTopDF')
# if (not minFreq is None) or (not removeTopTF is None) or \
# (not removeTopDF is None):
# corpus.filter_dictionaries(minFreq=minFreq,
# removeTopTF=removeTopTF,
# removeTopDF=removeTopDF)
# corpus.save_dictionaries(directory=out_dir.format(''))
# corpus.save(out_dir.format('corpus.json'))
# else:
# corpus = CPTCorpus.load(file_name=out_dir.format('corpus.json'),
# topicLines=params.get('topicLines'),
# opinionLines=params.get('opinionLines'),
# topicDict=out_dir.format('topicDict.dict'),
# opinionDict=out_dir.format('opinionDict.dict'))
# return corpus
#
# def get_sampler(params, corpus, nTopics=None, initialize=True):
# if nTopics is None:
# nTopics = params.get('nTopics')
# out_dir = params.get('outDir')
# nIter = params.get('nIter')
# alpha = 50.0/nTopics
# beta = params.get('beta')
# beta_o = params.get('beta_o')
# logger.info('creating Gibbs sampler (nTopics: {}, nIter: {}, alpha: {}, '
# 'beta: {}, beta_o: {})'.format(nTopics, nIter, alpha, beta,
# beta_o))
# sampler = GibbsSampler(corpus, nTopics=nTopics, nIter=nIter,
# alpha=alpha, beta=beta, beta_o=beta_o,
# out_dir=out_dir.format(nTopics),
# initialize=initialize)
# return sampler
. Output only the next line. | config = load_config(args.json) |
Given snippet: <|code_start|>"""
def calculate_perplexity(config, corpus, nPerplexity, nTopics):
sampler = get_sampler(config, corpus, nTopics, initialize=False)
results = []
for s in nPerplexity:
logger.info('doing perplexity calculation ({}, {})'.format(nTopics, s))
tw_perp, ow_perp = sampler.perplexity(index=s)
results.append((nTopics, s, tw_perp, ow_perp))
logger.info('finished perplexity calculation for {} topics'.
format(nTopics))
return results
logger = logging.getLogger(__name__)
logging.basicConfig(format='%(levelname)s : %(message)s', level=logging.INFO)
logging.getLogger('gensim').setLevel(logging.ERROR)
logging.getLogger('CPTCorpus').setLevel(logging.ERROR)
logging.getLogger('CPT_Gibbs').setLevel(logging.ERROR)
parser = argparse.ArgumentParser()
parser.add_argument('json', help='json file containing experiment '
'configuration.')
args = parser.parse_args()
config = load_config(args.json)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import pandas as pd
import logging
import argparse
from multiprocessing import Pool
from cptm.utils.experiment import load_config, get_corpus, get_sampler
and context:
# Path: cptm/utils/experiment.py
# def load_config(fName):
# with open(fName) as f:
# config = json.load(f)
#
# logger.debug('configuration of experiment: ')
# params = ['{}: {}'.format(p, v) for p, v in config.iteritems()]
# for p in params:
# logger.debug(p)
#
# params = {}
# params['inputData'] = config.get('inputData')
# params['outDir'] = config.get('outDir', '/{}')
# params['testSplit'] = config.get('testSplit', 20)
# params['minFreq'] = config.get('minFreq')
# params['removeTopTF'] = config.get('removeTopTF')
# params['removeTopDF'] = config.get('removeTopDF')
# params['nIter'] = config.get('nIter', 200)
# params['beta'] = config.get('beta', 0.02)
# params['beta_o'] = config.get('beta_o', 0.02)
# params['expNumTopics'] = config.get('expNumTopics', range(20, 201, 20))
# params['nTopics'] = config.get('nTopics')
# params['nProcesses'] = config.get('nProcesses', None)
# params['topicLines'] = config.get('topicLines', [0])
# params['opinionLines'] = config.get('opinionLines', [1])
# params['sampleEstimateStart'] = config.get('sampleEstimateStart')
# params['sampleEstimateEnd'] = config.get('sampleEstimateEnd')
#
# return params
#
# def get_corpus(params):
# out_dir = params.get('outDir')
# files = glob(params.get('inputData'))
#
# if not os.path.isfile(out_dir.format('corpus.json')):
# corpus = CPTCorpus(files,
# testSplit=params.get('testSplit'),
# topicLines=params.get('topicLines'),
# opinionLines=params.get('opinionLines'))
# minFreq = params.get('minFreq')
# removeTopTF = params.get('removeTopTF')
# removeTopDF = params.get('removeTopDF')
# if (not minFreq is None) or (not removeTopTF is None) or \
# (not removeTopDF is None):
# corpus.filter_dictionaries(minFreq=minFreq,
# removeTopTF=removeTopTF,
# removeTopDF=removeTopDF)
# corpus.save_dictionaries(directory=out_dir.format(''))
# corpus.save(out_dir.format('corpus.json'))
# else:
# corpus = CPTCorpus.load(file_name=out_dir.format('corpus.json'),
# topicLines=params.get('topicLines'),
# opinionLines=params.get('opinionLines'),
# topicDict=out_dir.format('topicDict.dict'),
# opinionDict=out_dir.format('opinionDict.dict'))
# return corpus
#
# def get_sampler(params, corpus, nTopics=None, initialize=True):
# if nTopics is None:
# nTopics = params.get('nTopics')
# out_dir = params.get('outDir')
# nIter = params.get('nIter')
# alpha = 50.0/nTopics
# beta = params.get('beta')
# beta_o = params.get('beta_o')
# logger.info('creating Gibbs sampler (nTopics: {}, nIter: {}, alpha: {}, '
# 'beta: {}, beta_o: {})'.format(nTopics, nIter, alpha, beta,
# beta_o))
# sampler = GibbsSampler(corpus, nTopics=nTopics, nIter=nIter,
# alpha=alpha, beta=beta, beta_o=beta_o,
# out_dir=out_dir.format(nTopics),
# initialize=initialize)
# return sampler
which might include code, classes, or functions. Output only the next line. | corpus = get_corpus(config) |
Based on the snippet: <|code_start|>"""Calculate opinion perplexity for different numbers of topics
Calclulate opinion perplexity for the test set as described in [Fang et al.
2012] section 5.1.1.
This script should be run after experiment_number_of_topics.py.
Usage: python cptm/experiment_calculate_perplexity.py /path/to/experiment.json.
"""
def calculate_perplexity(config, corpus, nPerplexity, nTopics):
<|code_end|>
, predict the immediate next line with the help of imports:
import pandas as pd
import logging
import argparse
from multiprocessing import Pool
from cptm.utils.experiment import load_config, get_corpus, get_sampler
and context (classes, functions, sometimes code) from other files:
# Path: cptm/utils/experiment.py
# def load_config(fName):
# with open(fName) as f:
# config = json.load(f)
#
# logger.debug('configuration of experiment: ')
# params = ['{}: {}'.format(p, v) for p, v in config.iteritems()]
# for p in params:
# logger.debug(p)
#
# params = {}
# params['inputData'] = config.get('inputData')
# params['outDir'] = config.get('outDir', '/{}')
# params['testSplit'] = config.get('testSplit', 20)
# params['minFreq'] = config.get('minFreq')
# params['removeTopTF'] = config.get('removeTopTF')
# params['removeTopDF'] = config.get('removeTopDF')
# params['nIter'] = config.get('nIter', 200)
# params['beta'] = config.get('beta', 0.02)
# params['beta_o'] = config.get('beta_o', 0.02)
# params['expNumTopics'] = config.get('expNumTopics', range(20, 201, 20))
# params['nTopics'] = config.get('nTopics')
# params['nProcesses'] = config.get('nProcesses', None)
# params['topicLines'] = config.get('topicLines', [0])
# params['opinionLines'] = config.get('opinionLines', [1])
# params['sampleEstimateStart'] = config.get('sampleEstimateStart')
# params['sampleEstimateEnd'] = config.get('sampleEstimateEnd')
#
# return params
#
# def get_corpus(params):
# out_dir = params.get('outDir')
# files = glob(params.get('inputData'))
#
# if not os.path.isfile(out_dir.format('corpus.json')):
# corpus = CPTCorpus(files,
# testSplit=params.get('testSplit'),
# topicLines=params.get('topicLines'),
# opinionLines=params.get('opinionLines'))
# minFreq = params.get('minFreq')
# removeTopTF = params.get('removeTopTF')
# removeTopDF = params.get('removeTopDF')
# if (not minFreq is None) or (not removeTopTF is None) or \
# (not removeTopDF is None):
# corpus.filter_dictionaries(minFreq=minFreq,
# removeTopTF=removeTopTF,
# removeTopDF=removeTopDF)
# corpus.save_dictionaries(directory=out_dir.format(''))
# corpus.save(out_dir.format('corpus.json'))
# else:
# corpus = CPTCorpus.load(file_name=out_dir.format('corpus.json'),
# topicLines=params.get('topicLines'),
# opinionLines=params.get('opinionLines'),
# topicDict=out_dir.format('topicDict.dict'),
# opinionDict=out_dir.format('opinionDict.dict'))
# return corpus
#
# def get_sampler(params, corpus, nTopics=None, initialize=True):
# if nTopics is None:
# nTopics = params.get('nTopics')
# out_dir = params.get('outDir')
# nIter = params.get('nIter')
# alpha = 50.0/nTopics
# beta = params.get('beta')
# beta_o = params.get('beta_o')
# logger.info('creating Gibbs sampler (nTopics: {}, nIter: {}, alpha: {}, '
# 'beta: {}, beta_o: {})'.format(nTopics, nIter, alpha, beta,
# beta_o))
# sampler = GibbsSampler(corpus, nTopics=nTopics, nIter=nIter,
# alpha=alpha, beta=beta, beta_o=beta_o,
# out_dir=out_dir.format(nTopics),
# initialize=initialize)
# return sampler
. Output only the next line. | sampler = get_sampler(config, corpus, nTopics, initialize=False) |
Next line prediction: <|code_start|>
def setup():
global jsonFile
global config
global nTopics
jsonFile = 'config.json'
# create cofig.json
params = {}
with open(jsonFile, 'wb') as f:
dump(params, f, sort_keys=True, indent=4)
<|code_end|>
. Use current file imports:
(from nose.tools import assert_equal, assert_false
from os import remove
from os.path import join
from json import dump
from cptm.utils.experiment import load_config, add_parameter, thetaFileName, \
topicFileName, opinionFileName, tarFileName, experimentName)
and context including class names, function names, or small code snippets from other files:
# Path: cptm/utils/experiment.py
# def load_config(fName):
# with open(fName) as f:
# config = json.load(f)
#
# logger.debug('configuration of experiment: ')
# params = ['{}: {}'.format(p, v) for p, v in config.iteritems()]
# for p in params:
# logger.debug(p)
#
# params = {}
# params['inputData'] = config.get('inputData')
# params['outDir'] = config.get('outDir', '/{}')
# params['testSplit'] = config.get('testSplit', 20)
# params['minFreq'] = config.get('minFreq')
# params['removeTopTF'] = config.get('removeTopTF')
# params['removeTopDF'] = config.get('removeTopDF')
# params['nIter'] = config.get('nIter', 200)
# params['beta'] = config.get('beta', 0.02)
# params['beta_o'] = config.get('beta_o', 0.02)
# params['expNumTopics'] = config.get('expNumTopics', range(20, 201, 20))
# params['nTopics'] = config.get('nTopics')
# params['nProcesses'] = config.get('nProcesses', None)
# params['topicLines'] = config.get('topicLines', [0])
# params['opinionLines'] = config.get('opinionLines', [1])
# params['sampleEstimateStart'] = config.get('sampleEstimateStart')
# params['sampleEstimateEnd'] = config.get('sampleEstimateEnd')
#
# return params
#
# def add_parameter(name, value, fName):
# with open(fName) as f:
# config = json.load(f)
# config[name] = value
# with open(fName, 'w') as f:
# json.dump(config, f)
#
# def thetaFileName(params):
# nTopics = params.get('nTopics')
# return os.path.join(params.get('outDir').format(''),
# 'theta_{}.csv'.format(nTopics))
#
# def topicFileName(params):
# nTopics = params.get('nTopics')
# return os.path.join(params.get('outDir').format(''),
# 'topics_{}.csv'.format(nTopics))
#
# def opinionFileName(params, name):
# nTopics = params.get('nTopics')
# return os.path.join(params.get('outDir').format(''),
# 'opinions_{}_{}.csv'.format(name, nTopics))
#
# def tarFileName(params):
# nTopics = params.get('nTopics')
# name = experimentName(params)
# return os.path.join(params.get('outDir').format(''),
# '{}_{}.tgz'.format(name, nTopics))
#
# def experimentName(params):
# fName = params.get('outDir')
# fName = fName.replace('/{}', '')
# _p, name = os.path.split(fName)
# return name
. Output only the next line. | config = load_config(jsonFile) |
Using the snippet: <|code_start|>
def test_load_config_default_values():
params = {}
params['inputData'] = None
params['outDir'] = '/{}'
params['testSplit'] = 20
params['minFreq'] = None
params['removeTopTF'] = None
params['removeTopDF'] = None
params['nIter'] = 200
params['beta'] = 0.02
params['beta_o'] = 0.02
params['expNumTopics'] = range(20, 201, 20)
params['nTopics'] = None
params['nProcesses'] = None
params['topicLines'] = [0]
params['opinionLines'] = [1]
params['sampleEstimateStart'] = None
params['sampleEstimateEnd'] = None
for p, v in params.iteritems():
yield assert_equal, v, config[p]
def test_add_parameter():
pName = 'nTopics'
yield assert_false, hasattr(config, pName)
<|code_end|>
, determine the next line of code. You have imports:
from nose.tools import assert_equal, assert_false
from os import remove
from os.path import join
from json import dump
from cptm.utils.experiment import load_config, add_parameter, thetaFileName, \
topicFileName, opinionFileName, tarFileName, experimentName
and context (class names, function names, or code) available:
# Path: cptm/utils/experiment.py
# def load_config(fName):
# with open(fName) as f:
# config = json.load(f)
#
# logger.debug('configuration of experiment: ')
# params = ['{}: {}'.format(p, v) for p, v in config.iteritems()]
# for p in params:
# logger.debug(p)
#
# params = {}
# params['inputData'] = config.get('inputData')
# params['outDir'] = config.get('outDir', '/{}')
# params['testSplit'] = config.get('testSplit', 20)
# params['minFreq'] = config.get('minFreq')
# params['removeTopTF'] = config.get('removeTopTF')
# params['removeTopDF'] = config.get('removeTopDF')
# params['nIter'] = config.get('nIter', 200)
# params['beta'] = config.get('beta', 0.02)
# params['beta_o'] = config.get('beta_o', 0.02)
# params['expNumTopics'] = config.get('expNumTopics', range(20, 201, 20))
# params['nTopics'] = config.get('nTopics')
# params['nProcesses'] = config.get('nProcesses', None)
# params['topicLines'] = config.get('topicLines', [0])
# params['opinionLines'] = config.get('opinionLines', [1])
# params['sampleEstimateStart'] = config.get('sampleEstimateStart')
# params['sampleEstimateEnd'] = config.get('sampleEstimateEnd')
#
# return params
#
# def add_parameter(name, value, fName):
# with open(fName) as f:
# config = json.load(f)
# config[name] = value
# with open(fName, 'w') as f:
# json.dump(config, f)
#
# def thetaFileName(params):
# nTopics = params.get('nTopics')
# return os.path.join(params.get('outDir').format(''),
# 'theta_{}.csv'.format(nTopics))
#
# def topicFileName(params):
# nTopics = params.get('nTopics')
# return os.path.join(params.get('outDir').format(''),
# 'topics_{}.csv'.format(nTopics))
#
# def opinionFileName(params, name):
# nTopics = params.get('nTopics')
# return os.path.join(params.get('outDir').format(''),
# 'opinions_{}_{}.csv'.format(name, nTopics))
#
# def tarFileName(params):
# nTopics = params.get('nTopics')
# name = experimentName(params)
# return os.path.join(params.get('outDir').format(''),
# '{}_{}.tgz'.format(name, nTopics))
#
# def experimentName(params):
# fName = params.get('outDir')
# fName = fName.replace('/{}', '')
# _p, name = os.path.split(fName)
# return name
. Output only the next line. | add_parameter(pName, nTopics, jsonFile) |
Based on the snippet: <|code_start|> params['removeTopTF'] = None
params['removeTopDF'] = None
params['nIter'] = 200
params['beta'] = 0.02
params['beta_o'] = 0.02
params['expNumTopics'] = range(20, 201, 20)
params['nTopics'] = None
params['nProcesses'] = None
params['topicLines'] = [0]
params['opinionLines'] = [1]
params['sampleEstimateStart'] = None
params['sampleEstimateEnd'] = None
for p, v in params.iteritems():
yield assert_equal, v, config[p]
def test_add_parameter():
pName = 'nTopics'
yield assert_false, hasattr(config, pName)
add_parameter(pName, nTopics, jsonFile)
config2 = load_config(jsonFile)
yield assert_equal, config2[pName], nTopics
def test_thetaFileName():
config['nTopics'] = nTopics
<|code_end|>
, predict the immediate next line with the help of imports:
from nose.tools import assert_equal, assert_false
from os import remove
from os.path import join
from json import dump
from cptm.utils.experiment import load_config, add_parameter, thetaFileName, \
topicFileName, opinionFileName, tarFileName, experimentName
and context (classes, functions, sometimes code) from other files:
# Path: cptm/utils/experiment.py
# def load_config(fName):
# with open(fName) as f:
# config = json.load(f)
#
# logger.debug('configuration of experiment: ')
# params = ['{}: {}'.format(p, v) for p, v in config.iteritems()]
# for p in params:
# logger.debug(p)
#
# params = {}
# params['inputData'] = config.get('inputData')
# params['outDir'] = config.get('outDir', '/{}')
# params['testSplit'] = config.get('testSplit', 20)
# params['minFreq'] = config.get('minFreq')
# params['removeTopTF'] = config.get('removeTopTF')
# params['removeTopDF'] = config.get('removeTopDF')
# params['nIter'] = config.get('nIter', 200)
# params['beta'] = config.get('beta', 0.02)
# params['beta_o'] = config.get('beta_o', 0.02)
# params['expNumTopics'] = config.get('expNumTopics', range(20, 201, 20))
# params['nTopics'] = config.get('nTopics')
# params['nProcesses'] = config.get('nProcesses', None)
# params['topicLines'] = config.get('topicLines', [0])
# params['opinionLines'] = config.get('opinionLines', [1])
# params['sampleEstimateStart'] = config.get('sampleEstimateStart')
# params['sampleEstimateEnd'] = config.get('sampleEstimateEnd')
#
# return params
#
# def add_parameter(name, value, fName):
# with open(fName) as f:
# config = json.load(f)
# config[name] = value
# with open(fName, 'w') as f:
# json.dump(config, f)
#
# def thetaFileName(params):
# nTopics = params.get('nTopics')
# return os.path.join(params.get('outDir').format(''),
# 'theta_{}.csv'.format(nTopics))
#
# def topicFileName(params):
# nTopics = params.get('nTopics')
# return os.path.join(params.get('outDir').format(''),
# 'topics_{}.csv'.format(nTopics))
#
# def opinionFileName(params, name):
# nTopics = params.get('nTopics')
# return os.path.join(params.get('outDir').format(''),
# 'opinions_{}_{}.csv'.format(name, nTopics))
#
# def tarFileName(params):
# nTopics = params.get('nTopics')
# name = experimentName(params)
# return os.path.join(params.get('outDir').format(''),
# '{}_{}.tgz'.format(name, nTopics))
#
# def experimentName(params):
# fName = params.get('outDir')
# fName = fName.replace('/{}', '')
# _p, name = os.path.split(fName)
# return name
. Output only the next line. | fName = thetaFileName(config) |
Continue the code snippet: <|code_start|> params['nTopics'] = None
params['nProcesses'] = None
params['topicLines'] = [0]
params['opinionLines'] = [1]
params['sampleEstimateStart'] = None
params['sampleEstimateEnd'] = None
for p, v in params.iteritems():
yield assert_equal, v, config[p]
def test_add_parameter():
pName = 'nTopics'
yield assert_false, hasattr(config, pName)
add_parameter(pName, nTopics, jsonFile)
config2 = load_config(jsonFile)
yield assert_equal, config2[pName], nTopics
def test_thetaFileName():
config['nTopics'] = nTopics
fName = thetaFileName(config)
assert_equal(fName, '/theta_{}.csv'.format(nTopics))
def test_topicFileName():
config['nTopics'] = nTopics
<|code_end|>
. Use current file imports:
from nose.tools import assert_equal, assert_false
from os import remove
from os.path import join
from json import dump
from cptm.utils.experiment import load_config, add_parameter, thetaFileName, \
topicFileName, opinionFileName, tarFileName, experimentName
and context (classes, functions, or code) from other files:
# Path: cptm/utils/experiment.py
# def load_config(fName):
# with open(fName) as f:
# config = json.load(f)
#
# logger.debug('configuration of experiment: ')
# params = ['{}: {}'.format(p, v) for p, v in config.iteritems()]
# for p in params:
# logger.debug(p)
#
# params = {}
# params['inputData'] = config.get('inputData')
# params['outDir'] = config.get('outDir', '/{}')
# params['testSplit'] = config.get('testSplit', 20)
# params['minFreq'] = config.get('minFreq')
# params['removeTopTF'] = config.get('removeTopTF')
# params['removeTopDF'] = config.get('removeTopDF')
# params['nIter'] = config.get('nIter', 200)
# params['beta'] = config.get('beta', 0.02)
# params['beta_o'] = config.get('beta_o', 0.02)
# params['expNumTopics'] = config.get('expNumTopics', range(20, 201, 20))
# params['nTopics'] = config.get('nTopics')
# params['nProcesses'] = config.get('nProcesses', None)
# params['topicLines'] = config.get('topicLines', [0])
# params['opinionLines'] = config.get('opinionLines', [1])
# params['sampleEstimateStart'] = config.get('sampleEstimateStart')
# params['sampleEstimateEnd'] = config.get('sampleEstimateEnd')
#
# return params
#
# def add_parameter(name, value, fName):
# with open(fName) as f:
# config = json.load(f)
# config[name] = value
# with open(fName, 'w') as f:
# json.dump(config, f)
#
# def thetaFileName(params):
# nTopics = params.get('nTopics')
# return os.path.join(params.get('outDir').format(''),
# 'theta_{}.csv'.format(nTopics))
#
# def topicFileName(params):
# nTopics = params.get('nTopics')
# return os.path.join(params.get('outDir').format(''),
# 'topics_{}.csv'.format(nTopics))
#
# def opinionFileName(params, name):
# nTopics = params.get('nTopics')
# return os.path.join(params.get('outDir').format(''),
# 'opinions_{}_{}.csv'.format(name, nTopics))
#
# def tarFileName(params):
# nTopics = params.get('nTopics')
# name = experimentName(params)
# return os.path.join(params.get('outDir').format(''),
# '{}_{}.tgz'.format(name, nTopics))
#
# def experimentName(params):
# fName = params.get('outDir')
# fName = fName.replace('/{}', '')
# _p, name = os.path.split(fName)
# return name
. Output only the next line. | fName = topicFileName(config) |
Given the code snippet: <|code_start|> yield assert_equal, v, config[p]
def test_add_parameter():
pName = 'nTopics'
yield assert_false, hasattr(config, pName)
add_parameter(pName, nTopics, jsonFile)
config2 = load_config(jsonFile)
yield assert_equal, config2[pName], nTopics
def test_thetaFileName():
config['nTopics'] = nTopics
fName = thetaFileName(config)
assert_equal(fName, '/theta_{}.csv'.format(nTopics))
def test_topicFileName():
config['nTopics'] = nTopics
fName = topicFileName(config)
assert_equal(fName, '/topics_{}.csv'.format(nTopics))
def test_opinionFileName():
config['nTopics'] = nTopics
perspectives = ['p0', 'p1', 'p2']
for p in perspectives:
<|code_end|>
, generate the next line using the imports in this file:
from nose.tools import assert_equal, assert_false
from os import remove
from os.path import join
from json import dump
from cptm.utils.experiment import load_config, add_parameter, thetaFileName, \
topicFileName, opinionFileName, tarFileName, experimentName
and context (functions, classes, or occasionally code) from other files:
# Path: cptm/utils/experiment.py
# def load_config(fName):
# with open(fName) as f:
# config = json.load(f)
#
# logger.debug('configuration of experiment: ')
# params = ['{}: {}'.format(p, v) for p, v in config.iteritems()]
# for p in params:
# logger.debug(p)
#
# params = {}
# params['inputData'] = config.get('inputData')
# params['outDir'] = config.get('outDir', '/{}')
# params['testSplit'] = config.get('testSplit', 20)
# params['minFreq'] = config.get('minFreq')
# params['removeTopTF'] = config.get('removeTopTF')
# params['removeTopDF'] = config.get('removeTopDF')
# params['nIter'] = config.get('nIter', 200)
# params['beta'] = config.get('beta', 0.02)
# params['beta_o'] = config.get('beta_o', 0.02)
# params['expNumTopics'] = config.get('expNumTopics', range(20, 201, 20))
# params['nTopics'] = config.get('nTopics')
# params['nProcesses'] = config.get('nProcesses', None)
# params['topicLines'] = config.get('topicLines', [0])
# params['opinionLines'] = config.get('opinionLines', [1])
# params['sampleEstimateStart'] = config.get('sampleEstimateStart')
# params['sampleEstimateEnd'] = config.get('sampleEstimateEnd')
#
# return params
#
# def add_parameter(name, value, fName):
# with open(fName) as f:
# config = json.load(f)
# config[name] = value
# with open(fName, 'w') as f:
# json.dump(config, f)
#
# def thetaFileName(params):
# nTopics = params.get('nTopics')
# return os.path.join(params.get('outDir').format(''),
# 'theta_{}.csv'.format(nTopics))
#
# def topicFileName(params):
# nTopics = params.get('nTopics')
# return os.path.join(params.get('outDir').format(''),
# 'topics_{}.csv'.format(nTopics))
#
# def opinionFileName(params, name):
# nTopics = params.get('nTopics')
# return os.path.join(params.get('outDir').format(''),
# 'opinions_{}_{}.csv'.format(name, nTopics))
#
# def tarFileName(params):
# nTopics = params.get('nTopics')
# name = experimentName(params)
# return os.path.join(params.get('outDir').format(''),
# '{}_{}.tgz'.format(name, nTopics))
#
# def experimentName(params):
# fName = params.get('outDir')
# fName = fName.replace('/{}', '')
# _p, name = os.path.split(fName)
# return name
. Output only the next line. | fName = opinionFileName(config, p) |
Continue the code snippet: <|code_start|> config['nTopics'] = nTopics
fName = thetaFileName(config)
assert_equal(fName, '/theta_{}.csv'.format(nTopics))
def test_topicFileName():
config['nTopics'] = nTopics
fName = topicFileName(config)
assert_equal(fName, '/topics_{}.csv'.format(nTopics))
def test_opinionFileName():
config['nTopics'] = nTopics
perspectives = ['p0', 'p1', 'p2']
for p in perspectives:
fName = opinionFileName(config, p)
yield assert_equal, fName, '/opinions_{}_{}.csv'.format(p, nTopics)
def test_experimentName():
config['outDir'] = '/tmp/test/{}'
assert_equal('test', experimentName(config))
def test_tarFileName():
config['outDir'] = '/{}'
config['nTopics'] = nTopics
name = experimentName(config)
<|code_end|>
. Use current file imports:
from nose.tools import assert_equal, assert_false
from os import remove
from os.path import join
from json import dump
from cptm.utils.experiment import load_config, add_parameter, thetaFileName, \
topicFileName, opinionFileName, tarFileName, experimentName
and context (classes, functions, or code) from other files:
# Path: cptm/utils/experiment.py
# def load_config(fName):
# with open(fName) as f:
# config = json.load(f)
#
# logger.debug('configuration of experiment: ')
# params = ['{}: {}'.format(p, v) for p, v in config.iteritems()]
# for p in params:
# logger.debug(p)
#
# params = {}
# params['inputData'] = config.get('inputData')
# params['outDir'] = config.get('outDir', '/{}')
# params['testSplit'] = config.get('testSplit', 20)
# params['minFreq'] = config.get('minFreq')
# params['removeTopTF'] = config.get('removeTopTF')
# params['removeTopDF'] = config.get('removeTopDF')
# params['nIter'] = config.get('nIter', 200)
# params['beta'] = config.get('beta', 0.02)
# params['beta_o'] = config.get('beta_o', 0.02)
# params['expNumTopics'] = config.get('expNumTopics', range(20, 201, 20))
# params['nTopics'] = config.get('nTopics')
# params['nProcesses'] = config.get('nProcesses', None)
# params['topicLines'] = config.get('topicLines', [0])
# params['opinionLines'] = config.get('opinionLines', [1])
# params['sampleEstimateStart'] = config.get('sampleEstimateStart')
# params['sampleEstimateEnd'] = config.get('sampleEstimateEnd')
#
# return params
#
# def add_parameter(name, value, fName):
# with open(fName) as f:
# config = json.load(f)
# config[name] = value
# with open(fName, 'w') as f:
# json.dump(config, f)
#
# def thetaFileName(params):
# nTopics = params.get('nTopics')
# return os.path.join(params.get('outDir').format(''),
# 'theta_{}.csv'.format(nTopics))
#
# def topicFileName(params):
# nTopics = params.get('nTopics')
# return os.path.join(params.get('outDir').format(''),
# 'topics_{}.csv'.format(nTopics))
#
# def opinionFileName(params, name):
# nTopics = params.get('nTopics')
# return os.path.join(params.get('outDir').format(''),
# 'opinions_{}_{}.csv'.format(name, nTopics))
#
# def tarFileName(params):
# nTopics = params.get('nTopics')
# name = experimentName(params)
# return os.path.join(params.get('outDir').format(''),
# '{}_{}.tgz'.format(name, nTopics))
#
# def experimentName(params):
# fName = params.get('outDir')
# fName = fName.replace('/{}', '')
# _p, name = os.path.split(fName)
# return name
. Output only the next line. | fName = tarFileName(config) |
Next line prediction: <|code_start|>
add_parameter(pName, nTopics, jsonFile)
config2 = load_config(jsonFile)
yield assert_equal, config2[pName], nTopics
def test_thetaFileName():
config['nTopics'] = nTopics
fName = thetaFileName(config)
assert_equal(fName, '/theta_{}.csv'.format(nTopics))
def test_topicFileName():
config['nTopics'] = nTopics
fName = topicFileName(config)
assert_equal(fName, '/topics_{}.csv'.format(nTopics))
def test_opinionFileName():
config['nTopics'] = nTopics
perspectives = ['p0', 'p1', 'p2']
for p in perspectives:
fName = opinionFileName(config, p)
yield assert_equal, fName, '/opinions_{}_{}.csv'.format(p, nTopics)
def test_experimentName():
config['outDir'] = '/tmp/test/{}'
<|code_end|>
. Use current file imports:
(from nose.tools import assert_equal, assert_false
from os import remove
from os.path import join
from json import dump
from cptm.utils.experiment import load_config, add_parameter, thetaFileName, \
topicFileName, opinionFileName, tarFileName, experimentName)
and context including class names, function names, or small code snippets from other files:
# Path: cptm/utils/experiment.py
# def load_config(fName):
# with open(fName) as f:
# config = json.load(f)
#
# logger.debug('configuration of experiment: ')
# params = ['{}: {}'.format(p, v) for p, v in config.iteritems()]
# for p in params:
# logger.debug(p)
#
# params = {}
# params['inputData'] = config.get('inputData')
# params['outDir'] = config.get('outDir', '/{}')
# params['testSplit'] = config.get('testSplit', 20)
# params['minFreq'] = config.get('minFreq')
# params['removeTopTF'] = config.get('removeTopTF')
# params['removeTopDF'] = config.get('removeTopDF')
# params['nIter'] = config.get('nIter', 200)
# params['beta'] = config.get('beta', 0.02)
# params['beta_o'] = config.get('beta_o', 0.02)
# params['expNumTopics'] = config.get('expNumTopics', range(20, 201, 20))
# params['nTopics'] = config.get('nTopics')
# params['nProcesses'] = config.get('nProcesses', None)
# params['topicLines'] = config.get('topicLines', [0])
# params['opinionLines'] = config.get('opinionLines', [1])
# params['sampleEstimateStart'] = config.get('sampleEstimateStart')
# params['sampleEstimateEnd'] = config.get('sampleEstimateEnd')
#
# return params
#
# def add_parameter(name, value, fName):
# with open(fName) as f:
# config = json.load(f)
# config[name] = value
# with open(fName, 'w') as f:
# json.dump(config, f)
#
# def thetaFileName(params):
# nTopics = params.get('nTopics')
# return os.path.join(params.get('outDir').format(''),
# 'theta_{}.csv'.format(nTopics))
#
# def topicFileName(params):
# nTopics = params.get('nTopics')
# return os.path.join(params.get('outDir').format(''),
# 'topics_{}.csv'.format(nTopics))
#
# def opinionFileName(params, name):
# nTopics = params.get('nTopics')
# return os.path.join(params.get('outDir').format(''),
# 'opinions_{}_{}.csv'.format(name, nTopics))
#
# def tarFileName(params):
# nTopics = params.get('nTopics')
# name = experimentName(params)
# return os.path.join(params.get('outDir').format(''),
# '{}_{}.tgz'.format(name, nTopics))
#
# def experimentName(params):
# fName = params.get('outDir')
# fName = fName.replace('/{}', '')
# _p, name = os.path.split(fName)
# return name
. Output only the next line. | assert_equal('test', experimentName(config)) |
Continue the code snippet: <|code_start|>logging.basicConfig(format='%(levelname)s : %(message)s', level=logging.DEBUG)
parser = argparse.ArgumentParser()
parser.add_argument('json', help='json file containing experiment '
'configuration.')
parser.add_argument('data_dir', help='dir containing the input data.')
parser.add_argument('out_dir', help='dir to write results to.')
args = parser.parse_args()
params = load_config(args.json)
input_dir = [args.data_dir]
topicDict = params.get('outDir').format('topicDict.dict')
opinionDict = params.get('outDir').format('opinionDict.dict')
phi_topic_file = topicFileName(params)
phi_topic = pd.read_csv(phi_topic_file, index_col=0, encoding='utf-8').values.T
#print phi_topic.shape
#print phi_topic
corpus = CPTCorpus(input=input_dir, topicDict=topicDict,
opinionDict=opinionDict, testSplit=100, file_dict=None,
topicLines=params.get('topicLines'),
opinionLines=params.get('opinionLines'))
print str(corpus)
params['outDir'] = args.out_dir
nTopics = params.get('nTopics')
for i in range(10):
<|code_end|>
. Use current file imports:
import logging
import argparse
import pandas as pd
import os
from CPTCorpus import CPTCorpus
from cptm.utils.experiment import get_sampler, thetaFileName, load_config, \
topicFileName
and context (classes, functions, or code) from other files:
# Path: cptm/utils/experiment.py
# def get_sampler(params, corpus, nTopics=None, initialize=True):
# if nTopics is None:
# nTopics = params.get('nTopics')
# out_dir = params.get('outDir')
# nIter = params.get('nIter')
# alpha = 50.0/nTopics
# beta = params.get('beta')
# beta_o = params.get('beta_o')
# logger.info('creating Gibbs sampler (nTopics: {}, nIter: {}, alpha: {}, '
# 'beta: {}, beta_o: {})'.format(nTopics, nIter, alpha, beta,
# beta_o))
# sampler = GibbsSampler(corpus, nTopics=nTopics, nIter=nIter,
# alpha=alpha, beta=beta, beta_o=beta_o,
# out_dir=out_dir.format(nTopics),
# initialize=initialize)
# return sampler
#
# def thetaFileName(params):
# nTopics = params.get('nTopics')
# return os.path.join(params.get('outDir').format(''),
# 'theta_{}.csv'.format(nTopics))
#
# def load_config(fName):
# with open(fName) as f:
# config = json.load(f)
#
# logger.debug('configuration of experiment: ')
# params = ['{}: {}'.format(p, v) for p, v in config.iteritems()]
# for p in params:
# logger.debug(p)
#
# params = {}
# params['inputData'] = config.get('inputData')
# params['outDir'] = config.get('outDir', '/{}')
# params['testSplit'] = config.get('testSplit', 20)
# params['minFreq'] = config.get('minFreq')
# params['removeTopTF'] = config.get('removeTopTF')
# params['removeTopDF'] = config.get('removeTopDF')
# params['nIter'] = config.get('nIter', 200)
# params['beta'] = config.get('beta', 0.02)
# params['beta_o'] = config.get('beta_o', 0.02)
# params['expNumTopics'] = config.get('expNumTopics', range(20, 201, 20))
# params['nTopics'] = config.get('nTopics')
# params['nProcesses'] = config.get('nProcesses', None)
# params['topicLines'] = config.get('topicLines', [0])
# params['opinionLines'] = config.get('opinionLines', [1])
# params['sampleEstimateStart'] = config.get('sampleEstimateStart')
# params['sampleEstimateEnd'] = config.get('sampleEstimateEnd')
#
# return params
#
# def topicFileName(params):
# nTopics = params.get('nTopics')
# return os.path.join(params.get('outDir').format(''),
# 'topics_{}.csv'.format(nTopics))
. Output only the next line. | sampler = get_sampler(params, corpus, nTopics=nTopics, |
Based on the snippet: <|code_start|>"""Script to extract a document/topic matrix for a set of text documents.
The corpus is not divided in perspectives.
Used to calculate theta for the CAP vragenuurtje data.
Before this script can be run, a cptm corpus should be created. Use the
tabular2cptm_input.py script to create a corpus that can be used
as input.
Usage: python experiment_theta_for_texts_perspectives.py <experiment.json>
<input dir> <output dir>
"""
logger = logging.getLogger(__name__)
logging.basicConfig(format='%(levelname)s : %(message)s', level=logging.DEBUG)
parser = argparse.ArgumentParser()
parser.add_argument('json', help='json file containing experiment '
'configuration.')
parser.add_argument('data_dir', help='dir containing the input data.')
parser.add_argument('out_dir', help='dir to write results to.')
args = parser.parse_args()
<|code_end|>
, predict the immediate next line with the help of imports:
import logging
import argparse
import pandas as pd
import os
from CPTCorpus import CPTCorpus
from cptm.utils.experiment import get_sampler, thetaFileName, load_config, \
topicFileName
and context (classes, functions, sometimes code) from other files:
# Path: cptm/utils/experiment.py
# def get_sampler(params, corpus, nTopics=None, initialize=True):
# if nTopics is None:
# nTopics = params.get('nTopics')
# out_dir = params.get('outDir')
# nIter = params.get('nIter')
# alpha = 50.0/nTopics
# beta = params.get('beta')
# beta_o = params.get('beta_o')
# logger.info('creating Gibbs sampler (nTopics: {}, nIter: {}, alpha: {}, '
# 'beta: {}, beta_o: {})'.format(nTopics, nIter, alpha, beta,
# beta_o))
# sampler = GibbsSampler(corpus, nTopics=nTopics, nIter=nIter,
# alpha=alpha, beta=beta, beta_o=beta_o,
# out_dir=out_dir.format(nTopics),
# initialize=initialize)
# return sampler
#
# def thetaFileName(params):
# nTopics = params.get('nTopics')
# return os.path.join(params.get('outDir').format(''),
# 'theta_{}.csv'.format(nTopics))
#
# def load_config(fName):
# with open(fName) as f:
# config = json.load(f)
#
# logger.debug('configuration of experiment: ')
# params = ['{}: {}'.format(p, v) for p, v in config.iteritems()]
# for p in params:
# logger.debug(p)
#
# params = {}
# params['inputData'] = config.get('inputData')
# params['outDir'] = config.get('outDir', '/{}')
# params['testSplit'] = config.get('testSplit', 20)
# params['minFreq'] = config.get('minFreq')
# params['removeTopTF'] = config.get('removeTopTF')
# params['removeTopDF'] = config.get('removeTopDF')
# params['nIter'] = config.get('nIter', 200)
# params['beta'] = config.get('beta', 0.02)
# params['beta_o'] = config.get('beta_o', 0.02)
# params['expNumTopics'] = config.get('expNumTopics', range(20, 201, 20))
# params['nTopics'] = config.get('nTopics')
# params['nProcesses'] = config.get('nProcesses', None)
# params['topicLines'] = config.get('topicLines', [0])
# params['opinionLines'] = config.get('opinionLines', [1])
# params['sampleEstimateStart'] = config.get('sampleEstimateStart')
# params['sampleEstimateEnd'] = config.get('sampleEstimateEnd')
#
# return params
#
# def topicFileName(params):
# nTopics = params.get('nTopics')
# return os.path.join(params.get('outDir').format(''),
# 'topics_{}.csv'.format(nTopics))
. Output only the next line. | params = load_config(args.json) |
Using the snippet: <|code_start|>"""Script to extract a document/topic matrix for a set of text documents.
The corpus is not divided in perspectives.
Used to calculate theta for the CAP vragenuurtje data.
Before this script can be run, a cptm corpus should be created. Use the
tabular2cptm_input.py script to create a corpus that can be used
as input.
Usage: python experiment_theta_for_texts_perspectives.py <experiment.json>
<input dir> <output dir>
"""
logger = logging.getLogger(__name__)
logging.basicConfig(format='%(levelname)s : %(message)s', level=logging.DEBUG)
parser = argparse.ArgumentParser()
parser.add_argument('json', help='json file containing experiment '
'configuration.')
parser.add_argument('data_dir', help='dir containing the input data.')
parser.add_argument('out_dir', help='dir to write results to.')
args = parser.parse_args()
params = load_config(args.json)
input_dir = [args.data_dir]
topicDict = params.get('outDir').format('topicDict.dict')
opinionDict = params.get('outDir').format('opinionDict.dict')
<|code_end|>
, determine the next line of code. You have imports:
import logging
import argparse
import pandas as pd
import os
from CPTCorpus import CPTCorpus
from cptm.utils.experiment import get_sampler, thetaFileName, load_config, \
topicFileName
and context (class names, function names, or code) available:
# Path: cptm/utils/experiment.py
# def get_sampler(params, corpus, nTopics=None, initialize=True):
# if nTopics is None:
# nTopics = params.get('nTopics')
# out_dir = params.get('outDir')
# nIter = params.get('nIter')
# alpha = 50.0/nTopics
# beta = params.get('beta')
# beta_o = params.get('beta_o')
# logger.info('creating Gibbs sampler (nTopics: {}, nIter: {}, alpha: {}, '
# 'beta: {}, beta_o: {})'.format(nTopics, nIter, alpha, beta,
# beta_o))
# sampler = GibbsSampler(corpus, nTopics=nTopics, nIter=nIter,
# alpha=alpha, beta=beta, beta_o=beta_o,
# out_dir=out_dir.format(nTopics),
# initialize=initialize)
# return sampler
#
# def thetaFileName(params):
# nTopics = params.get('nTopics')
# return os.path.join(params.get('outDir').format(''),
# 'theta_{}.csv'.format(nTopics))
#
# def load_config(fName):
# with open(fName) as f:
# config = json.load(f)
#
# logger.debug('configuration of experiment: ')
# params = ['{}: {}'.format(p, v) for p, v in config.iteritems()]
# for p in params:
# logger.debug(p)
#
# params = {}
# params['inputData'] = config.get('inputData')
# params['outDir'] = config.get('outDir', '/{}')
# params['testSplit'] = config.get('testSplit', 20)
# params['minFreq'] = config.get('minFreq')
# params['removeTopTF'] = config.get('removeTopTF')
# params['removeTopDF'] = config.get('removeTopDF')
# params['nIter'] = config.get('nIter', 200)
# params['beta'] = config.get('beta', 0.02)
# params['beta_o'] = config.get('beta_o', 0.02)
# params['expNumTopics'] = config.get('expNumTopics', range(20, 201, 20))
# params['nTopics'] = config.get('nTopics')
# params['nProcesses'] = config.get('nProcesses', None)
# params['topicLines'] = config.get('topicLines', [0])
# params['opinionLines'] = config.get('opinionLines', [1])
# params['sampleEstimateStart'] = config.get('sampleEstimateStart')
# params['sampleEstimateEnd'] = config.get('sampleEstimateEnd')
#
# return params
#
# def topicFileName(params):
# nTopics = params.get('nTopics')
# return os.path.join(params.get('outDir').format(''),
# 'topics_{}.csv'.format(nTopics))
. Output only the next line. | phi_topic_file = topicFileName(params) |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/python
# -*- coding: utf-8 -*-
def test_remove_training_digits():
cases = {u'd66': u'd',
u'f16': u'f',
u'é33': u'é'}
for i, o in cases.iteritems():
<|code_end|>
using the current file's imports:
from nose.tools import assert_equal
from cptm.utils.inputgeneration import remove_trailing_digits
and any relevant context from other files:
# Path: cptm/utils/inputgeneration.py
# def remove_trailing_digits(word):
# """Convert words like d66 to d.
#
# In the folia files from politicalmashup, words such as d66 have been
# extracted as two words (d and 66) and only d ended up in the data input
# files. The folia files were probably created with an old version of frog,
# because currenly, words like these are parsed correctly.
#
# This function can be used when parsing and lemmatizing new text to match
# the vocabulary used in the old folia files.
# """
# regex = re.compile('^(.+?)(\d+)$', flags=re.UNICODE)
# m = regex.match(word)
# if m:
# return m.group(1)
# return word
. Output only the next line. | r = remove_trailing_digits(i) |
Using the snippet: <|code_start|>"""Remove saved parameter samples for certain iterations
Before, the Gibbs sampler saved estimates for all iterations. However, because
this took to much disk space, now the sampler only saves every tenth estimate.
This script removes samples for results generated with an old version of the
sampler.
Usage: python experiment_prune_samples.py /path/to/experiment.json
"""
logger = logging.getLogger(__name__)
logging.basicConfig(format='%(levelname)s : %(message)s', level=logging.INFO)
logging.getLogger('gensim').setLevel(logging.ERROR)
logging.getLogger('CPTCorpus').setLevel(logging.ERROR)
logging.getLogger('CPT_Gibbs').setLevel(logging.ERROR)
parser = argparse.ArgumentParser()
parser.add_argument('json', help='json file containing experiment '
'configuration.')
args = parser.parse_args()
<|code_end|>
, determine the next line of code. You have imports:
import logging
import argparse
from os import remove
from cptm.utils.experiment import load_config, get_corpus, get_sampler
and context (class names, function names, or code) available:
# Path: cptm/utils/experiment.py
# def load_config(fName):
# with open(fName) as f:
# config = json.load(f)
#
# logger.debug('configuration of experiment: ')
# params = ['{}: {}'.format(p, v) for p, v in config.iteritems()]
# for p in params:
# logger.debug(p)
#
# params = {}
# params['inputData'] = config.get('inputData')
# params['outDir'] = config.get('outDir', '/{}')
# params['testSplit'] = config.get('testSplit', 20)
# params['minFreq'] = config.get('minFreq')
# params['removeTopTF'] = config.get('removeTopTF')
# params['removeTopDF'] = config.get('removeTopDF')
# params['nIter'] = config.get('nIter', 200)
# params['beta'] = config.get('beta', 0.02)
# params['beta_o'] = config.get('beta_o', 0.02)
# params['expNumTopics'] = config.get('expNumTopics', range(20, 201, 20))
# params['nTopics'] = config.get('nTopics')
# params['nProcesses'] = config.get('nProcesses', None)
# params['topicLines'] = config.get('topicLines', [0])
# params['opinionLines'] = config.get('opinionLines', [1])
# params['sampleEstimateStart'] = config.get('sampleEstimateStart')
# params['sampleEstimateEnd'] = config.get('sampleEstimateEnd')
#
# return params
#
# def get_corpus(params):
# out_dir = params.get('outDir')
# files = glob(params.get('inputData'))
#
# if not os.path.isfile(out_dir.format('corpus.json')):
# corpus = CPTCorpus(files,
# testSplit=params.get('testSplit'),
# topicLines=params.get('topicLines'),
# opinionLines=params.get('opinionLines'))
# minFreq = params.get('minFreq')
# removeTopTF = params.get('removeTopTF')
# removeTopDF = params.get('removeTopDF')
# if (not minFreq is None) or (not removeTopTF is None) or \
# (not removeTopDF is None):
# corpus.filter_dictionaries(minFreq=minFreq,
# removeTopTF=removeTopTF,
# removeTopDF=removeTopDF)
# corpus.save_dictionaries(directory=out_dir.format(''))
# corpus.save(out_dir.format('corpus.json'))
# else:
# corpus = CPTCorpus.load(file_name=out_dir.format('corpus.json'),
# topicLines=params.get('topicLines'),
# opinionLines=params.get('opinionLines'),
# topicDict=out_dir.format('topicDict.dict'),
# opinionDict=out_dir.format('opinionDict.dict'))
# return corpus
#
# def get_sampler(params, corpus, nTopics=None, initialize=True):
# if nTopics is None:
# nTopics = params.get('nTopics')
# out_dir = params.get('outDir')
# nIter = params.get('nIter')
# alpha = 50.0/nTopics
# beta = params.get('beta')
# beta_o = params.get('beta_o')
# logger.info('creating Gibbs sampler (nTopics: {}, nIter: {}, alpha: {}, '
# 'beta: {}, beta_o: {})'.format(nTopics, nIter, alpha, beta,
# beta_o))
# sampler = GibbsSampler(corpus, nTopics=nTopics, nIter=nIter,
# alpha=alpha, beta=beta, beta_o=beta_o,
# out_dir=out_dir.format(nTopics),
# initialize=initialize)
# return sampler
. Output only the next line. | config = load_config(args.json) |
Based on the snippet: <|code_start|>"""Remove saved parameter samples for certain iterations
Before, the Gibbs sampler saved estimates for all iterations. However, because
this took to much disk space, now the sampler only saves every tenth estimate.
This script removes samples for results generated with an old version of the
sampler.
Usage: python experiment_prune_samples.py /path/to/experiment.json
"""
logger = logging.getLogger(__name__)
logging.basicConfig(format='%(levelname)s : %(message)s', level=logging.INFO)
logging.getLogger('gensim').setLevel(logging.ERROR)
logging.getLogger('CPTCorpus').setLevel(logging.ERROR)
logging.getLogger('CPT_Gibbs').setLevel(logging.ERROR)
parser = argparse.ArgumentParser()
parser.add_argument('json', help='json file containing experiment '
'configuration.')
args = parser.parse_args()
config = load_config(args.json)
<|code_end|>
, predict the immediate next line with the help of imports:
import logging
import argparse
from os import remove
from cptm.utils.experiment import load_config, get_corpus, get_sampler
and context (classes, functions, sometimes code) from other files:
# Path: cptm/utils/experiment.py
# def load_config(fName):
# with open(fName) as f:
# config = json.load(f)
#
# logger.debug('configuration of experiment: ')
# params = ['{}: {}'.format(p, v) for p, v in config.iteritems()]
# for p in params:
# logger.debug(p)
#
# params = {}
# params['inputData'] = config.get('inputData')
# params['outDir'] = config.get('outDir', '/{}')
# params['testSplit'] = config.get('testSplit', 20)
# params['minFreq'] = config.get('minFreq')
# params['removeTopTF'] = config.get('removeTopTF')
# params['removeTopDF'] = config.get('removeTopDF')
# params['nIter'] = config.get('nIter', 200)
# params['beta'] = config.get('beta', 0.02)
# params['beta_o'] = config.get('beta_o', 0.02)
# params['expNumTopics'] = config.get('expNumTopics', range(20, 201, 20))
# params['nTopics'] = config.get('nTopics')
# params['nProcesses'] = config.get('nProcesses', None)
# params['topicLines'] = config.get('topicLines', [0])
# params['opinionLines'] = config.get('opinionLines', [1])
# params['sampleEstimateStart'] = config.get('sampleEstimateStart')
# params['sampleEstimateEnd'] = config.get('sampleEstimateEnd')
#
# return params
#
# def get_corpus(params):
# out_dir = params.get('outDir')
# files = glob(params.get('inputData'))
#
# if not os.path.isfile(out_dir.format('corpus.json')):
# corpus = CPTCorpus(files,
# testSplit=params.get('testSplit'),
# topicLines=params.get('topicLines'),
# opinionLines=params.get('opinionLines'))
# minFreq = params.get('minFreq')
# removeTopTF = params.get('removeTopTF')
# removeTopDF = params.get('removeTopDF')
# if (not minFreq is None) or (not removeTopTF is None) or \
# (not removeTopDF is None):
# corpus.filter_dictionaries(minFreq=minFreq,
# removeTopTF=removeTopTF,
# removeTopDF=removeTopDF)
# corpus.save_dictionaries(directory=out_dir.format(''))
# corpus.save(out_dir.format('corpus.json'))
# else:
# corpus = CPTCorpus.load(file_name=out_dir.format('corpus.json'),
# topicLines=params.get('topicLines'),
# opinionLines=params.get('opinionLines'),
# topicDict=out_dir.format('topicDict.dict'),
# opinionDict=out_dir.format('opinionDict.dict'))
# return corpus
#
# def get_sampler(params, corpus, nTopics=None, initialize=True):
# if nTopics is None:
# nTopics = params.get('nTopics')
# out_dir = params.get('outDir')
# nIter = params.get('nIter')
# alpha = 50.0/nTopics
# beta = params.get('beta')
# beta_o = params.get('beta_o')
# logger.info('creating Gibbs sampler (nTopics: {}, nIter: {}, alpha: {}, '
# 'beta: {}, beta_o: {})'.format(nTopics, nIter, alpha, beta,
# beta_o))
# sampler = GibbsSampler(corpus, nTopics=nTopics, nIter=nIter,
# alpha=alpha, beta=beta, beta_o=beta_o,
# out_dir=out_dir.format(nTopics),
# initialize=initialize)
# return sampler
. Output only the next line. | corpus = get_corpus(config) |
Here is a snippet: <|code_start|>Before, the Gibbs sampler saved estimates for all iterations. However, because
this took to much disk space, now the sampler only saves every tenth estimate.
This script removes samples for results generated with an old version of the
sampler.
Usage: python experiment_prune_samples.py /path/to/experiment.json
"""
logger = logging.getLogger(__name__)
logging.basicConfig(format='%(levelname)s : %(message)s', level=logging.INFO)
logging.getLogger('gensim').setLevel(logging.ERROR)
logging.getLogger('CPTCorpus').setLevel(logging.ERROR)
logging.getLogger('CPT_Gibbs').setLevel(logging.ERROR)
parser = argparse.ArgumentParser()
parser.add_argument('json', help='json file containing experiment '
'configuration.')
args = parser.parse_args()
config = load_config(args.json)
corpus = get_corpus(config)
nTopics = config.get('expNumTopics')
nIter = config.get('nIter')
outDir = config.get('outDir')
sampleInterval = 10
for nt in nTopics:
<|code_end|>
. Write the next line using the current file imports:
import logging
import argparse
from os import remove
from cptm.utils.experiment import load_config, get_corpus, get_sampler
and context from other files:
# Path: cptm/utils/experiment.py
# def load_config(fName):
# with open(fName) as f:
# config = json.load(f)
#
# logger.debug('configuration of experiment: ')
# params = ['{}: {}'.format(p, v) for p, v in config.iteritems()]
# for p in params:
# logger.debug(p)
#
# params = {}
# params['inputData'] = config.get('inputData')
# params['outDir'] = config.get('outDir', '/{}')
# params['testSplit'] = config.get('testSplit', 20)
# params['minFreq'] = config.get('minFreq')
# params['removeTopTF'] = config.get('removeTopTF')
# params['removeTopDF'] = config.get('removeTopDF')
# params['nIter'] = config.get('nIter', 200)
# params['beta'] = config.get('beta', 0.02)
# params['beta_o'] = config.get('beta_o', 0.02)
# params['expNumTopics'] = config.get('expNumTopics', range(20, 201, 20))
# params['nTopics'] = config.get('nTopics')
# params['nProcesses'] = config.get('nProcesses', None)
# params['topicLines'] = config.get('topicLines', [0])
# params['opinionLines'] = config.get('opinionLines', [1])
# params['sampleEstimateStart'] = config.get('sampleEstimateStart')
# params['sampleEstimateEnd'] = config.get('sampleEstimateEnd')
#
# return params
#
# def get_corpus(params):
# out_dir = params.get('outDir')
# files = glob(params.get('inputData'))
#
# if not os.path.isfile(out_dir.format('corpus.json')):
# corpus = CPTCorpus(files,
# testSplit=params.get('testSplit'),
# topicLines=params.get('topicLines'),
# opinionLines=params.get('opinionLines'))
# minFreq = params.get('minFreq')
# removeTopTF = params.get('removeTopTF')
# removeTopDF = params.get('removeTopDF')
# if (not minFreq is None) or (not removeTopTF is None) or \
# (not removeTopDF is None):
# corpus.filter_dictionaries(minFreq=minFreq,
# removeTopTF=removeTopTF,
# removeTopDF=removeTopDF)
# corpus.save_dictionaries(directory=out_dir.format(''))
# corpus.save(out_dir.format('corpus.json'))
# else:
# corpus = CPTCorpus.load(file_name=out_dir.format('corpus.json'),
# topicLines=params.get('topicLines'),
# opinionLines=params.get('opinionLines'),
# topicDict=out_dir.format('topicDict.dict'),
# opinionDict=out_dir.format('opinionDict.dict'))
# return corpus
#
# def get_sampler(params, corpus, nTopics=None, initialize=True):
# if nTopics is None:
# nTopics = params.get('nTopics')
# out_dir = params.get('outDir')
# nIter = params.get('nIter')
# alpha = 50.0/nTopics
# beta = params.get('beta')
# beta_o = params.get('beta_o')
# logger.info('creating Gibbs sampler (nTopics: {}, nIter: {}, alpha: {}, '
# 'beta: {}, beta_o: {})'.format(nTopics, nIter, alpha, beta,
# beta_o))
# sampler = GibbsSampler(corpus, nTopics=nTopics, nIter=nIter,
# alpha=alpha, beta=beta, beta_o=beta_o,
# out_dir=out_dir.format(nTopics),
# initialize=initialize)
# return sampler
, which may include functions, classes, or code. Output only the next line. | sampler = get_sampler(config, corpus, nTopics=nt, initialize=False) |
Given the following code snippet before the placeholder: <|code_start|>
@contextmanager
def not_raises(exception):
try:
yield
except exception:
raise pytest.fail("Unexpected raise {0}".format(exception))
def kern32_script_test(scripts, specs=None):
if specs is None:
specs = DefaultKern32Specs
ids = []
params = []
for script in scripts:
for spec in specs:
version, bitness, expected = (
spec
if isinstance(spec[0], float) or isinstance(spec[0], int)
else spec[1]
)
path, sversion, sbitness = get_kern32_path(version, bitness)
params.append(pytest.param(path, version, bitness, expected, script))
ids.append("/".join([sversion, sbitness, script.__name__]))
return pytest.mark.parametrize(
"kernel32_idb_path, version, bitness, expected, script", params, ids=ids
)
<|code_end|>
, predict the next line using imports from the current file:
from contextlib import contextmanager
from fixtures import DefaultKern32Specs, get_kern32_path
from scripts import (
dump_btree,
dump_types,
dump_user,
dump_scripts,
extract_function_names,
extract_md5,
extract_version,
)
import pytest
and context including class names, function names, and sometimes code from other files:
# Path: scripts/dump_btree.py
# def main(argv=None):
#
# Path: scripts/dump_types.py
# class TILEncoder(json.JSONEncoder):
# def default(self, obj):
# def main(argv=None):
#
# Path: scripts/dump_user.py
# def is_encrypted(buf):
# def decrypt(buf):
# def parse_user_data(buf):
# def get_userdata(netnode):
# def print_userdata(api, tag="$ original user"):
# def main(argv=None):
# HEXRAYS_PUBKEY = 0x93AF7A8E3A6EB93D1B4D1FB7EC29299D2BC8F3CE5F84BFE88E47DDBDD5550C3CE3D2B16A2E2FBD0FBD919E8038BB05752EC92DD1498CB283AA087A93184F1DD9DD5D5DF7857322DFCD70890F814B58448071BBABB0FC8A7868B62EB29CC2664C8FE61DFBC5DB0EE8BF6ECF0B65250514576C4384582211896E5478F95C42FDED
#
# Path: scripts/dump_scripts.py
# def main(argv=None):
#
# Path: scripts/extract_function_names.py
# def main(argv=None):
#
# Path: scripts/extract_md5.py
# def main(argv=None):
#
# Path: scripts/extract_version.py
# def main(argv=None):
. Output only the next line. | SlowScripts = [dump_btree, extract_function_names] |
Based on the snippet: <|code_start|>
@contextmanager
def not_raises(exception):
try:
yield
except exception:
raise pytest.fail("Unexpected raise {0}".format(exception))
def kern32_script_test(scripts, specs=None):
if specs is None:
specs = DefaultKern32Specs
ids = []
params = []
for script in scripts:
for spec in specs:
version, bitness, expected = (
spec
if isinstance(spec[0], float) or isinstance(spec[0], int)
else spec[1]
)
path, sversion, sbitness = get_kern32_path(version, bitness)
params.append(pytest.param(path, version, bitness, expected, script))
ids.append("/".join([sversion, sbitness, script.__name__]))
return pytest.mark.parametrize(
"kernel32_idb_path, version, bitness, expected, script", params, ids=ids
)
SlowScripts = [dump_btree, extract_function_names]
<|code_end|>
, predict the immediate next line with the help of imports:
from contextlib import contextmanager
from fixtures import DefaultKern32Specs, get_kern32_path
from scripts import (
dump_btree,
dump_types,
dump_user,
dump_scripts,
extract_function_names,
extract_md5,
extract_version,
)
import pytest
and context (classes, functions, sometimes code) from other files:
# Path: scripts/dump_btree.py
# def main(argv=None):
#
# Path: scripts/dump_types.py
# class TILEncoder(json.JSONEncoder):
# def default(self, obj):
# def main(argv=None):
#
# Path: scripts/dump_user.py
# def is_encrypted(buf):
# def decrypt(buf):
# def parse_user_data(buf):
# def get_userdata(netnode):
# def print_userdata(api, tag="$ original user"):
# def main(argv=None):
# HEXRAYS_PUBKEY = 0x93AF7A8E3A6EB93D1B4D1FB7EC29299D2BC8F3CE5F84BFE88E47DDBDD5550C3CE3D2B16A2E2FBD0FBD919E8038BB05752EC92DD1498CB283AA087A93184F1DD9DD5D5DF7857322DFCD70890F814B58448071BBABB0FC8A7868B62EB29CC2664C8FE61DFBC5DB0EE8BF6ECF0B65250514576C4384582211896E5478F95C42FDED
#
# Path: scripts/dump_scripts.py
# def main(argv=None):
#
# Path: scripts/extract_function_names.py
# def main(argv=None):
#
# Path: scripts/extract_md5.py
# def main(argv=None):
#
# Path: scripts/extract_version.py
# def main(argv=None):
. Output only the next line. | Scripts = [dump_types, dump_user, dump_scripts, extract_md5, extract_version] |
Predict the next line after this snippet: <|code_start|>
@contextmanager
def not_raises(exception):
try:
yield
except exception:
raise pytest.fail("Unexpected raise {0}".format(exception))
def kern32_script_test(scripts, specs=None):
if specs is None:
specs = DefaultKern32Specs
ids = []
params = []
for script in scripts:
for spec in specs:
version, bitness, expected = (
spec
if isinstance(spec[0], float) or isinstance(spec[0], int)
else spec[1]
)
path, sversion, sbitness = get_kern32_path(version, bitness)
params.append(pytest.param(path, version, bitness, expected, script))
ids.append("/".join([sversion, sbitness, script.__name__]))
return pytest.mark.parametrize(
"kernel32_idb_path, version, bitness, expected, script", params, ids=ids
)
SlowScripts = [dump_btree, extract_function_names]
<|code_end|>
using the current file's imports:
from contextlib import contextmanager
from fixtures import DefaultKern32Specs, get_kern32_path
from scripts import (
dump_btree,
dump_types,
dump_user,
dump_scripts,
extract_function_names,
extract_md5,
extract_version,
)
import pytest
and any relevant context from other files:
# Path: scripts/dump_btree.py
# def main(argv=None):
#
# Path: scripts/dump_types.py
# class TILEncoder(json.JSONEncoder):
# def default(self, obj):
# def main(argv=None):
#
# Path: scripts/dump_user.py
# def is_encrypted(buf):
# def decrypt(buf):
# def parse_user_data(buf):
# def get_userdata(netnode):
# def print_userdata(api, tag="$ original user"):
# def main(argv=None):
# HEXRAYS_PUBKEY = 0x93AF7A8E3A6EB93D1B4D1FB7EC29299D2BC8F3CE5F84BFE88E47DDBDD5550C3CE3D2B16A2E2FBD0FBD919E8038BB05752EC92DD1498CB283AA087A93184F1DD9DD5D5DF7857322DFCD70890F814B58448071BBABB0FC8A7868B62EB29CC2664C8FE61DFBC5DB0EE8BF6ECF0B65250514576C4384582211896E5478F95C42FDED
#
# Path: scripts/dump_scripts.py
# def main(argv=None):
#
# Path: scripts/extract_function_names.py
# def main(argv=None):
#
# Path: scripts/extract_md5.py
# def main(argv=None):
#
# Path: scripts/extract_version.py
# def main(argv=None):
. Output only the next line. | Scripts = [dump_types, dump_user, dump_scripts, extract_md5, extract_version] |
Based on the snippet: <|code_start|>
@contextmanager
def not_raises(exception):
try:
yield
except exception:
raise pytest.fail("Unexpected raise {0}".format(exception))
def kern32_script_test(scripts, specs=None):
if specs is None:
specs = DefaultKern32Specs
ids = []
params = []
for script in scripts:
for spec in specs:
version, bitness, expected = (
spec
if isinstance(spec[0], float) or isinstance(spec[0], int)
else spec[1]
)
path, sversion, sbitness = get_kern32_path(version, bitness)
params.append(pytest.param(path, version, bitness, expected, script))
ids.append("/".join([sversion, sbitness, script.__name__]))
return pytest.mark.parametrize(
"kernel32_idb_path, version, bitness, expected, script", params, ids=ids
)
SlowScripts = [dump_btree, extract_function_names]
<|code_end|>
, predict the immediate next line with the help of imports:
from contextlib import contextmanager
from fixtures import DefaultKern32Specs, get_kern32_path
from scripts import (
dump_btree,
dump_types,
dump_user,
dump_scripts,
extract_function_names,
extract_md5,
extract_version,
)
import pytest
and context (classes, functions, sometimes code) from other files:
# Path: scripts/dump_btree.py
# def main(argv=None):
#
# Path: scripts/dump_types.py
# class TILEncoder(json.JSONEncoder):
# def default(self, obj):
# def main(argv=None):
#
# Path: scripts/dump_user.py
# def is_encrypted(buf):
# def decrypt(buf):
# def parse_user_data(buf):
# def get_userdata(netnode):
# def print_userdata(api, tag="$ original user"):
# def main(argv=None):
# HEXRAYS_PUBKEY = 0x93AF7A8E3A6EB93D1B4D1FB7EC29299D2BC8F3CE5F84BFE88E47DDBDD5550C3CE3D2B16A2E2FBD0FBD919E8038BB05752EC92DD1498CB283AA087A93184F1DD9DD5D5DF7857322DFCD70890F814B58448071BBABB0FC8A7868B62EB29CC2664C8FE61DFBC5DB0EE8BF6ECF0B65250514576C4384582211896E5478F95C42FDED
#
# Path: scripts/dump_scripts.py
# def main(argv=None):
#
# Path: scripts/extract_function_names.py
# def main(argv=None):
#
# Path: scripts/extract_md5.py
# def main(argv=None):
#
# Path: scripts/extract_version.py
# def main(argv=None):
. Output only the next line. | Scripts = [dump_types, dump_user, dump_scripts, extract_md5, extract_version] |
Based on the snippet: <|code_start|>
@contextmanager
def not_raises(exception):
try:
yield
except exception:
raise pytest.fail("Unexpected raise {0}".format(exception))
def kern32_script_test(scripts, specs=None):
if specs is None:
specs = DefaultKern32Specs
ids = []
params = []
for script in scripts:
for spec in specs:
version, bitness, expected = (
spec
if isinstance(spec[0], float) or isinstance(spec[0], int)
else spec[1]
)
path, sversion, sbitness = get_kern32_path(version, bitness)
params.append(pytest.param(path, version, bitness, expected, script))
ids.append("/".join([sversion, sbitness, script.__name__]))
return pytest.mark.parametrize(
"kernel32_idb_path, version, bitness, expected, script", params, ids=ids
)
<|code_end|>
, predict the immediate next line with the help of imports:
from contextlib import contextmanager
from fixtures import DefaultKern32Specs, get_kern32_path
from scripts import (
dump_btree,
dump_types,
dump_user,
dump_scripts,
extract_function_names,
extract_md5,
extract_version,
)
import pytest
and context (classes, functions, sometimes code) from other files:
# Path: scripts/dump_btree.py
# def main(argv=None):
#
# Path: scripts/dump_types.py
# class TILEncoder(json.JSONEncoder):
# def default(self, obj):
# def main(argv=None):
#
# Path: scripts/dump_user.py
# def is_encrypted(buf):
# def decrypt(buf):
# def parse_user_data(buf):
# def get_userdata(netnode):
# def print_userdata(api, tag="$ original user"):
# def main(argv=None):
# HEXRAYS_PUBKEY = 0x93AF7A8E3A6EB93D1B4D1FB7EC29299D2BC8F3CE5F84BFE88E47DDBDD5550C3CE3D2B16A2E2FBD0FBD919E8038BB05752EC92DD1498CB283AA087A93184F1DD9DD5D5DF7857322DFCD70890F814B58448071BBABB0FC8A7868B62EB29CC2664C8FE61DFBC5DB0EE8BF6ECF0B65250514576C4384582211896E5478F95C42FDED
#
# Path: scripts/dump_scripts.py
# def main(argv=None):
#
# Path: scripts/extract_function_names.py
# def main(argv=None):
#
# Path: scripts/extract_md5.py
# def main(argv=None):
#
# Path: scripts/extract_version.py
# def main(argv=None):
. Output only the next line. | SlowScripts = [dump_btree, extract_function_names] |
Here is a snippet: <|code_start|>
@contextmanager
def not_raises(exception):
try:
yield
except exception:
raise pytest.fail("Unexpected raise {0}".format(exception))
def kern32_script_test(scripts, specs=None):
if specs is None:
specs = DefaultKern32Specs
ids = []
params = []
for script in scripts:
for spec in specs:
version, bitness, expected = (
spec
if isinstance(spec[0], float) or isinstance(spec[0], int)
else spec[1]
)
path, sversion, sbitness = get_kern32_path(version, bitness)
params.append(pytest.param(path, version, bitness, expected, script))
ids.append("/".join([sversion, sbitness, script.__name__]))
return pytest.mark.parametrize(
"kernel32_idb_path, version, bitness, expected, script", params, ids=ids
)
SlowScripts = [dump_btree, extract_function_names]
<|code_end|>
. Write the next line using the current file imports:
from contextlib import contextmanager
from fixtures import DefaultKern32Specs, get_kern32_path
from scripts import (
dump_btree,
dump_types,
dump_user,
dump_scripts,
extract_function_names,
extract_md5,
extract_version,
)
import pytest
and context from other files:
# Path: scripts/dump_btree.py
# def main(argv=None):
#
# Path: scripts/dump_types.py
# class TILEncoder(json.JSONEncoder):
# def default(self, obj):
# def main(argv=None):
#
# Path: scripts/dump_user.py
# def is_encrypted(buf):
# def decrypt(buf):
# def parse_user_data(buf):
# def get_userdata(netnode):
# def print_userdata(api, tag="$ original user"):
# def main(argv=None):
# HEXRAYS_PUBKEY = 0x93AF7A8E3A6EB93D1B4D1FB7EC29299D2BC8F3CE5F84BFE88E47DDBDD5550C3CE3D2B16A2E2FBD0FBD919E8038BB05752EC92DD1498CB283AA087A93184F1DD9DD5D5DF7857322DFCD70890F814B58448071BBABB0FC8A7868B62EB29CC2664C8FE61DFBC5DB0EE8BF6ECF0B65250514576C4384582211896E5478F95C42FDED
#
# Path: scripts/dump_scripts.py
# def main(argv=None):
#
# Path: scripts/extract_function_names.py
# def main(argv=None):
#
# Path: scripts/extract_md5.py
# def main(argv=None):
#
# Path: scripts/extract_version.py
# def main(argv=None):
, which may include functions, classes, or code. Output only the next line. | Scripts = [dump_types, dump_user, dump_scripts, extract_md5, extract_version] |
Here is a snippet: <|code_start|>
@contextmanager
def not_raises(exception):
try:
yield
except exception:
raise pytest.fail("Unexpected raise {0}".format(exception))
def kern32_script_test(scripts, specs=None):
if specs is None:
specs = DefaultKern32Specs
ids = []
params = []
for script in scripts:
for spec in specs:
version, bitness, expected = (
spec
if isinstance(spec[0], float) or isinstance(spec[0], int)
else spec[1]
)
path, sversion, sbitness = get_kern32_path(version, bitness)
params.append(pytest.param(path, version, bitness, expected, script))
ids.append("/".join([sversion, sbitness, script.__name__]))
return pytest.mark.parametrize(
"kernel32_idb_path, version, bitness, expected, script", params, ids=ids
)
SlowScripts = [dump_btree, extract_function_names]
<|code_end|>
. Write the next line using the current file imports:
from contextlib import contextmanager
from fixtures import DefaultKern32Specs, get_kern32_path
from scripts import (
dump_btree,
dump_types,
dump_user,
dump_scripts,
extract_function_names,
extract_md5,
extract_version,
)
import pytest
and context from other files:
# Path: scripts/dump_btree.py
# def main(argv=None):
#
# Path: scripts/dump_types.py
# class TILEncoder(json.JSONEncoder):
# def default(self, obj):
# def main(argv=None):
#
# Path: scripts/dump_user.py
# def is_encrypted(buf):
# def decrypt(buf):
# def parse_user_data(buf):
# def get_userdata(netnode):
# def print_userdata(api, tag="$ original user"):
# def main(argv=None):
# HEXRAYS_PUBKEY = 0x93AF7A8E3A6EB93D1B4D1FB7EC29299D2BC8F3CE5F84BFE88E47DDBDD5550C3CE3D2B16A2E2FBD0FBD919E8038BB05752EC92DD1498CB283AA087A93184F1DD9DD5D5DF7857322DFCD70890F814B58448071BBABB0FC8A7868B62EB29CC2664C8FE61DFBC5DB0EE8BF6ECF0B65250514576C4384582211896E5478F95C42FDED
#
# Path: scripts/dump_scripts.py
# def main(argv=None):
#
# Path: scripts/extract_function_names.py
# def main(argv=None):
#
# Path: scripts/extract_md5.py
# def main(argv=None):
#
# Path: scripts/extract_version.py
# def main(argv=None):
, which may include functions, classes, or code. Output only the next line. | Scripts = [dump_types, dump_user, dump_scripts, extract_md5, extract_version] |
Using the snippet: <|code_start|>
class DummyProvider:
def __init__(self, files):
self.files = files;
def list(self):
return self.files
def has(self, filename):
return filename in self.list()
def open(self, filename, *args, **kwargs):
if not self.has(filename):
<|code_end|>
, determine the next line of code. You have imports:
import os
import codecs
from io import StringIO
from pytest import fixture
from rave import filesystem
and context (class names, function names, or code) available:
# Path: rave/filesystem.py
# PATH_SEPARATOR = '/'
# ROOT = '/'
# BAD_PATH_PATTERN = re.compile(r'(?:{0}{{2,}}|(?:{0}|^)\.+(?:{0}|$))'.format(PATH_SEPARATOR))
# ENGINE_MOUNT = '/.rave'
# MODULE_MOUNT = '/.modules'
# GAME_MOUNT = '/'
# COMMON_MOUNT = '/.common'
# class FileSystemError(rave.common.raveError, IOError):
# class NativeError(FileSystemError):
# class FileNotFound(FileSystemError, FileNotFoundError):
# class AccessDenied(FileSystemError, PermissionError):
# class FileNotReadable(FileSystemError, PermissionError, io.UnsupportedOperation):
# class FileNotWritable(FileSystemError, PermissionError, io.UnsupportedOperation):
# class FileNotSeekable(FileSystemError, PermissionError, io.UnsupportedOperation):
# class FileClosed(FileSystemError, BrokenPipeError):
# class NotAFile(FileSystemError, IsADirectoryError):
# class NotADirectory(FileSystemError, NotADirectoryError):
# class FileSystem:
# class File(io.IOBase):
# class FileSystemProvider:
# def __init__(self, filename, message=None):
# def __init__(self, filename, parent):
# def __init__(self):
# def __repr__(self):
# def clear(self):
# def _build_cache(self):
# def _build_provider_cache(self, provider, root):
# def _build_transformer_cache(self, transformer, pattern):
# def _cache_directory(self, provider, root, path):
# def _cache_file(self, provider, root, path):
# def _cache_entry(self, provider, root, path):
# def _cache_transformed_file(self, transformer, path, handle):
# def _providers_for_file(self, path):
# def _local_file(self, root, path):
# def list(self, subdir=None):
# def listdir(self, subdir=None):
# def mount(self, path, provider):
# def unmount(self, path, provider):
# def transform(self, pattern, transformer):
# def untransform(self, pattern, transformer):
# def open(self, filename, *args, **kwargs):
# def exists(self, filename):
# def isdir(self, filename):
# def isfile(self, filename):
# def dirname(self, path):
# def basename(self, path):
# def join(self, *paths, normalized=True):
# def split(self, path, *args, **kwargs):
# def normalize(self, path):
# def __del__(self):
# def close(self):
# def opened(self):
# def readable(self):
# def writable(self):
# def seekable(self):
# def read(self, amount=None):
# def write(self, data):
# def seek(self, position, mode=os.SEEK_CUR):
# def tell(self):
# def __init__(self, fs):
# def __repr__(self):
# def list(self):
# def open(self, filename, *args, **kwargs):
# def has(self, filename):
# def isfile(self, filename):
# def isdir(self, filename):
# def current():
# def list(subdir=None):
# def listdir(subdir=None):
# def mount(path, provider):
# def unmount(path, provider):
# def transform(pattern, transformer):
# def untransform(pattern, transformer):
# def open(filename, *args, **kwargs):
# def exists(filename):
# def isfile(filename):
# def isdir(filename):
# def dirname(path):
# def basename(path):
# def join(*paths, normalized=True):
# def split(path, *args, **kwargs):
# def normalize(path):
. Output only the next line. | raise filesystem.FileNotFound(filename) |
Predict the next line for this snippet: <|code_start|> assert transfs.list() == { '/', '/x', '/x/a.txt', '/x/a.txt.rot13', '/x/b.png' }
def test_transform_list_after(fs):
fs.transform('.txt$', DummyTransformer)
fs.mount('/x', DummyProvider({ '/a.txt', '/b.png' }))
test_transform_list(fs)
def test_transform_list_relative(dummyfs):
DummyTransformer.RELATIVE = True
try:
dummyfs.transform('.txt$', DummyTransformer)
assert dummyfs.list() == { '/', '/x', '/x/a.txt', '/x/b.png', '/x/x', '/x/x/a.txt.rot13' }
finally:
DummyTransformer.RELATIVE = False
def test_transform_list_relative_after(fs):
DummyTransformer.RELATIVE = True
try:
fs.transform('.txt$', DummyTransformer)
fs.mount('/x', DummyProvider({ '/a.txt', '/b.png' }))
assert fs.list() == { '/', '/x', '/x/a.txt', '/x/b.png', '/x/x', '/x/x/a.txt.rot13' }
finally:
DummyTransformer.RELATIVE = False
def test_transform_open(transfs):
with transfs.open('/x/a.txt.rot13') as f:
<|code_end|>
with the help of current file imports:
from rave import filesystem
from pytest import raises
from .support.filesystem import *
and context from other files:
# Path: rave/filesystem.py
# PATH_SEPARATOR = '/'
# ROOT = '/'
# BAD_PATH_PATTERN = re.compile(r'(?:{0}{{2,}}|(?:{0}|^)\.+(?:{0}|$))'.format(PATH_SEPARATOR))
# ENGINE_MOUNT = '/.rave'
# MODULE_MOUNT = '/.modules'
# GAME_MOUNT = '/'
# COMMON_MOUNT = '/.common'
# class FileSystemError(rave.common.raveError, IOError):
# class NativeError(FileSystemError):
# class FileNotFound(FileSystemError, FileNotFoundError):
# class AccessDenied(FileSystemError, PermissionError):
# class FileNotReadable(FileSystemError, PermissionError, io.UnsupportedOperation):
# class FileNotWritable(FileSystemError, PermissionError, io.UnsupportedOperation):
# class FileNotSeekable(FileSystemError, PermissionError, io.UnsupportedOperation):
# class FileClosed(FileSystemError, BrokenPipeError):
# class NotAFile(FileSystemError, IsADirectoryError):
# class NotADirectory(FileSystemError, NotADirectoryError):
# class FileSystem:
# class File(io.IOBase):
# class FileSystemProvider:
# def __init__(self, filename, message=None):
# def __init__(self, filename, parent):
# def __init__(self):
# def __repr__(self):
# def clear(self):
# def _build_cache(self):
# def _build_provider_cache(self, provider, root):
# def _build_transformer_cache(self, transformer, pattern):
# def _cache_directory(self, provider, root, path):
# def _cache_file(self, provider, root, path):
# def _cache_entry(self, provider, root, path):
# def _cache_transformed_file(self, transformer, path, handle):
# def _providers_for_file(self, path):
# def _local_file(self, root, path):
# def list(self, subdir=None):
# def listdir(self, subdir=None):
# def mount(self, path, provider):
# def unmount(self, path, provider):
# def transform(self, pattern, transformer):
# def untransform(self, pattern, transformer):
# def open(self, filename, *args, **kwargs):
# def exists(self, filename):
# def isdir(self, filename):
# def isfile(self, filename):
# def dirname(self, path):
# def basename(self, path):
# def join(self, *paths, normalized=True):
# def split(self, path, *args, **kwargs):
# def normalize(self, path):
# def __del__(self):
# def close(self):
# def opened(self):
# def readable(self):
# def writable(self):
# def seekable(self):
# def read(self, amount=None):
# def write(self, data):
# def seek(self, position, mode=os.SEEK_CUR):
# def tell(self):
# def __init__(self, fs):
# def __repr__(self):
# def list(self):
# def open(self, filename, *args, **kwargs):
# def has(self, filename):
# def isfile(self, filename):
# def isdir(self, filename):
# def current():
# def list(subdir=None):
# def listdir(subdir=None):
# def mount(path, provider):
# def unmount(path, provider):
# def transform(pattern, transformer):
# def untransform(pattern, transformer):
# def open(filename, *args, **kwargs):
# def exists(filename):
# def isfile(filename):
# def isdir(filename):
# def dirname(path):
# def basename(path):
# def join(*paths, normalized=True):
# def split(path, *args, **kwargs):
# def normalize(path):
, which may contain function names, class names, or code. Output only the next line. | assert isinstance(f, filesystem.File) |
Given snippet: <|code_start|> for fmt, pattern in FORMAT_PATTERNS.items():
if _formats & fmt:
game.resources.register_loader(ImageLoader, pattern)
_log.debug('Loaded support for {fmt} images.', fmt=FORMAT_NAMES[fmt])
else:
_log.warn('Failed to load support for {fmt} images.', fmt=FORMAT_NAMES[fmt])
class ImageData(rave.resources.ImageData):
__slots__ = ('surface',)
def __init__(self, surface, *args, **kwargs):
super().__init__(*args, **kwargs)
self.surface = surface
def __del__(self):
sdl2.SDL_FreeSurface(self.surface)
def get_data(self, amount=None):
if amount:
return self.surface.contents.pixels[:amount]
return self.surface.contents.pixels
class ImageLoader:
@classmethod
def can_load(cls, path, fd):
return True
@classmethod
def load(cls, path, fd):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import sdl2
import sdl2.ext
import sdl2.sdlimage as sdl2image
import rave.log
import rave.events
import rave.rendering
import rave.resources
from .common import fs_to_rwops
and context:
# Path: modules/sdl2/common/filesystem.py
# def fs_to_rwops(handle):
# return sdl2.rw_from_object(RWOpsWrapper(handle))
which might include code, classes, or functions. Output only the next line. | handle = fs_to_rwops(fd) |
Using the snippet: <|code_start|>
def test_empty(fs):
assert fs.list() == { '/' }
assert fs.listdir('/') == set()
def test_clear(dummyfs):
dummyfs.clear()
test_empty(dummyfs)
def test_list(dummyfs):
assert dummyfs.list() == { '/', '/x', '/x/a.txt', '/x/b.png' }
assert dummyfs.list('/x') == { '/', '/a.txt', '/b.png' }
def test_list_nested(nestedfs):
assert nestedfs.list() == { '/', '/x', '/x/y', '/x/y/z', '/x/y/c.txt', '/x/y/p.png' }
assert nestedfs.list('/x') == { '/', '/y', '/y/z', '/y/c.txt', '/y/p.png' }
def test_list_multiple(doublefs):
assert doublefs.list() == { '/', '/x', '/x/a.txt', '/x/b.png', '/y', '/y/c.exe', '/y/d.jpg' }
def test_list_merged(mergedfs):
assert mergedfs.list() == { '/', '/x', '/x/a.txt', '/x/b.png', '/x/c.exe', '/x/d.jpg' }
def test_list_nonexistent(dummyfs):
<|code_end|>
, determine the next line of code. You have imports:
from rave import filesystem
from pytest import raises
from .support.filesystem import *
and context (class names, function names, or code) available:
# Path: rave/filesystem.py
# PATH_SEPARATOR = '/'
# ROOT = '/'
# BAD_PATH_PATTERN = re.compile(r'(?:{0}{{2,}}|(?:{0}|^)\.+(?:{0}|$))'.format(PATH_SEPARATOR))
# ENGINE_MOUNT = '/.rave'
# MODULE_MOUNT = '/.modules'
# GAME_MOUNT = '/'
# COMMON_MOUNT = '/.common'
# class FileSystemError(rave.common.raveError, IOError):
# class NativeError(FileSystemError):
# class FileNotFound(FileSystemError, FileNotFoundError):
# class AccessDenied(FileSystemError, PermissionError):
# class FileNotReadable(FileSystemError, PermissionError, io.UnsupportedOperation):
# class FileNotWritable(FileSystemError, PermissionError, io.UnsupportedOperation):
# class FileNotSeekable(FileSystemError, PermissionError, io.UnsupportedOperation):
# class FileClosed(FileSystemError, BrokenPipeError):
# class NotAFile(FileSystemError, IsADirectoryError):
# class NotADirectory(FileSystemError, NotADirectoryError):
# class FileSystem:
# class File(io.IOBase):
# class FileSystemProvider:
# def __init__(self, filename, message=None):
# def __init__(self, filename, parent):
# def __init__(self):
# def __repr__(self):
# def clear(self):
# def _build_cache(self):
# def _build_provider_cache(self, provider, root):
# def _build_transformer_cache(self, transformer, pattern):
# def _cache_directory(self, provider, root, path):
# def _cache_file(self, provider, root, path):
# def _cache_entry(self, provider, root, path):
# def _cache_transformed_file(self, transformer, path, handle):
# def _providers_for_file(self, path):
# def _local_file(self, root, path):
# def list(self, subdir=None):
# def listdir(self, subdir=None):
# def mount(self, path, provider):
# def unmount(self, path, provider):
# def transform(self, pattern, transformer):
# def untransform(self, pattern, transformer):
# def open(self, filename, *args, **kwargs):
# def exists(self, filename):
# def isdir(self, filename):
# def isfile(self, filename):
# def dirname(self, path):
# def basename(self, path):
# def join(self, *paths, normalized=True):
# def split(self, path, *args, **kwargs):
# def normalize(self, path):
# def __del__(self):
# def close(self):
# def opened(self):
# def readable(self):
# def writable(self):
# def seekable(self):
# def read(self, amount=None):
# def write(self, data):
# def seek(self, position, mode=os.SEEK_CUR):
# def tell(self):
# def __init__(self, fs):
# def __repr__(self):
# def list(self):
# def open(self, filename, *args, **kwargs):
# def has(self, filename):
# def isfile(self, filename):
# def isdir(self, filename):
# def current():
# def list(subdir=None):
# def listdir(subdir=None):
# def mount(path, provider):
# def unmount(path, provider):
# def transform(pattern, transformer):
# def untransform(pattern, transformer):
# def open(filename, *args, **kwargs):
# def exists(filename):
# def isfile(filename):
# def isdir(filename):
# def dirname(path):
# def basename(path):
# def join(*paths, normalized=True):
# def split(path, *args, **kwargs):
# def normalize(path):
. Output only the next line. | with raises(filesystem.FileNotFound): |
Continue the code snippet: <|code_start|># Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in 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.
@pytest.mark.asyncio
async def test_fetch_id_token(http_request):
audience = "https://pubsub.googleapis.com"
token = await google.oauth2._id_token_async.fetch_id_token(http_request, audience)
<|code_end|>
. Use current file imports:
import pytest
import google.oauth2._id_token_async
from google.auth import jwt
and context (classes, functions, or code) from other files:
# Path: google/auth/jwt.py
# _DEFAULT_TOKEN_LIFETIME_SECS = 3600 # 1 hour in seconds
# _DEFAULT_MAX_CACHE_SIZE = 10
# _ALGORITHM_TO_VERIFIER_CLASS = {"RS256": crypt.RSAVerifier}
# _CRYPTOGRAPHY_BASED_ALGORITHMS = frozenset(["ES256"])
# _ALGORITHM_TO_VERIFIER_CLASS["ES256"] = es256.ES256Verifier # type: ignore
# def encode(signer, payload, header=None, key_id=None):
# def _decode_jwt_segment(encoded_section):
# def _unverified_decode(token):
# def decode_header(token):
# def _verify_iat_and_exp(payload, clock_skew_in_seconds=0):
# def decode(token, certs=None, verify=True, audience=None, clock_skew_in_seconds=0):
# def __init__(
# self,
# signer,
# issuer,
# subject,
# audience,
# additional_claims=None,
# token_lifetime=_DEFAULT_TOKEN_LIFETIME_SECS,
# quota_project_id=None,
# ):
# def _from_signer_and_info(cls, signer, info, **kwargs):
# def from_service_account_info(cls, info, **kwargs):
# def from_service_account_file(cls, filename, **kwargs):
# def from_signing_credentials(cls, credentials, audience, **kwargs):
# def with_claims(
# self, issuer=None, subject=None, audience=None, additional_claims=None
# ):
# def with_quota_project(self, quota_project_id):
# def _make_jwt(self):
# def refresh(self, request):
# def sign_bytes(self, message):
# def signer_email(self):
# def signer(self):
# def __init__(
# self,
# signer,
# issuer,
# subject,
# additional_claims=None,
# token_lifetime=_DEFAULT_TOKEN_LIFETIME_SECS,
# max_cache_size=_DEFAULT_MAX_CACHE_SIZE,
# quota_project_id=None,
# ):
# def _from_signer_and_info(cls, signer, info, **kwargs):
# def from_service_account_info(cls, info, **kwargs):
# def from_service_account_file(cls, filename, **kwargs):
# def from_signing_credentials(cls, credentials, **kwargs):
# def with_claims(self, issuer=None, subject=None, additional_claims=None):
# def with_quota_project(self, quota_project_id):
# def valid(self):
# def _make_jwt_for_audience(self, audience):
# def _get_jwt_for_audience(self, audience):
# def refresh(self, request):
# def before_request(self, request, method, url, headers):
# def sign_bytes(self, message):
# def signer_email(self):
# def signer(self):
# class Credentials(
# google.auth.credentials.Signing, google.auth.credentials.CredentialsWithQuotaProject
# ):
# class OnDemandCredentials(
# google.auth.credentials.Signing, google.auth.credentials.CredentialsWithQuotaProject
# ):
. Output only the next line. | _, payload, _, _ = jwt._unverified_decode(token) |
Given the code snippet: <|code_start|># You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
DATA_DIR = os.path.join(os.path.dirname(__file__), "data")
SERVICE_ACCOUNT_JSON_FILE = os.path.join(DATA_DIR, "service_account.json")
def test__convert_oauth2_credentials():
old_credentials = oauth2client.client.OAuth2Credentials(
"access_token",
"client_id",
"client_secret",
"refresh_token",
datetime.datetime.min,
"token_uri",
"user_agent",
scopes="one two",
)
<|code_end|>
, generate the next line using the imports in this file:
import datetime
import os
import sys
import mock
import oauth2client.client # type: ignore
import oauth2client.contrib.gce # type: ignore
import oauth2client.service_account # type: ignore
import pytest # type: ignore
import oauth2client.contrib.appengine # type: ignore
from six.moves import reload_module
from google.auth import _oauth2client
and context (functions, classes, or occasionally code) from other files:
# Path: google/auth/_oauth2client.py
# _HAS_APPENGINE = True
# _HAS_APPENGINE = False
# _CONVERT_ERROR_TMPL = "Unable to convert {} to a google-auth credentials class."
# _CLASS_CONVERSION_MAP = {
# oauth2client.client.OAuth2Credentials: _convert_oauth2_credentials,
# oauth2client.client.GoogleCredentials: _convert_oauth2_credentials,
# oauth2client.service_account.ServiceAccountCredentials: _convert_service_account_credentials,
# oauth2client.service_account._JWTAccessCredentials: _convert_service_account_credentials,
# oauth2client.contrib.gce.AppAssertionCredentials: _convert_gce_app_assertion_credentials,
# }
# def _convert_oauth2_credentials(credentials):
# def _convert_service_account_credentials(credentials):
# def _convert_gce_app_assertion_credentials(credentials):
# def _convert_appengine_app_assertion_credentials(credentials):
# def convert(credentials):
. Output only the next line. | new_credentials = _oauth2client._convert_oauth2_credentials(old_credentials) |
Based on the snippet: <|code_start|># Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in 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.
def test_fetch_id_token(http_request):
audience = "https://pubsub.googleapis.com"
token = google.oauth2.id_token.fetch_id_token(http_request, audience)
<|code_end|>
, predict the immediate next line with the help of imports:
import pytest
import google.oauth2.id_token
from google.auth import jwt
and context (classes, functions, sometimes code) from other files:
# Path: google/auth/jwt.py
# _DEFAULT_TOKEN_LIFETIME_SECS = 3600 # 1 hour in seconds
# _DEFAULT_MAX_CACHE_SIZE = 10
# _ALGORITHM_TO_VERIFIER_CLASS = {"RS256": crypt.RSAVerifier}
# _CRYPTOGRAPHY_BASED_ALGORITHMS = frozenset(["ES256"])
# _ALGORITHM_TO_VERIFIER_CLASS["ES256"] = es256.ES256Verifier # type: ignore
# def encode(signer, payload, header=None, key_id=None):
# def _decode_jwt_segment(encoded_section):
# def _unverified_decode(token):
# def decode_header(token):
# def _verify_iat_and_exp(payload, clock_skew_in_seconds=0):
# def decode(token, certs=None, verify=True, audience=None, clock_skew_in_seconds=0):
# def __init__(
# self,
# signer,
# issuer,
# subject,
# audience,
# additional_claims=None,
# token_lifetime=_DEFAULT_TOKEN_LIFETIME_SECS,
# quota_project_id=None,
# ):
# def _from_signer_and_info(cls, signer, info, **kwargs):
# def from_service_account_info(cls, info, **kwargs):
# def from_service_account_file(cls, filename, **kwargs):
# def from_signing_credentials(cls, credentials, audience, **kwargs):
# def with_claims(
# self, issuer=None, subject=None, audience=None, additional_claims=None
# ):
# def with_quota_project(self, quota_project_id):
# def _make_jwt(self):
# def refresh(self, request):
# def sign_bytes(self, message):
# def signer_email(self):
# def signer(self):
# def __init__(
# self,
# signer,
# issuer,
# subject,
# additional_claims=None,
# token_lifetime=_DEFAULT_TOKEN_LIFETIME_SECS,
# max_cache_size=_DEFAULT_MAX_CACHE_SIZE,
# quota_project_id=None,
# ):
# def _from_signer_and_info(cls, signer, info, **kwargs):
# def from_service_account_info(cls, info, **kwargs):
# def from_service_account_file(cls, filename, **kwargs):
# def from_signing_credentials(cls, credentials, **kwargs):
# def with_claims(self, issuer=None, subject=None, additional_claims=None):
# def with_quota_project(self, quota_project_id):
# def valid(self):
# def _make_jwt_for_audience(self, audience):
# def _get_jwt_for_audience(self, audience):
# def refresh(self, request):
# def before_request(self, request, method, url, headers):
# def sign_bytes(self, message):
# def signer_email(self):
# def signer(self):
# class Credentials(
# google.auth.credentials.Signing, google.auth.credentials.CredentialsWithQuotaProject
# ):
# class OnDemandCredentials(
# google.auth.credentials.Signing, google.auth.credentials.CredentialsWithQuotaProject
# ):
. Output only the next line. | _, payload, _, _ = jwt._unverified_decode(token) |
Predict the next line for this snippet: <|code_start|># See the License for the specific language governing permissions and
# limitations under the License.
class _AppIdentityModule(object):
"""The interface of the App Idenity app engine module.
See https://cloud.google.com/appengine/docs/standard/python/refdocs
/google.appengine.api.app_identity.app_identity
"""
def get_application_id(self):
raise NotImplementedError()
def sign_blob(self, bytes_to_sign, deadline=None):
raise NotImplementedError()
def get_service_account_name(self, deadline=None):
raise NotImplementedError()
def get_access_token(self, scopes, service_account_id=None):
raise NotImplementedError()
@pytest.fixture
def app_identity(monkeypatch):
"""Mocks the app_identity module for google.auth.app_engine."""
app_identity_module = mock.create_autospec(_AppIdentityModule, instance=True)
<|code_end|>
with the help of current file imports:
import datetime
import mock
import pytest # type: ignore
from google.auth import app_engine
and context from other files:
# Path: google/auth/app_engine.py
# class Signer(crypt.Signer):
# class Credentials(
# credentials.Scoped, credentials.Signing, credentials.CredentialsWithQuotaProject
# ):
# def key_id(self):
# def sign(self, message):
# def get_project_id():
# def __init__(
# self,
# scopes=None,
# default_scopes=None,
# service_account_id=None,
# quota_project_id=None,
# ):
# def refresh(self, request):
# def service_account_email(self):
# def requires_scopes(self):
# def with_scopes(self, scopes, default_scopes=None):
# def with_quota_project(self, quota_project_id):
# def sign_bytes(self, message):
# def signer_email(self):
# def signer(self):
, which may contain function names, class names, or code. Output only the next line. | monkeypatch.setattr(app_engine, "app_identity", app_identity_module) |
Next line prediction: <|code_start|># Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in 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.
EXPECT_PROJECT_ID = os.environ.get("EXPECT_PROJECT_ID")
@pytest.mark.asyncio
async def test_application_default_credentials(verify_refresh):
<|code_end|>
. Use current file imports:
(import os
import pytest
from google.auth import _default_async)
and context including class names, function names, or small code snippets from other files:
# Path: google/auth/_default_async.py
# def load_credentials_from_file(filename, scopes=None, quota_project_id=None):
# def _get_gcloud_sdk_credentials(quota_project_id=None):
# def _get_explicit_environ_credentials(quota_project_id=None):
# def _get_gae_credentials():
# def _get_gce_credentials(request=None):
# def default_async(scopes=None, request=None, quota_project_id=None):
. Output only the next line. | credentials, project_id = _default_async.default_async() |
Given snippet: <|code_start|> # Apply the default credentials to the headers to make the request.
headers = {}
credentials.apply(headers)
response = request(
url="https://dns.googleapis.com/dns/v1/projects/{}".format(project_id),
headers=headers,
)
if response.status == 200:
return response.data
def dns_access_client_library(_, project_id):
service = discovery.build("dns", "v1")
request = service.projects().get(project=project_id)
return request.execute()
@pytest.fixture(params=[dns_access_direct, dns_access_client_library])
def dns_access(request, http_request, service_account_info):
# Fill in the fixtures on the functions,
# so that we don't have to fill in the parameters manually.
def wrapper():
return request.param(http_request, service_account_info["project_id"])
yield wrapper
@pytest.fixture
def oidc_credentials(service_account_file, http_request):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import json
import os
import socket
import threading
import sys
import google.auth
import pytest
from tempfile import NamedTemporaryFile
from googleapiclient import discovery
from six.moves import BaseHTTPServer
from google.oauth2 import service_account
from mock import patch
and context:
# Path: google/oauth2/service_account.py
# _DEFAULT_TOKEN_LIFETIME_SECS = 3600 # 1 hour in seconds
# _GOOGLE_OAUTH2_TOKEN_ENDPOINT = "https://oauth2.googleapis.com/token"
# class Credentials(
# credentials.Signing, credentials.Scoped, credentials.CredentialsWithQuotaProject
# ):
# class IDTokenCredentials(credentials.Signing, credentials.CredentialsWithQuotaProject):
# def __init__(
# self,
# signer,
# service_account_email,
# token_uri,
# scopes=None,
# default_scopes=None,
# subject=None,
# project_id=None,
# quota_project_id=None,
# additional_claims=None,
# always_use_jwt_access=False,
# ):
# def _from_signer_and_info(cls, signer, info, **kwargs):
# def from_service_account_info(cls, info, **kwargs):
# def from_service_account_file(cls, filename, **kwargs):
# def service_account_email(self):
# def project_id(self):
# def requires_scopes(self):
# def with_scopes(self, scopes, default_scopes=None):
# def with_always_use_jwt_access(self, always_use_jwt_access):
# def with_subject(self, subject):
# def with_claims(self, additional_claims):
# def with_quota_project(self, quota_project_id):
# def _make_authorization_grant_assertion(self):
# def refresh(self, request):
# def _create_self_signed_jwt(self, audience):
# def sign_bytes(self, message):
# def signer(self):
# def signer_email(self):
# def __init__(
# self,
# signer,
# service_account_email,
# token_uri,
# target_audience,
# additional_claims=None,
# quota_project_id=None,
# ):
# def _from_signer_and_info(cls, signer, info, **kwargs):
# def from_service_account_info(cls, info, **kwargs):
# def from_service_account_file(cls, filename, **kwargs):
# def with_target_audience(self, target_audience):
# def with_quota_project(self, quota_project_id):
# def _make_authorization_grant_assertion(self):
# def refresh(self, request):
# def service_account_email(self):
# def sign_bytes(self, message):
# def signer(self):
# def signer_email(self):
which might include code, classes, or functions. Output only the next line. | result = service_account.IDTokenCredentials.from_service_account_file( |
Next line prediction: <|code_start|>
class TestResponse:
def test_ctor(self):
response = aiohttp_requests._Response(mock.sentinel.response)
assert response._response == mock.sentinel.response
@pytest.mark.asyncio
async def test_headers_prop(self):
rm = core.RequestMatch("url", headers={"Content-Encoding": "header prop"})
mock_response = await rm.build_response(core.URL("url"))
response = aiohttp_requests._Response(mock_response)
assert response.headers["Content-Encoding"] == "header prop"
@pytest.mark.asyncio
async def test_status_prop(self):
rm = core.RequestMatch("url", status=123)
mock_response = await rm.build_response(core.URL("url"))
response = aiohttp_requests._Response(mock_response)
assert response.status == 123
@pytest.mark.asyncio
async def test_data_prop(self):
mock_response = mock.AsyncMock()
mock_response.content.read.return_value = mock.sentinel.read
response = aiohttp_requests._Response(mock_response)
data = await response.data.read()
assert data == mock.sentinel.read
<|code_end|>
. Use current file imports:
(import aiohttp # type: ignore
import mock
import pytest # type: ignore
import google.auth._credentials_async
import google.auth.transport._mtls_helper
from aioresponses import aioresponses, core # type: ignore
from tests_async.transport import async_compliance
from google.auth.transport import _aiohttp_requests as aiohttp_requests)
and context including class names, function names, or small code snippets from other files:
# Path: tests_async/transport/async_compliance.py
# class RequestResponseTests(object):
# def server(self):
# def index():
# def server_error():
# def wait():
# async def test_request_basic(self, server):
# async def test_request_basic_with_http(self, server):
# async def test_request_with_timeout_success(self, server):
# async def test_request_with_timeout_failure(self, server):
# async def test_request_headers(self, server):
# async def test_request_error(self, server):
# async def test_connection_error(self):
#
# Path: google/auth/transport/_aiohttp_requests.py
# _DEFAULT_TIMEOUT = 180 # in seconds
# class _CombinedResponse(transport.Response):
# class _Response(transport.Response):
# class Request(transport.Request):
# class AuthorizedSession(aiohttp.ClientSession):
# def __init__(self, response):
# def _is_compressed(self):
# def status(self):
# def headers(self):
# def data(self):
# async def raw_content(self):
# async def content(self):
# def __init__(self, response):
# def status(self):
# def headers(self):
# def data(self):
# def __init__(self, session=None):
# async def __call__(
# self,
# url,
# method="GET",
# body=None,
# headers=None,
# timeout=_DEFAULT_TIMEOUT,
# **kwargs,
# ):
# def __init__(
# self,
# credentials,
# refresh_status_codes=transport.DEFAULT_REFRESH_STATUS_CODES,
# max_refresh_attempts=transport.DEFAULT_MAX_REFRESH_ATTEMPTS,
# refresh_timeout=None,
# auth_request=None,
# auto_decompress=False,
# ):
# async def request(
# self,
# method,
# url,
# data=None,
# headers=None,
# max_allowed_time=None,
# timeout=_DEFAULT_TIMEOUT,
# auto_decompress=False,
# **kwargs,
# ):
. Output only the next line. | class TestRequestResponse(async_compliance.RequestResponseTests): |
Here is a snippet: <|code_start|># Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in 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 TestCombinedResponse:
@pytest.mark.asyncio
async def test__is_compressed(self):
response = core.CallbackResult(headers={"Content-Encoding": "gzip"})
<|code_end|>
. Write the next line using the current file imports:
import aiohttp # type: ignore
import mock
import pytest # type: ignore
import google.auth._credentials_async
import google.auth.transport._mtls_helper
from aioresponses import aioresponses, core # type: ignore
from tests_async.transport import async_compliance
from google.auth.transport import _aiohttp_requests as aiohttp_requests
and context from other files:
# Path: tests_async/transport/async_compliance.py
# class RequestResponseTests(object):
# def server(self):
# def index():
# def server_error():
# def wait():
# async def test_request_basic(self, server):
# async def test_request_basic_with_http(self, server):
# async def test_request_with_timeout_success(self, server):
# async def test_request_with_timeout_failure(self, server):
# async def test_request_headers(self, server):
# async def test_request_error(self, server):
# async def test_connection_error(self):
#
# Path: google/auth/transport/_aiohttp_requests.py
# _DEFAULT_TIMEOUT = 180 # in seconds
# class _CombinedResponse(transport.Response):
# class _Response(transport.Response):
# class Request(transport.Request):
# class AuthorizedSession(aiohttp.ClientSession):
# def __init__(self, response):
# def _is_compressed(self):
# def status(self):
# def headers(self):
# def data(self):
# async def raw_content(self):
# async def content(self):
# def __init__(self, response):
# def status(self):
# def headers(self):
# def data(self):
# def __init__(self, session=None):
# async def __call__(
# self,
# url,
# method="GET",
# body=None,
# headers=None,
# timeout=_DEFAULT_TIMEOUT,
# **kwargs,
# ):
# def __init__(
# self,
# credentials,
# refresh_status_codes=transport.DEFAULT_REFRESH_STATUS_CODES,
# max_refresh_attempts=transport.DEFAULT_MAX_REFRESH_ATTEMPTS,
# refresh_timeout=None,
# auth_request=None,
# auto_decompress=False,
# ):
# async def request(
# self,
# method,
# url,
# data=None,
# headers=None,
# max_allowed_time=None,
# timeout=_DEFAULT_TIMEOUT,
# auto_decompress=False,
# **kwargs,
# ):
, which may include functions, classes, or code. Output only the next line. | combined_response = aiohttp_requests._CombinedResponse(response) |
Given snippet: <|code_start|>
# Blame Google translate...
TEST_APP_ES = {
"title": "Pruebas",
"tagline": "Aplicación de prueba",
"description": "Esta es una aplicación de prueba para, así, las cosas de la prueba.",
"slug": "test-app",
"icon": "test",
"colour": "#F4A15D",
"categories": ["code"],
"packages": [],
"dependencies": [],
"launch_command": "echo '¡Hola!'"
}
def test_get_applications(tmpdir):
application_dir = tmpdir.mkdir('applications')
# create some fake applications
test_app_1 = application_dir.join('test-app-1.app')
test_app_1.write(json.dumps(TEST_APP))
with patch(
'kano_apps.AppData._SYSTEM_APPLICATIONS_LOC',
os.path.join(application_dir.strpath, '')
):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import json
import os
from mock import patch
from kano_apps.AppData import get_applications
and context:
# Path: kano_apps/AppData.py
# def get_applications(parse_cmds=True, all_locales=False, current_locale=True):
# """ Get all the applications installed on the system.
#
# :param parse_cmds:
# :type parse_cmds: bool
#
# :returns: A dict with all apps.
# :rtype: dict
# """
#
# loc = os.path.expanduser(_SYSTEM_APPLICATIONS_LOC)
# blacklist = [
# "idle3.desktop", "idle.desktop", "idle-python2.7.desktop",
# "idle-python3.2.desktop", "xarchiver.desktop",
# "make-minecraft.desktop", "make-music.desktop", "make-pong.desktop",
# "make-snake.desktop", "kano-video.desktop", "lxsession-edit.desktop",
# "lxrandr.desktop", "lxinput.desktop", "obconf.desktop",
# "openbox.desktop", "libfm-pref-apps.desktop", "lxappearance.desktop",
# "htop.desktop", "pcmanfm-desktop-pref.desktop", "video-cli.desktop",
# "lxsession-default-apps.desktop", "pcmanfm.desktop", "help.desktop",
# "rxvt-unicode.desktop", "org.gnome.gedit.desktop",
# "chromium-browser.desktop", "openjdk-7-policytool.desktop"
# ]
#
# def _collect_apps(application_dir, skip_checks=False):
# if not os.path.exists(application_dir):
# return {}
#
# _applications = {}
#
# for f in os.listdir(os.path.join(application_dir, '')):
# fp = os.path.join(application_dir, f)
#
# if os.path.isdir(fp):
# continue
#
# if f[-4:] == ".app":
# data = load_from_app_file(fp, not skip_checks and parse_cmds)
# if data is not None:
# if not skip_checks and not is_app_installed(data):
# data["_install"] = True
#
# _applications[f] = data
# if "overrides" in data:
# blacklist.extend(data["overrides"])
#
# elif f[-8:] == ".desktop" and f[0:5] != "auto_":
# data = _load_from_dentry(fp)
# if data is not None:
# _applications[f] = data
#
# return _applications
#
# locales = [
# (DEFAULT_LOCALE, _SYSTEM_APPLICATIONS_LOC)
# ]
#
# locale_code = None
#
# if all_locales:
# locales += [
# (locale, get_locale_dir(locale))
# for locale in os.listdir(APP_LOCALE_DIR)
# ]
# elif current_locale:
# current_locale = ensure_utf_locale(get_locale())
# if current_locale and get_current_translation():
# locale_code = current_locale.split('.')[0]
# locales.append(
# (locale_code, get_locale_dir(locale_code))
# )
#
# apps = {}
#
# for locale, locale_dir in locales:
# locale_apps = _collect_apps(
# locale_dir, skip_checks=locale != DEFAULT_LOCALE
# )
#
# for app_name, app_data in locale_apps.iteritems():
# if app_name not in apps:
# apps[app_name] = {}
#
# if locale == DEFAULT_LOCALE:
# apps[app_name].update(app_data)
# else:
# if LOCALE_KEY not in apps[app_name]:
# apps[app_name][LOCALE_KEY] = {}
#
# apps[app_name][LOCALE_KEY][locale] = app_data
#
# if locale_code:
# apps = flatten_locale(apps, locale_code)
# filtered_apps = [
# app for f, app in apps.iteritems()
# if os.path.basename(app['origin']) not in blacklist
# ]
#
# return sorted(filtered_apps, key=lambda a: a["title"])
#
# return apps
which might include code, classes, or functions. Output only the next line. | apps = get_applications() |
Predict the next line after this snippet: <|code_start|>KDESK_EXEC = '/usr/bin/kdesk'
def _get_kdesk_icon_path(app):
kdesk_dir = os.path.expanduser(KDESK_DIR)
return kdesk_dir + re.sub(' ', '-', app["title"]) + ".lnk"
def _create_kdesk_icon(app):
icon_theme = Gtk.IconTheme.get_default()
icon_info = icon_theme.lookup_icon(app["icon"], 66, 0)
icon = app["icon"]
if icon_info is not None:
icon = icon_info.get_filename()
cmd = app["launch_command"]
if type(app["launch_command"]) is dict:
args = map(lambda s: "\"{}\"".format(s) if s.find(" ") >= 0 else s,
app["launch_command"]["args"])
cmd = app["launch_command"]["cmd"]
if len(args) > 0:
cmd += " " + " ".join(args)
kdesk_entry = 'table Icon\n'
kdesk_entry += ' Caption:\n'
kdesk_entry += ' AppID:\n'
kdesk_entry += ' Command: {}\n'.format(cmd)
kdesk_entry += ' Singleton: true\n'
kdesk_entry += ' Icon: {}\n'.format(icon)
<|code_end|>
using the current file's imports:
import os
import json
import re
from gi import require_version
from gi.repository import Gtk, Gdk
from kano_apps.Media import media_dir
and any relevant context from other files:
# Path: kano_apps/Media.py
# def media_dir():
# for path in MEDIA_LOCS:
# if os.path.exists(path):
# return os.path.abspath(path) + '/'
#
# raise Exception('Media directory not found.')
. Output only the next line. | kdesk_entry += ' IconHover: {}\n'.format(media_dir() + |
Using the snippet: <|code_start|>
def install_app(app, sudo_pwd=None, gui=True):
pkgs = " ".join(app["packages"] + app["dependencies"])
cmd = ""
if gui:
cmd = "rxvt -title 'Installing {}' -e bash -c ".format(app["title"])
if sudo_pwd:
cmd = "echo {} | sudo -S ".format(sudo_pwd) + cmd
if sudo_pwd:
cleanup_cmd = "echo {} | sudo -S dpkg --configure -a".format(sudo_pwd)
update_cmd = "echo {} | sudo -S apt-get update".format(sudo_pwd)
run = "sudo apt-get install -y {}".format(pkgs)
else:
cleanup_cmd = "sudo dpkg --configure -a".format(sudo_pwd)
update_cmd = "sudo apt-get update".format(sudo_pwd)
run = "sudo apt-get install -y {}".format(pkgs)
if gui:
run = "'{}'".format(run)
cmd += run
# make sure there are no broken packages on the system
run_cmd(cleanup_cmd)
run_cmd(update_cmd)
os.system(cmd.encode('utf8'))
done = True
<|code_end|>
, determine the next line of code. You have imports:
import os
import json
import time
import requests
from kano_apps.utils import get_dpkg_dict
from kano.utils import run_cmd, download_url, has_min_performance
from kano_world.config import load_conf
and context (class names, function names, or code) available:
# Path: kano_apps/utils.py
# def get_dpkg_dict(include_unpacked=False):
# apps_ok = dict()
# apps_other = dict()
#
# cmd = 'dpkg -l'
# o, _, _ = run_cmd(cmd)
# lines = o.splitlines()
# for l in lines[5:]:
# parts = l.split()
# state = parts[0]
# name = parts[1]
# version = parts[2]
#
# if state == 'ii' or (include_unpacked and state == 'iU'):
# apps_ok[name] = version
# else:
# apps_other[name] = version
#
# return apps_ok, apps_other
. Output only the next line. | installed_packages = get_dpkg_dict()[0] |
Predict the next line for this snippet: <|code_start|># coding: utf-8
# test_AppManage.py
#
# Copyright (C) 2016, 2015 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU GPL v2
#
# Tests for AppManage
@patch('kano_apps.AppManage.query_for_app')
@patch('kano_apps.AppManage.download_url')
@patch('kano_apps.AppManage.has_min_performance')
def test_download_app_error(
mock_has_min_performance, mock_download_url, mock_query_for_app
):
mock_query_for_app.return_value = json.loads(
'{ "icon_url": "foo.bar", "min_performance_score": 1, "title": "¡Hola!" }'
)
mock_has_min_performance.return_value = True
mock_download_url.return_value = (True, None)
install('kano-apps')
with pytest.raises(AppDownloadError) as excinfo:
<|code_end|>
with the help of current file imports:
import json
import pytest
from mock import patch
from kano_apps.AppManage import download_app, AppDownloadError
from kano_i18n.init import install
and context from other files:
# Path: kano_apps/AppManage.py
# def download_app(app_id_or_slug):
# data = query_for_app(app_id_or_slug)
#
# # download the icon
# icon_file_type = data['icon_url'].split(".")[-1]
# icon_path = '/tmp/{}.{}'.format(app_id_or_slug, icon_file_type)
# rv, err = download_url(data['icon_url'], icon_path)
# if not rv:
# msg = _("Unable to download the application ({})").format(err)
# raise AppDownloadError(msg)
#
# # Check if the app is going to run well on the hardware
# if 'min_performance_score' in data and \
# has_min_performance(data['min_performance_score']):
#
# msg = _(
# "{} won't be downloaded "
# "because the hardware is not performant enough"
# ).format(data['title'])
# raise AppDownloadError(msg)
#
# # Cleanup the JSON file
# data['icon'] = data['slug']
# del data['icon_url']
# data['time_installed'] = int(time.time())
# data['categories'] = map(lambda c: c.lower(), data['categories'])
# data['removable'] = True
#
# # FIXME: This should all be done in the API
# if 'priority' not in data:
# data['priority'] = get_prio(data['slug'])
#
# if data['slug'] == 'powerup':
# data['title'] = 'Make Light'
#
# # write out the data
# data_path = '/tmp/{}.app'.format(app_id_or_slug)
# with open(data_path, 'w') as f:
# f.write(json.dumps(data))
#
# return [data_path, icon_path]
#
# class AppDownloadError(Exception):
# pass
, which may contain function names, class names, or code. Output only the next line. | download_app('foo') |
Given snippet: <|code_start|># coding: utf-8
# test_AppManage.py
#
# Copyright (C) 2016, 2015 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU GPL v2
#
# Tests for AppManage
@patch('kano_apps.AppManage.query_for_app')
@patch('kano_apps.AppManage.download_url')
@patch('kano_apps.AppManage.has_min_performance')
def test_download_app_error(
mock_has_min_performance, mock_download_url, mock_query_for_app
):
mock_query_for_app.return_value = json.loads(
'{ "icon_url": "foo.bar", "min_performance_score": 1, "title": "¡Hola!" }'
)
mock_has_min_performance.return_value = True
mock_download_url.return_value = (True, None)
install('kano-apps')
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import json
import pytest
from mock import patch
from kano_apps.AppManage import download_app, AppDownloadError
from kano_i18n.init import install
and context:
# Path: kano_apps/AppManage.py
# def download_app(app_id_or_slug):
# data = query_for_app(app_id_or_slug)
#
# # download the icon
# icon_file_type = data['icon_url'].split(".")[-1]
# icon_path = '/tmp/{}.{}'.format(app_id_or_slug, icon_file_type)
# rv, err = download_url(data['icon_url'], icon_path)
# if not rv:
# msg = _("Unable to download the application ({})").format(err)
# raise AppDownloadError(msg)
#
# # Check if the app is going to run well on the hardware
# if 'min_performance_score' in data and \
# has_min_performance(data['min_performance_score']):
#
# msg = _(
# "{} won't be downloaded "
# "because the hardware is not performant enough"
# ).format(data['title'])
# raise AppDownloadError(msg)
#
# # Cleanup the JSON file
# data['icon'] = data['slug']
# del data['icon_url']
# data['time_installed'] = int(time.time())
# data['categories'] = map(lambda c: c.lower(), data['categories'])
# data['removable'] = True
#
# # FIXME: This should all be done in the API
# if 'priority' not in data:
# data['priority'] = get_prio(data['slug'])
#
# if data['slug'] == 'powerup':
# data['title'] = 'Make Light'
#
# # write out the data
# data_path = '/tmp/{}.app'.format(app_id_or_slug)
# with open(data_path, 'w') as f:
# f.write(json.dumps(data))
#
# return [data_path, icon_path]
#
# class AppDownloadError(Exception):
# pass
which might include code, classes, or functions. Output only the next line. | with pytest.raises(AppDownloadError) as excinfo: |
Using the snippet: <|code_start|># AppData.py
#
# Copyright (C) 2014, 2015 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU GPL v2
#
# Which apps to look for on the system
# The system directory that contains *.app and *.desktop entries
_SYSTEM_APPLICATIONS_LOC = '/usr/share/applications/'
DEFAULT_LOCALE = 'en_US'
LOCALE_KEY = 'locale'
APP_LOCALE_DIR = os.path.join(_SYSTEM_APPLICATIONS_LOC, 'locale')
# Store the package list globally so it doesn't get parsed every time
# we query for applications - it takes some time to parse it.
<|code_end|>
, determine the next line of code. You have imports:
import os
import re
import json
from kano_settings.system.locale import get_locale, ensure_utf_locale
from kano_apps.utils import get_dpkg_dict
from kano_i18n.init import get_current_translation
and context (class names, function names, or code) available:
# Path: kano_apps/utils.py
# def get_dpkg_dict(include_unpacked=False):
# apps_ok = dict()
# apps_other = dict()
#
# cmd = 'dpkg -l'
# o, _, _ = run_cmd(cmd)
# lines = o.splitlines()
# for l in lines[5:]:
# parts = l.split()
# state = parts[0]
# name = parts[1]
# version = parts[2]
#
# if state == 'ii' or (include_unpacked and state == 'iU'):
# apps_ok[name] = version
# else:
# apps_other[name] = version
#
# return apps_ok, apps_other
. Output only the next line. | _INSTALLED_PKGS = get_dpkg_dict()[0] |
Given snippet: <|code_start|>
THROTTLE_PARAMS = [10, 60, 'user_reads']
def throttle(*args, **kwargs):
@decorator
def inner_func(func, *inner_args, **inner_kwargs):
return func(*inner_args, **inner_kwargs)
return inner_func
def fullurl(url):
return settings.SITE_DOMAIN + url
class ParliamentHandler(BaseHandler):
allowed_methods = ('GET',)
@throttle(*THROTTLE_PARAMS)
def read(self, request, parliament_number=None):
if parliament_number is None:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.core.urlresolvers import reverse
from django.http import Http404
from django.conf import settings
from piston.handler import BaseHandler
from piston.decorator import decorator
from tagging.models import Tag, TaggedItem
from bundestagger.bundestag.models import Parliament, ParliamentSession, Speech
from random import randint
and context:
# Path: bundestagger/bundestag/models.py
# class Parliament(models.Model):
# number = models.IntegerField()
# start = models.DateField(default=datetime.datetime.today, null=True, blank=True)
# end = models.DateField(default=datetime.datetime.today, null=True, blank=True)
#
# def __unicode__(self):
# return u"Parliament %d" % (self.number,)
#
# class ParliamentSession(models.Model):
# parliament = models.ForeignKey(Parliament)
# number = models.PositiveSmallIntegerField(db_index=True)
# date = models.DateTimeField()
# until = models.DateTimeField()
# checked = models.BooleanField(default=False)
#
# tags = models.TextField(blank=True)
#
# objects = ParliamentSessionManager()
#
# def __unicode__(self):
# return u"%d. Sitzung (%s) des %d. Deutschen Bundestags" % (self.number, self.date.strftime("%d.%m.%Y"), self.parliament.number)
#
# def get_absolute_url(self):
# return reverse("bundestagger-bundestag-show_session", args=(self.parliament.number, self.number))
#
# @property
# def tag_list(self):
# return [tag.strip() for tag in self.tags.split(",") if len(tag.strip())>0]
#
# def update_tags(self,new_tags):
# tag_set = set([t.strip() for t in self.tags.split(",") if len(t.strip())>0])
# tag_set.update([t.strip() for t in new_tags.split(",") if len(t.strip())>0])
# self.tags = ",".join(tag_set)
# self.clear_cache()
# self.save()
#
# @property
# def document_url(self):
# return "http://dip21.bundestag.de/dip21/btp/%(leg)d/%(leg)d%(id)s.pdf" % {"leg":self.parliament.number, "id": padd_zeros(self.number)}
#
# def clear_cache(self):
# invalidate_cache(reverse("bundestagger-bundestag-list_sessions"))
# last_speech = self.speech_set.order_by("-ordernr")[0]
# url = last_speech.get_base_url()
# invalidate_cache_all_pages(url, last_speech.ordernr, settings.SPEECHES_PER_PAGE)
#
# class Speech(models.Model):
# session = models.ForeignKey(ParliamentSession)
# ordernr = models.IntegerField()
# speaker = models.ForeignKey(Politician)
# start = models.DateTimeField(blank=True, default=None, null=True)
# end = models.DateTimeField(blank=True, default=None, null=True)
# webtv = models.IntegerField(blank=True, null=True)
#
# tags = TagField(blank=True)
#
# def save(self, *args, **kwargs):
# super(Speech,self).save(*args, **kwargs)
# self.session.update_tags(self.tags)
#
#
# def __unicode__(self):
# return u"Rede von %s in der %s" % (self.speaker, self.session)
#
# def text(self):
# return u"\n".join(map(lambda x:x.text, self.speechpart_set.order_by("ordernr")))
#
# @property
# def tag_list(self):
# return [tag.strip() for tag in self.tags.split(",") if len(tag.strip())>0]
#
# @property
# def webtv_url(self):
# if self.webtv is not None:
# return u"http://webtv.bundestag.de/iptv/player/macros/_v_f_514_de/od_player.html?singleton=true&content=%d" % (self.webtv,)
# return u""
#
# @property
# def webtv_search(self):
# url = u"http://webtv.bundestag.de/iptv/player/macros/bttv/list.html?pageOffset=0&pageLength=40&sort=2&lastName=%(lastname)s&firstName=%(firstname)s&fraction=&meetingNumber=%(session)s&period=%(period)s&startDay=&endDay=&topic=&submit=Suchen"
# return url % { "firstname": self.speaker.first_name,
# "lastname": self.speaker.last_name,
# "session": self.session.number,
# "period": self.session.parliament.number
# }
#
# def get_base_url(self):
# return reverse("bundestagger-bundestag-show_session", args=(self.session.parliament.number, self.session.number))
#
# def get_absolute_url(self):
# page = get_page(self.ordernr, settings.SPEECHES_PER_PAGE)
# if page == 1:
# page = ""
# else:
# page = "?page=%d" % page
# fragment = "#speech-%d" % self.id
# return self.get_base_url() + page + fragment
#
# def clear_cache(self):
# url = self.get_base_url()
# invalidate_cache(url, self.ordernr, settings.SPEECHES_PER_PAGE)
which might include code, classes, or functions. Output only the next line. | return [{"href": self.get_url(p)} for p in Parliament.objects.all()] |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
class BundesOpenidConsumer(SessionConsumer):
session_key = 'openid'
openid_required_message = 'Gib eine OpenID ein'
xri_disabled_message = 'i-names werden nicht unterstützt'
openid_invalid_message = 'Die OpenID ist nicht gültig'
request_cancelled_message = 'Die Anfrage wurde abgebrochen'
message_loggedin = "Erfolgreich eingeloggt"
message_loggedout = "Erfolgreich ausgeloggt"
failure_message = 'Fehler: %s'
setup_needed_message = 'Setup benötigt'
sign_next_param = False
salt_next = '07n98kpajapd290?(H"N=)(czar3)' # Adds extra saltiness to the ?next= salt
xri_enabled = False
on_complete_url = None
trust_root = settings.SITE_DOMAIN # If None, full URL to endpoint is used
logo_path = None # Path to the OpenID logo, as used by the login view
def show_error(self, request, message, exception=None):
messages.error(request, message)
return HttpResponseRedirect("/")
def show_message(self, request, title, message):
messages.info(request, message)
return HttpResponseRedirect("/")
def on_success(self, request, identity_url, openid_response):
messages.info(request, self.message_loggedin)
<|code_end|>
, generate the next line using the imports in this file:
from django.http import HttpResponseRedirect
from django.conf import settings
from django_openid.consumer import SessionConsumer
from django.contrib import messages
from bundestagger.account.auth import login, logout
and context (functions, classes, or occasionally code) from other files:
# Path: bundestagger/account/auth.py
# def login(request, openid):
# try:
# user = User.objects.get(openid=openid)
# except User.DoesNotExist:
# user = User.objects.create(openid=openid, username="Nutzer")
# user.username = "%s%d" % (user.username,user.id)
# user.save()
# request.session["bundesuser"] = user
# return True
#
# def logout(request):
# if "bundesuser" in request.session:
# del request.session["bundesuser"]
# if "openids" in request.session:
# del request.session["openids"]
# if "openid" in request.session:
# del request.session["openid"]
. Output only the next line. | login(request, identity_url) |
Using the snippet: <|code_start|> session_key = 'openid'
openid_required_message = 'Gib eine OpenID ein'
xri_disabled_message = 'i-names werden nicht unterstützt'
openid_invalid_message = 'Die OpenID ist nicht gültig'
request_cancelled_message = 'Die Anfrage wurde abgebrochen'
message_loggedin = "Erfolgreich eingeloggt"
message_loggedout = "Erfolgreich ausgeloggt"
failure_message = 'Fehler: %s'
setup_needed_message = 'Setup benötigt'
sign_next_param = False
salt_next = '07n98kpajapd290?(H"N=)(czar3)' # Adds extra saltiness to the ?next= salt
xri_enabled = False
on_complete_url = None
trust_root = settings.SITE_DOMAIN # If None, full URL to endpoint is used
logo_path = None # Path to the OpenID logo, as used by the login view
def show_error(self, request, message, exception=None):
messages.error(request, message)
return HttpResponseRedirect("/")
def show_message(self, request, title, message):
messages.info(request, message)
return HttpResponseRedirect("/")
def on_success(self, request, identity_url, openid_response):
messages.info(request, self.message_loggedin)
login(request, identity_url)
return super(BundesOpenidConsumer,self).on_success(request, identity_url, openid_response)
def do_logout(self, request):
<|code_end|>
, determine the next line of code. You have imports:
from django.http import HttpResponseRedirect
from django.conf import settings
from django_openid.consumer import SessionConsumer
from django.contrib import messages
from bundestagger.account.auth import login, logout
and context (class names, function names, or code) available:
# Path: bundestagger/account/auth.py
# def login(request, openid):
# try:
# user = User.objects.get(openid=openid)
# except User.DoesNotExist:
# user = User.objects.create(openid=openid, username="Nutzer")
# user.username = "%s%d" % (user.username,user.id)
# user.save()
# request.session["bundesuser"] = user
# return True
#
# def logout(request):
# if "bundesuser" in request.session:
# del request.session["bundesuser"]
# if "openids" in request.session:
# del request.session["openids"]
# if "openid" in request.session:
# del request.session["openid"]
. Output only the next line. | logout(request) |
Predict the next line for this snippet: <|code_start|>class ParliamentSession(models.Model):
parliament = models.ForeignKey(Parliament)
number = models.PositiveSmallIntegerField(db_index=True)
date = models.DateTimeField()
until = models.DateTimeField()
checked = models.BooleanField(default=False)
tags = models.TextField(blank=True)
objects = ParliamentSessionManager()
def __unicode__(self):
return u"%d. Sitzung (%s) des %d. Deutschen Bundestags" % (self.number, self.date.strftime("%d.%m.%Y"), self.parliament.number)
def get_absolute_url(self):
return reverse("bundestagger-bundestag-show_session", args=(self.parliament.number, self.number))
@property
def tag_list(self):
return [tag.strip() for tag in self.tags.split(",") if len(tag.strip())>0]
def update_tags(self,new_tags):
tag_set = set([t.strip() for t in self.tags.split(",") if len(t.strip())>0])
tag_set.update([t.strip() for t in new_tags.split(",") if len(t.strip())>0])
self.tags = ",".join(tag_set)
self.clear_cache()
self.save()
@property
def document_url(self):
<|code_end|>
with the help of current file imports:
import datetime
import re
import django.dispatch
from difflib import SequenceMatcher
from django.db import models
from django.db.models import Q
from django.conf import settings
from django.core.urlresolvers import reverse
from django.conf import settings
from django.template.defaultfilters import slugify
from tagging.fields import TagField
from bundestagger.helper.utils import padd_zeros, invalidate_cache, invalidate_cache_all_pages, get_page
and context from other files:
# Path: bundestagger/helper/utils.py
# def padd_zeros(num, padd_base=3):
# num = str(num)
# for k in range(padd_base-len(num)):
# num = "0"+num
# return num
#
# def invalidate_cache(path, *args):
# page = None
# if len(args)==2:
# index, max_per_page = args
# page = get_page(index, max_per_page)
# if page is not None and page != 1:
# request = FakeRequest(path, {"page": page})
# else:
# request = FakeRequest(path)
# cache.delete(get_cache_key(request))
#
# def invalidate_cache_all_pages(path, highest, max_per_page):
# last = get_page(highest,max_per_page)
# request = FakeRequest(path)
# cache.delete(get_cache_key(request))
# for i in range(last-1)+2:
# request = FakeRequest(path, {"page": last})
# cache.delete(get_cache_key(request))
#
# def get_page(index, max_per_page):
# return int(math.ceil(float(index) / max_per_page))
, which may contain function names, class names, or code. Output only the next line. | return "http://dip21.bundestag.de/dip21/btp/%(leg)d/%(leg)d%(id)s.pdf" % {"leg":self.parliament.number, "id": padd_zeros(self.number)} |
Given the following code snippet before the placeholder: <|code_start|> date = models.DateTimeField()
until = models.DateTimeField()
checked = models.BooleanField(default=False)
tags = models.TextField(blank=True)
objects = ParliamentSessionManager()
def __unicode__(self):
return u"%d. Sitzung (%s) des %d. Deutschen Bundestags" % (self.number, self.date.strftime("%d.%m.%Y"), self.parliament.number)
def get_absolute_url(self):
return reverse("bundestagger-bundestag-show_session", args=(self.parliament.number, self.number))
@property
def tag_list(self):
return [tag.strip() for tag in self.tags.split(",") if len(tag.strip())>0]
def update_tags(self,new_tags):
tag_set = set([t.strip() for t in self.tags.split(",") if len(t.strip())>0])
tag_set.update([t.strip() for t in new_tags.split(",") if len(t.strip())>0])
self.tags = ",".join(tag_set)
self.clear_cache()
self.save()
@property
def document_url(self):
return "http://dip21.bundestag.de/dip21/btp/%(leg)d/%(leg)d%(id)s.pdf" % {"leg":self.parliament.number, "id": padd_zeros(self.number)}
def clear_cache(self):
<|code_end|>
, predict the next line using imports from the current file:
import datetime
import re
import django.dispatch
from difflib import SequenceMatcher
from django.db import models
from django.db.models import Q
from django.conf import settings
from django.core.urlresolvers import reverse
from django.conf import settings
from django.template.defaultfilters import slugify
from tagging.fields import TagField
from bundestagger.helper.utils import padd_zeros, invalidate_cache, invalidate_cache_all_pages, get_page
and context including class names, function names, and sometimes code from other files:
# Path: bundestagger/helper/utils.py
# def padd_zeros(num, padd_base=3):
# num = str(num)
# for k in range(padd_base-len(num)):
# num = "0"+num
# return num
#
# def invalidate_cache(path, *args):
# page = None
# if len(args)==2:
# index, max_per_page = args
# page = get_page(index, max_per_page)
# if page is not None and page != 1:
# request = FakeRequest(path, {"page": page})
# else:
# request = FakeRequest(path)
# cache.delete(get_cache_key(request))
#
# def invalidate_cache_all_pages(path, highest, max_per_page):
# last = get_page(highest,max_per_page)
# request = FakeRequest(path)
# cache.delete(get_cache_key(request))
# for i in range(last-1)+2:
# request = FakeRequest(path, {"page": last})
# cache.delete(get_cache_key(request))
#
# def get_page(index, max_per_page):
# return int(math.ceil(float(index) / max_per_page))
. Output only the next line. | invalidate_cache(reverse("bundestagger-bundestag-list_sessions")) |
Predict the next line after this snippet: <|code_start|>
tags = models.TextField(blank=True)
objects = ParliamentSessionManager()
def __unicode__(self):
return u"%d. Sitzung (%s) des %d. Deutschen Bundestags" % (self.number, self.date.strftime("%d.%m.%Y"), self.parliament.number)
def get_absolute_url(self):
return reverse("bundestagger-bundestag-show_session", args=(self.parliament.number, self.number))
@property
def tag_list(self):
return [tag.strip() for tag in self.tags.split(",") if len(tag.strip())>0]
def update_tags(self,new_tags):
tag_set = set([t.strip() for t in self.tags.split(",") if len(t.strip())>0])
tag_set.update([t.strip() for t in new_tags.split(",") if len(t.strip())>0])
self.tags = ",".join(tag_set)
self.clear_cache()
self.save()
@property
def document_url(self):
return "http://dip21.bundestag.de/dip21/btp/%(leg)d/%(leg)d%(id)s.pdf" % {"leg":self.parliament.number, "id": padd_zeros(self.number)}
def clear_cache(self):
invalidate_cache(reverse("bundestagger-bundestag-list_sessions"))
last_speech = self.speech_set.order_by("-ordernr")[0]
url = last_speech.get_base_url()
<|code_end|>
using the current file's imports:
import datetime
import re
import django.dispatch
from difflib import SequenceMatcher
from django.db import models
from django.db.models import Q
from django.conf import settings
from django.core.urlresolvers import reverse
from django.conf import settings
from django.template.defaultfilters import slugify
from tagging.fields import TagField
from bundestagger.helper.utils import padd_zeros, invalidate_cache, invalidate_cache_all_pages, get_page
and any relevant context from other files:
# Path: bundestagger/helper/utils.py
# def padd_zeros(num, padd_base=3):
# num = str(num)
# for k in range(padd_base-len(num)):
# num = "0"+num
# return num
#
# def invalidate_cache(path, *args):
# page = None
# if len(args)==2:
# index, max_per_page = args
# page = get_page(index, max_per_page)
# if page is not None and page != 1:
# request = FakeRequest(path, {"page": page})
# else:
# request = FakeRequest(path)
# cache.delete(get_cache_key(request))
#
# def invalidate_cache_all_pages(path, highest, max_per_page):
# last = get_page(highest,max_per_page)
# request = FakeRequest(path)
# cache.delete(get_cache_key(request))
# for i in range(last-1)+2:
# request = FakeRequest(path, {"page": last})
# cache.delete(get_cache_key(request))
#
# def get_page(index, max_per_page):
# return int(math.ceil(float(index) / max_per_page))
. Output only the next line. | invalidate_cache_all_pages(url, last_speech.ordernr, settings.SPEECHES_PER_PAGE) |
Based on the snippet: <|code_start|>
def __unicode__(self):
return u"Rede von %s in der %s" % (self.speaker, self.session)
def text(self):
return u"\n".join(map(lambda x:x.text, self.speechpart_set.order_by("ordernr")))
@property
def tag_list(self):
return [tag.strip() for tag in self.tags.split(",") if len(tag.strip())>0]
@property
def webtv_url(self):
if self.webtv is not None:
return u"http://webtv.bundestag.de/iptv/player/macros/_v_f_514_de/od_player.html?singleton=true&content=%d" % (self.webtv,)
return u""
@property
def webtv_search(self):
url = u"http://webtv.bundestag.de/iptv/player/macros/bttv/list.html?pageOffset=0&pageLength=40&sort=2&lastName=%(lastname)s&firstName=%(firstname)s&fraction=&meetingNumber=%(session)s&period=%(period)s&startDay=&endDay=&topic=&submit=Suchen"
return url % { "firstname": self.speaker.first_name,
"lastname": self.speaker.last_name,
"session": self.session.number,
"period": self.session.parliament.number
}
def get_base_url(self):
return reverse("bundestagger-bundestag-show_session", args=(self.session.parliament.number, self.session.number))
def get_absolute_url(self):
<|code_end|>
, predict the immediate next line with the help of imports:
import datetime
import re
import django.dispatch
from difflib import SequenceMatcher
from django.db import models
from django.db.models import Q
from django.conf import settings
from django.core.urlresolvers import reverse
from django.conf import settings
from django.template.defaultfilters import slugify
from tagging.fields import TagField
from bundestagger.helper.utils import padd_zeros, invalidate_cache, invalidate_cache_all_pages, get_page
and context (classes, functions, sometimes code) from other files:
# Path: bundestagger/helper/utils.py
# def padd_zeros(num, padd_base=3):
# num = str(num)
# for k in range(padd_base-len(num)):
# num = "0"+num
# return num
#
# def invalidate_cache(path, *args):
# page = None
# if len(args)==2:
# index, max_per_page = args
# page = get_page(index, max_per_page)
# if page is not None and page != 1:
# request = FakeRequest(path, {"page": page})
# else:
# request = FakeRequest(path)
# cache.delete(get_cache_key(request))
#
# def invalidate_cache_all_pages(path, highest, max_per_page):
# last = get_page(highest,max_per_page)
# request = FakeRequest(path)
# cache.delete(get_cache_key(request))
# for i in range(last-1)+2:
# request = FakeRequest(path, {"page": last})
# cache.delete(get_cache_key(request))
#
# def get_page(index, max_per_page):
# return int(math.ceil(float(index) / max_per_page))
. Output only the next line. | page = get_page(self.ordernr, settings.SPEECHES_PER_PAGE) |
Next line prediction: <|code_start|>
register = Library()
class TagsFormNode(Node):
def __init__(self, context_var):
self.context_var = context_var
def render(self, context):
<|code_end|>
. Use current file imports:
(from django.template import Library, Node, TemplateSyntaxError
from django.contrib.contenttypes.models import ContentType
from django.core.urlresolvers import reverse
from bundestagger.bundestagging.forms import TagsForm)
and context including class names, function names, or small code snippets from other files:
# Path: bundestagger/bundestagging/forms.py
# class TagsForm(forms.Form):
# tags = forms.CharField(widget=forms.TextInput(attrs={"class": "autocompleteme"}))
. Output only the next line. | context[self.context_var] = TagsForm(auto_id=False) |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
@is_post
def logout(request):
logout_func(request)
next = "/"
if "next" in request.POST:
next = request.POST["next"]
return redirect(next)
@is_post
<|code_end|>
using the current file's imports:
from django.http import Http404, HttpResponseBadRequest, HttpResponseForbidden, HttpResponseNotAllowed
from django.shortcuts import redirect
from django.contrib import messages
from bundestagger.helper.utils import is_post
from bundestagger.account.auth import logged_in
from bundestagger.account.models import User
from bundestagger.account.auth import logout as logout_func
and any relevant context from other files:
# Path: bundestagger/helper/utils.py
# def is_post(func):
# return is_method("POST", func)
#
# Path: bundestagger/account/auth.py
# def logged_in(func):
# def loggedin_func(*args, **kwargs):
# request = args[0]
# if "bundesuser" in request.session:
# request.bundesuser = request.session["bundesuser"]
# return func(*args, **kwargs)
# raise PermissionDenied
# return loggedin_func
#
# Path: bundestagger/account/models.py
# class User(models.Model):
# openid = models.CharField(blank=True, max_length=255)
# ipaddress = models.IPAddressField(blank=True, null=True)
# username = models.CharField(null=True, blank=True, max_length=30)
# level = models.IntegerField(default=0)
# last_seen = models.DateTimeField(auto_now=True)
#
# def __unicode__(self):
# return self.username
#
# @property
# def is_moderator(self):
# return self.level >= EDIT_LEVEL
#
# @property
# def is_admin(self):
# return self.level >= SUPER_LEVEL
. Output only the next line. | @logged_in |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
@is_post
def logout(request):
logout_func(request)
next = "/"
if "next" in request.POST:
next = request.POST["next"]
return redirect(next)
@is_post
@logged_in
def change_username(request):
if "username" in request.POST:
user = request.bundesuser
username = request.POST["username"]
if username != user.username:
if len(username)>20:
messages.add_message(request, messages.INFO, u"Username ist zu lang")
elif len(username)==0:
messages.add_message(request, messages.INFO, u"Username ist zu kurz")
else:
<|code_end|>
, determine the next line of code. You have imports:
from django.http import Http404, HttpResponseBadRequest, HttpResponseForbidden, HttpResponseNotAllowed
from django.shortcuts import redirect
from django.contrib import messages
from bundestagger.helper.utils import is_post
from bundestagger.account.auth import logged_in
from bundestagger.account.models import User
from bundestagger.account.auth import logout as logout_func
and context (class names, function names, or code) available:
# Path: bundestagger/helper/utils.py
# def is_post(func):
# return is_method("POST", func)
#
# Path: bundestagger/account/auth.py
# def logged_in(func):
# def loggedin_func(*args, **kwargs):
# request = args[0]
# if "bundesuser" in request.session:
# request.bundesuser = request.session["bundesuser"]
# return func(*args, **kwargs)
# raise PermissionDenied
# return loggedin_func
#
# Path: bundestagger/account/models.py
# class User(models.Model):
# openid = models.CharField(blank=True, max_length=255)
# ipaddress = models.IPAddressField(blank=True, null=True)
# username = models.CharField(null=True, blank=True, max_length=30)
# level = models.IntegerField(default=0)
# last_seen = models.DateTimeField(auto_now=True)
#
# def __unicode__(self):
# return self.username
#
# @property
# def is_moderator(self):
# return self.level >= EDIT_LEVEL
#
# @property
# def is_admin(self):
# return self.level >= SUPER_LEVEL
. Output only the next line. | uc = User.objects.filter(username=username).count() |
Given snippet: <|code_start|>
def get_user(request):
if "bundesuser" in request.session:
return request.session["bundesuser"]
return None
def login(request, openid):
try:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.core.exceptions import PermissionDenied
from bundestagger.account.models import User
and context:
# Path: bundestagger/account/models.py
# class User(models.Model):
# openid = models.CharField(blank=True, max_length=255)
# ipaddress = models.IPAddressField(blank=True, null=True)
# username = models.CharField(null=True, blank=True, max_length=30)
# level = models.IntegerField(default=0)
# last_seen = models.DateTimeField(auto_now=True)
#
# def __unicode__(self):
# return self.username
#
# @property
# def is_moderator(self):
# return self.level >= EDIT_LEVEL
#
# @property
# def is_admin(self):
# return self.level >= SUPER_LEVEL
which might include code, classes, or functions. Output only the next line. | user = User.objects.get(openid=openid) |
Given the following code snippet before the placeholder: <|code_start|> except (EmptyPage, InvalidPage):
page_obj = paginator.page(paginator.num_pages)
gt = ((page - 1) * settings.SPEECHES_PER_PAGE)
lte = (page * settings.SPEECHES_PER_PAGE)
speech_parts = SpeechPart.objects.filter(speech__session=parliament_session)\
.filter(speech__ordernr__gt=gt, speech__ordernr__lte=lte)\
.order_by("speech__ordernr", "ordernr")\
.select_related("speech", "speech__speaker", "speech__speaker__party")
speeches = groupby(speech_parts, lambda sp: sp.speech)
new_speeches = []
for speech, it in speeches:
speech.speech_parts = list(it)
new_speeches.append(speech)
events = Event.objects.filter(context__id__in=[speech_part.id for speech_part in speech_parts])\
.select_related("context", "actor_politician", "actor_party")
events = groupby(events, lambda e: e.context.id)
new_events = {}
for k,v in events:
new_events[k] = list(v)
return render_to_response("bundestag/show.html", RequestContext(request, {"session" : parliament_session,
"speech_parts": speech_parts,
"speeches": new_speeches,
"events": new_events,
"paginator": paginator,
"page_obj":page_obj,
# "sessiontops":sessiontops
"all_speeches": all_speeches
}))
@is_post
<|code_end|>
, predict the next line using imports from the current file:
import re
from django.shortcuts import render_to_response, get_object_or_404, redirect
from django.http import HttpResponse, Http404, HttpResponseBadRequest, HttpResponseForbidden, HttpResponseNotAllowed
from django.template import RequestContext
from django.utils.itercompat import groupby
from django.core.paginator import Paginator, EmptyPage, InvalidPage
from django.conf import settings
from django.db.models import Q
from improvetext.models import Improvement
from models import ParliamentSession, Speech, SpeechPart, Event, Politician
from forms import EditSpeechPartForm
from bundestagger.account.auth import logged_in
from bundestagger.helper.utils import invalidate_cache, is_post, is_get
and context including class names, function names, and sometimes code from other files:
# Path: bundestagger/account/auth.py
# def logged_in(func):
# def loggedin_func(*args, **kwargs):
# request = args[0]
# if "bundesuser" in request.session:
# request.bundesuser = request.session["bundesuser"]
# return func(*args, **kwargs)
# raise PermissionDenied
# return loggedin_func
#
# Path: bundestagger/helper/utils.py
# def invalidate_cache(path, *args):
# page = None
# if len(args)==2:
# index, max_per_page = args
# page = get_page(index, max_per_page)
# if page is not None and page != 1:
# request = FakeRequest(path, {"page": page})
# else:
# request = FakeRequest(path)
# cache.delete(get_cache_key(request))
#
# def is_post(func):
# return is_method("POST", func)
#
# def is_get(func):
# return is_method("GET", func)
. Output only the next line. | @logged_in |
Here is a snippet: <|code_start|> page_obj = paginator.page(page)
except (EmptyPage, InvalidPage):
page_obj = paginator.page(paginator.num_pages)
gt = ((page - 1) * settings.SPEECHES_PER_PAGE)
lte = (page * settings.SPEECHES_PER_PAGE)
speech_parts = SpeechPart.objects.filter(speech__session=parliament_session)\
.filter(speech__ordernr__gt=gt, speech__ordernr__lte=lte)\
.order_by("speech__ordernr", "ordernr")\
.select_related("speech", "speech__speaker", "speech__speaker__party")
speeches = groupby(speech_parts, lambda sp: sp.speech)
new_speeches = []
for speech, it in speeches:
speech.speech_parts = list(it)
new_speeches.append(speech)
events = Event.objects.filter(context__id__in=[speech_part.id for speech_part in speech_parts])\
.select_related("context", "actor_politician", "actor_party")
events = groupby(events, lambda e: e.context.id)
new_events = {}
for k,v in events:
new_events[k] = list(v)
return render_to_response("bundestag/show.html", RequestContext(request, {"session" : parliament_session,
"speech_parts": speech_parts,
"speeches": new_speeches,
"events": new_events,
"paginator": paginator,
"page_obj":page_obj,
# "sessiontops":sessiontops
"all_speeches": all_speeches
}))
<|code_end|>
. Write the next line using the current file imports:
import re
from django.shortcuts import render_to_response, get_object_or_404, redirect
from django.http import HttpResponse, Http404, HttpResponseBadRequest, HttpResponseForbidden, HttpResponseNotAllowed
from django.template import RequestContext
from django.utils.itercompat import groupby
from django.core.paginator import Paginator, EmptyPage, InvalidPage
from django.conf import settings
from django.db.models import Q
from improvetext.models import Improvement
from models import ParliamentSession, Speech, SpeechPart, Event, Politician
from forms import EditSpeechPartForm
from bundestagger.account.auth import logged_in
from bundestagger.helper.utils import invalidate_cache, is_post, is_get
and context from other files:
# Path: bundestagger/account/auth.py
# def logged_in(func):
# def loggedin_func(*args, **kwargs):
# request = args[0]
# if "bundesuser" in request.session:
# request.bundesuser = request.session["bundesuser"]
# return func(*args, **kwargs)
# raise PermissionDenied
# return loggedin_func
#
# Path: bundestagger/helper/utils.py
# def invalidate_cache(path, *args):
# page = None
# if len(args)==2:
# index, max_per_page = args
# page = get_page(index, max_per_page)
# if page is not None and page != 1:
# request = FakeRequest(path, {"page": page})
# else:
# request = FakeRequest(path)
# cache.delete(get_cache_key(request))
#
# def is_post(func):
# return is_method("POST", func)
#
# def is_get(func):
# return is_method("GET", func)
, which may include functions, classes, or code. Output only the next line. | @is_post |
Based on the snippet: <|code_start|> if i % 1000 == 0:
print "%d/%d" % (i, count)
# if i>2000: break
i+=1
key = key_function(result)
aggregated.setdefault(key,0)
aggregated[key]+=1
sorted_aggregation = sorted(aggregated, key=lambda x: aggregated[x], reverse=True)
firsttop = [(key,aggregated[key]) for key in sorted_aggregation[:top]]
sorted_aggregation = sorted_aggregation[top:]
sorted_aggregation = sum(map(lambda x: aggregated[x], sorted_aggregation))
pp.pprint(firsttop)
print "Rest: %d" % sorted_aggregation
if not self.id:
self.save()
rank=0
for key,val in firsttop:
rank+=1
if "party" in key.__class__.__name__.lower():
FeatureRank.objects.create(feature=self, rank=rank, value=val, party=key)
else:
FeatureRank.objects.create(feature=self, rank=rank, value=val, politician=key)
FeatureRank.objects.create(feature=self, value=sorted_aggregation, label="Rest")
class FeatureRank(models.Model):
feature = models.ForeignKey(Feature)
rank = models.IntegerField(blank=True, null=True)
value = models.IntegerField()
<|code_end|>
, predict the immediate next line with the help of imports:
from django.db import models
from django.db.models import Q
from bundestagger.bundestag.models import Politician, Party, Event
import pickle
import marshal, types
import pprint
and context (classes, functions, sometimes code) from other files:
# Path: bundestagger/bundestag/models.py
# class Politician(models.Model):
# first_name = models.CharField(blank=True, max_length=100)
# last_name_prefix = models.CharField(blank=True, max_length=100)
# last_name = models.CharField(blank=True, max_length=100)
# title = models.CharField(blank=True, max_length=100)
# party = models.ForeignKey(Party, blank=True, null=True)
# # party_member = models.OneToOneField(PartyMember, blank=True, null=True)
# location = models.CharField(null=True, blank=True, max_length=255)
# born = models.DateField(null=True, blank=True)
#
# objects = PoliticianManager()
#
# def __unicode__(self):
# if self.party_id is not None:
# party = Party.objects.get(id=self.party_id)
# return u"%s (%s)" % (self.name, party)
# else:
# return u"%s (unbekannt)" % (self.name)
#
# @property
# def slug(self):
# return slugify(self.name)
#
# def get_absolute_url(self):
# return reverse("bundestagger-bundestag-show_politician", args=(self.slug, self.id))
#
# @property
# def name(self):
# if len(self.title):
# title = self.title + u" "
# else:
# title= u""
# if len(self.first_name):
# first_name = self.first_name + u" "
# else:
# first_name = u""
# if len(self.last_name_prefix):
# last_name_prefix = self.last_name_prefix + u" "
# else:
# last_name_prefix = u""
# return "%s%s%s%s" % (title, first_name, last_name_prefix,self.last_name)
#
# def all_relations(self):
# relations = [x for x in dir(self) if x.endswith("_set")]
# result = []
# for relation in relations:
# result.extend(getattr(self, relation).all())
# return result
#
# def replace_with(self, real_politician):
# relations = [x for x in dir(self) if x.endswith("_set")]
# for relation in relations:
# relset = getattr(self, relation).all()
# if len(relset) > 0:
# politician_fields = []
# for obj in relset:
# fields = obj.__class__._meta.fields
# for field in fields:
# try:
# if field.rel.to.__name__ == self.__class__.__name__:
# politician_fields.append(field.name)
# except AttributeError:
# pass
# if len(politician_fields)>0:
# for pf in politician_fields:
# if getattr(obj, pf) == self:
# setattr(obj, pf, real_politician)
# obj.save()
#
# class Party(models.Model):
# name = models.CharField(blank=True, max_length=100)
# abbr = models.CharField(blank=True, max_length=30)
#
# objects = PartyManager()
#
# color_mapping = {
# 1 : "#000000",
# 2 : "#F1AB00",
# 3 : "#D71F1D",
# 4 : "#BE3075",
# 5 : "#78BC1B",
# 6 : "#999999"
# }
#
# def __unicode__(self):
# return self.abbr
#
# @property
# def color(self):
# return self.color_mapping[self.id]
#
# class Event(models.Model):
# # Zwischenruf, Buhruf, Heiterkeit, Beifall
# context = models.ForeignKey(SpeechPart, null=True, blank=True)
# kind = models.CharField(blank=True, max_length=100)
# actor_politician = models.ForeignKey(Politician, null=True, blank=True)
# actor_party = models.ForeignKey(Party, null=True, blank=True)
# text = models.TextField(blank=True, null=True)
#
# def __unicode__(self):
# return u"%s: %s (%s - %s @ %s)" % (self.kind, self.actor, self.text, self.id, self.context_id)
#
# @property
# def actor(self):
# if self.actor_politician is not None:
# return self.actor_politician
# else:
# return self.actor_party
#
# def display(self):
# out = u""
# try:
# if self.kind != "":
# out+=u"[%s] " % self.kind
# if self.actor is not None:
# out+=u"%s" % self.actor
# if self.text is not None and len(self.text)>0:
# if self.actor is not None or self.kind !="":
# out+=": "
# out+=self.text
# except Exception,e:
# return e
# return out
. Output only the next line. | politician = models.ForeignKey(Politician, null=True, blank=True) |
Using the snippet: <|code_start|> print "%d/%d" % (i, count)
# if i>2000: break
i+=1
key = key_function(result)
aggregated.setdefault(key,0)
aggregated[key]+=1
sorted_aggregation = sorted(aggregated, key=lambda x: aggregated[x], reverse=True)
firsttop = [(key,aggregated[key]) for key in sorted_aggregation[:top]]
sorted_aggregation = sorted_aggregation[top:]
sorted_aggregation = sum(map(lambda x: aggregated[x], sorted_aggregation))
pp.pprint(firsttop)
print "Rest: %d" % sorted_aggregation
if not self.id:
self.save()
rank=0
for key,val in firsttop:
rank+=1
if "party" in key.__class__.__name__.lower():
FeatureRank.objects.create(feature=self, rank=rank, value=val, party=key)
else:
FeatureRank.objects.create(feature=self, rank=rank, value=val, politician=key)
FeatureRank.objects.create(feature=self, value=sorted_aggregation, label="Rest")
class FeatureRank(models.Model):
feature = models.ForeignKey(Feature)
rank = models.IntegerField(blank=True, null=True)
value = models.IntegerField()
politician = models.ForeignKey(Politician, null=True, blank=True)
<|code_end|>
, determine the next line of code. You have imports:
from django.db import models
from django.db.models import Q
from bundestagger.bundestag.models import Politician, Party, Event
import pickle
import marshal, types
import pprint
and context (class names, function names, or code) available:
# Path: bundestagger/bundestag/models.py
# class Politician(models.Model):
# first_name = models.CharField(blank=True, max_length=100)
# last_name_prefix = models.CharField(blank=True, max_length=100)
# last_name = models.CharField(blank=True, max_length=100)
# title = models.CharField(blank=True, max_length=100)
# party = models.ForeignKey(Party, blank=True, null=True)
# # party_member = models.OneToOneField(PartyMember, blank=True, null=True)
# location = models.CharField(null=True, blank=True, max_length=255)
# born = models.DateField(null=True, blank=True)
#
# objects = PoliticianManager()
#
# def __unicode__(self):
# if self.party_id is not None:
# party = Party.objects.get(id=self.party_id)
# return u"%s (%s)" % (self.name, party)
# else:
# return u"%s (unbekannt)" % (self.name)
#
# @property
# def slug(self):
# return slugify(self.name)
#
# def get_absolute_url(self):
# return reverse("bundestagger-bundestag-show_politician", args=(self.slug, self.id))
#
# @property
# def name(self):
# if len(self.title):
# title = self.title + u" "
# else:
# title= u""
# if len(self.first_name):
# first_name = self.first_name + u" "
# else:
# first_name = u""
# if len(self.last_name_prefix):
# last_name_prefix = self.last_name_prefix + u" "
# else:
# last_name_prefix = u""
# return "%s%s%s%s" % (title, first_name, last_name_prefix,self.last_name)
#
# def all_relations(self):
# relations = [x for x in dir(self) if x.endswith("_set")]
# result = []
# for relation in relations:
# result.extend(getattr(self, relation).all())
# return result
#
# def replace_with(self, real_politician):
# relations = [x for x in dir(self) if x.endswith("_set")]
# for relation in relations:
# relset = getattr(self, relation).all()
# if len(relset) > 0:
# politician_fields = []
# for obj in relset:
# fields = obj.__class__._meta.fields
# for field in fields:
# try:
# if field.rel.to.__name__ == self.__class__.__name__:
# politician_fields.append(field.name)
# except AttributeError:
# pass
# if len(politician_fields)>0:
# for pf in politician_fields:
# if getattr(obj, pf) == self:
# setattr(obj, pf, real_politician)
# obj.save()
#
# class Party(models.Model):
# name = models.CharField(blank=True, max_length=100)
# abbr = models.CharField(blank=True, max_length=30)
#
# objects = PartyManager()
#
# color_mapping = {
# 1 : "#000000",
# 2 : "#F1AB00",
# 3 : "#D71F1D",
# 4 : "#BE3075",
# 5 : "#78BC1B",
# 6 : "#999999"
# }
#
# def __unicode__(self):
# return self.abbr
#
# @property
# def color(self):
# return self.color_mapping[self.id]
#
# class Event(models.Model):
# # Zwischenruf, Buhruf, Heiterkeit, Beifall
# context = models.ForeignKey(SpeechPart, null=True, blank=True)
# kind = models.CharField(blank=True, max_length=100)
# actor_politician = models.ForeignKey(Politician, null=True, blank=True)
# actor_party = models.ForeignKey(Party, null=True, blank=True)
# text = models.TextField(blank=True, null=True)
#
# def __unicode__(self):
# return u"%s: %s (%s - %s @ %s)" % (self.kind, self.actor, self.text, self.id, self.context_id)
#
# @property
# def actor(self):
# if self.actor_politician is not None:
# return self.actor_politician
# else:
# return self.actor_party
#
# def display(self):
# out = u""
# try:
# if self.kind != "":
# out+=u"[%s] " % self.kind
# if self.actor is not None:
# out+=u"%s" % self.actor
# if self.text is not None and len(self.text)>0:
# if self.actor is not None or self.kind !="":
# out+=": "
# out+=self.text
# except Exception,e:
# return e
# return out
. Output only the next line. | party = models.ForeignKey(Party, null=True, blank=True) |
Predict the next line for this snippet: <|code_start|>
urlpatterns = patterns('',
url(r'^add/(?P<content_type>\d+)/(?P<object_id>\d+)/$', add_tags, name='tagging_add-tags'),
url(r'^autocomplete/$', autocomplete, name='tagging_autocomplete'),
)
urlpatterns += patterns('',
<|code_end|>
with the help of current file imports:
from django.conf.urls.defaults import *
from bundestagger.bundestagging.views import add_tags, autocomplete
from bundestagger.bundestag.models import Speech
and context from other files:
# Path: bundestagger/bundestagging/views.py
# def add_tags(request, content_type=None, object_id=None, ajax=False):
# if request.method=="POST":
# content_type = get_object_or_404(ContentType, id = int(content_type))
# tagged_object = content_type.get_object_for_this_type(id = int(object_id))
# if not hasattr(tagged_object,"tags"):
# return HttpResponseBadRequest()
# li = tagged_object.tags.split(",")
# s = set([l.strip() for l in li if len(l.strip())>0])
# new_tags = parse_tag_input(request.POST["tags"])
# s.update(new_tags)
# tagged_object.tags = ",".join(s)
# tagged_object.save()
# tagged_object.clear_cache()
# if request.is_ajax():
# t = loader.get_template("tagging/_tag_list.html")
# return HttpResponse(t.render(RequestContext(request, {"tags": new_tags})))
#
# else:
# next = "/"
# if "next" in request.POST:
# next = request.POST["next"]
# else:
# next = tagged_object.get_absolute_url()
# return HttpResponseRedirect(next)
#
# def autocomplete(request):
# q = request.GET.get("q","")
# try:
# limit = int(request.GET.get("limit",10))
# except TypeError:
# limit = 10
# return HttpResponse("\n".join(map(lambda x:x.name,Tag.objects.filter(name__istartswith=q)[:limit])),mimetype="text/plain")
#
# Path: bundestagger/bundestag/models.py
# class Speech(models.Model):
# session = models.ForeignKey(ParliamentSession)
# ordernr = models.IntegerField()
# speaker = models.ForeignKey(Politician)
# start = models.DateTimeField(blank=True, default=None, null=True)
# end = models.DateTimeField(blank=True, default=None, null=True)
# webtv = models.IntegerField(blank=True, null=True)
#
# tags = TagField(blank=True)
#
# def save(self, *args, **kwargs):
# super(Speech,self).save(*args, **kwargs)
# self.session.update_tags(self.tags)
#
#
# def __unicode__(self):
# return u"Rede von %s in der %s" % (self.speaker, self.session)
#
# def text(self):
# return u"\n".join(map(lambda x:x.text, self.speechpart_set.order_by("ordernr")))
#
# @property
# def tag_list(self):
# return [tag.strip() for tag in self.tags.split(",") if len(tag.strip())>0]
#
# @property
# def webtv_url(self):
# if self.webtv is not None:
# return u"http://webtv.bundestag.de/iptv/player/macros/_v_f_514_de/od_player.html?singleton=true&content=%d" % (self.webtv,)
# return u""
#
# @property
# def webtv_search(self):
# url = u"http://webtv.bundestag.de/iptv/player/macros/bttv/list.html?pageOffset=0&pageLength=40&sort=2&lastName=%(lastname)s&firstName=%(firstname)s&fraction=&meetingNumber=%(session)s&period=%(period)s&startDay=&endDay=&topic=&submit=Suchen"
# return url % { "firstname": self.speaker.first_name,
# "lastname": self.speaker.last_name,
# "session": self.session.number,
# "period": self.session.parliament.number
# }
#
# def get_base_url(self):
# return reverse("bundestagger-bundestag-show_session", args=(self.session.parliament.number, self.session.number))
#
# def get_absolute_url(self):
# page = get_page(self.ordernr, settings.SPEECHES_PER_PAGE)
# if page == 1:
# page = ""
# else:
# page = "?page=%d" % page
# fragment = "#speech-%d" % self.id
# return self.get_base_url() + page + fragment
#
# def clear_cache(self):
# url = self.get_base_url()
# invalidate_cache(url, self.ordernr, settings.SPEECHES_PER_PAGE)
, which may contain function names, class names, or code. Output only the next line. | ('^(?P<tag>[^/]+)$', 'tagging.views.tagged_object_list', {'queryset_or_model': Speech, 'template_name': "bundestagging/tag.html"}, 'tagging-tag_url'), |
Given the code snippet: <|code_start|>
for pyfile in py_files:
if 'mysql/__init__.py' in pyfile:
continue
os.unlink(pyfile)
if LICENSE == 'Commercial':
util.byte_compile = _byte_compile
# Development Status Trove Classifiers significant for Connector/Python
DEVELOPMENT_STATUSES = {
'a': '3 - Alpha',
'b': '4 - Beta',
'': '5 - Production/Stable'
}
if sys.version_info >= (3, 1):
sys.path = ['python3/'] + sys.path
package_dir = { '': 'python3' }
elif sys.version_info >= (2, 6) and sys.version_info < (3, 0):
sys.path = ['python2/'] + sys.path
package_dir = { '': 'python2' }
else:
raise RuntimeError(
"Python v%d.%d is not supported" % sys.version_info[0:2])
package_dir['mysql.connector.django'] = os.path.join('python23', 'django')
package_dir['mysql.connector.fabric'] = os.path.join('python23', 'fabric')
name = 'mysql-connector-python'
<|code_end|>
, generate the next line using the imports in this file:
import sys
import os
from distutils.sysconfig import get_python_lib
from distutils.file_util import copy_file
from distutils.dir_util import mkpath, copy_tree
from distutils.errors import DistutilsError
from distutils import util
from version import VERSION, LICENSE
from support.distribution.commands import (
sdist, bdist, dist_rpm, build, dist_deb, dist_osx
)
from distutils import dir_util
from support.distribution.commands import (dist_msi)
and context (functions, classes, or occasionally code) from other files:
# Path: version.py
# VERSION = (1, 2, 0, 'a', 1)
#
# LICENSE = 'GPLv2 with FOSS License Exception'
. Output only the next line. | version = '{0}.{1}.{2}'.format(*VERSION[0:3]) |
Next line prediction: <|code_start|> for base, dirs, files in os.walk(django_dir):
for file_ in files:
if file_.endswith('.py'):
pyfile = os.path.join(base, file_)
if os.path.getsize(pyfile) > 10:
self._check_copyright_absence(pyfile)
self._check_gpl_absence(pyfile)
class DebianTests(support.tests.SupportTests):
"""Test Debian packaging"""
def test_changelog_version(self):
ver = self.get_connector_version(no_suffix=True)
debian_folders = ['commercial', 'gpl']
for debian_folder in debian_folders:
changelog = os.path.join('support', 'Debian', debian_folder,
'changelog')
content = open(changelog, 'r').read()
self.assertTrue(ver in content,
"Version %s not found in %s" % (ver, changelog))
class CommercialTests(support.tests.SupportTests):
"""Test functionality regarding commercial releases"""
def test_remove_gpl(self):
pyfile = 'python2/mysql/connector/connection.py'
# Succesfully remove GPL
tmpfile = tempfile.NamedTemporaryFile(mode='w+')
tmpfile.write(open(pyfile, 'r').read())
<|code_end|>
. Use current file imports:
(import os
import time
import re
import tempfile
import filecmp
import difflib
import support.tests
from datetime import datetime
from distutils.errors import DistutilsError
from support.distribution import commercial)
and context including class names, function names, or small code snippets from other files:
# Path: support/distribution/commercial.py
# GPL_NOTICE_LINENR = 19
# COMMERCIAL_LICENSE_NOTICE = """
# This is a release of MySQL Connector/Python, Oracle's dual-
# license Python Driver for MySQL. For the avoidance of
# doubt, this particular copy of the software is released
# under a commercial license and the GNU General Public
# License does not apply. MySQL Connector/Python is brought
# to you by Oracle.
#
# Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
#
# This distribution may include materials developed by third
# parties. For license and attribution notices for these
# materials, please refer to the documentation that accompanies
# this distribution (see the "Licenses for Third-Party Components"
# appendix) or view the online documentation at
# <http://dev.mysql.com/doc/>
# """
# COMMERCIAL_SETUP_PY = """#!/usr/bin/env python
# # -*- coding: utf-8 -*-
# # MySQL Connector/Python - MySQL driver written in Python.
# # Copyright (c) 2012, %d, Oracle and/or its affiliates. All rights reserved.
#
# import os
# from distutils.core import setup
# from distutils.command.build import build
# from distutils.dir_util import copy_tree
#
# class Build(build):
# def run(self):
# copy_tree('mysql', os.path.join(self.build_lib, 'mysql'))
#
# LONG_DESCRIPTION = \"\"\"
# {long_description}
# \"\"\"
#
# setup(
# name = '{name}',
# version = '{version}',
# description = '{description}',
# long_description = LONG_DESCRIPTION,
# author = '{author}',
# author_email = '{author_email}',
# license = '{license}',
# keywords = '{keywords}',
# url = '{url}',
# download_url = '{download_url}',
# package_dir = {{ '': '' }},
# packages = ['mysql', 'mysql.connector',
# 'mysql.connector.locales', 'mysql.connector.locales.eng'],
# classifiers = {classifiers},
# cmdclass = {{
# 'build': Build,
# }}
# )
#
# """ % (date.today().year)
# def remove_gpl(pyfile, dry_run=0):
. Output only the next line. | commercial.remove_gpl(tmpfile.name) |
Given snippet: <|code_start|> raise ValueError("Failed reading server error message")
def _serverr_get_translations(self):
"""Create a dictionary of server codes with translations
This method will return a dictionary where the key is the server
error code and value another dictionary containing the error message
in all available languages.
Example output:
{ 1003: {
'eng': "NO",
'ger': "Nein",
'kor': "아니오"',
...
}
}
String values are unicode.
Returns a dictionary.
"""
result = {}
for err_name, err in self._errors.items():
result[err['code']] = err['messages']
return result
def _write_header(self, fp):
fp.write("# -*- coding: utf-8 -*-\n\n")
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import sys
import os
import re
import codecs
import datetime
import logging
import argparse
from collections import OrderedDict
from pprint import pprint, pformat
from support.distribution import opensource
and context:
# Path: support/distribution/opensource.py
# GPLGNU2_LICENSE_NOTICE = \
# """MySQL Connector/Python - MySQL driver written in Python.
# Copyright (c) {year}, Oracle and/or its affiliates. All rights reserved.
#
# MySQL Connector/Python is licensed under the terms of the GPLv2
# <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most
# MySQL Connectors. There are special exceptions to the terms and
# conditions of the GPLv2 as it is applied to this software, see the
# FOSS License Exception
# <http://www.mysql.com/about/legal/licensing/foss-exception.html>.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """
which might include code, classes, or functions. Output only the next line. | license = opensource.GPLGNU2_LICENSE_NOTICE.format( |
Predict the next line for this snippet: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in 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 Client(object):
def __init__(self, session=None, service_type='rca', **kwargs):
logger = logging.getLogger(__name__)
<|code_end|>
with the help of current file imports:
import logging
from vitrageclient import client
from vitrageclient.v1 import alarm
from vitrageclient.v1 import event
from vitrageclient.v1 import healthcheck
from vitrageclient.v1 import rca
from vitrageclient.v1 import resource
from vitrageclient.v1 import service
from vitrageclient.v1 import status
from vitrageclient.v1 import template
from vitrageclient.v1 import topology
from vitrageclient.v1 import webhook
and context from other files:
# Path: vitrageclient/client.py
# def Client(version, *args, **kwargs):
# def request(self, url, method, **kwargs):
# class VitrageClient(keystoneauth.Adapter):
#
# Path: vitrageclient/v1/alarm.py
# class Alarm(object):
# def __init__(self, api):
# def list(self, vitrage_id, all_tenants=False,
# limit=1000,
# sort_by=['start_timestamp', 'vitrage_id'],
# sort_dirs=['asc', 'asc'],
# filter_by=None,
# filter_vals=None,
# next_page=True,
# marker=None):
# def history(self, all_tenants=False,
# start=None,
# end=None,
# limit=1000,
# sort_by=('start_timestamp', 'vitrage_id'),
# sort_dirs=('asc', 'asc'),
# filter_by=None,
# filter_vals=None,
# next_page=True,
# marker=None):
# def get(self, vitrage_id):
# def count(self, all_tenants=False):
#
# Path: vitrageclient/v1/event.py
# class Event(object):
# URL = 'v1/event/'
# def __init__(self, api):
# def post(self, event_time, event_type, details):
#
# Path: vitrageclient/v1/healthcheck.py
# class HealthCheck(object):
# URL = 'healthcheck/'
# STATUS_CODE_OK = 200
# def __init__(self, api):
# def get(self):
#
# Path: vitrageclient/v1/rca.py
# class Rca(object):
# def __init__(self, api):
# def get(self, alarm_id, all_tenants=False):
#
# Path: vitrageclient/v1/resource.py
# class Resource(object):
# def __init__(self, api):
# def list(self, resource_type=None, all_tenants=False, query=None):
# def get(self, vitrage_id):
# def count(self, resource_type=None, all_tenants=False, query=None,
# group_by=None):
#
# Path: vitrageclient/v1/service.py
# class Service(object):
# def __init__(self, api):
# def list(self):
#
# Path: vitrageclient/v1/status.py
# class Status(object):
# URL = 'v1/status/'
# def __init__(self, api):
# def get(self):
#
# Path: vitrageclient/v1/template.py
# class Template(object):
# def __init__(self, api):
# def list(self):
# def versions(self):
# def show(self, _id):
# def add(self, path=None, template_type=None,
# params=None, template_str=None, overwrite=False):
# def delete(self, ids):
# def validate(self, path=None, template_type=None,
# params=None, template_str=None):
# def _load_yaml_files(cls, path):
# def _load_yaml_file(cls, path):
# def _load_yaml(cls, yaml_content):
# def _load_template(cls, path, template_str):
#
# Path: vitrageclient/v1/topology.py
# class Topology(object):
# URL = 'v1/topology/'
# def __init__(self, api):
# def get(self,
# limit=None,
# graph_type='graph',
# query=None,
# root=None,
# all_tenants=False):
#
# Path: vitrageclient/v1/webhook.py
# class Webhook(object):
# def __init__(self, api):
# def list(self, all_tenants=False):
# def show(self, id):
# def add(self, url, regex_filter=None, headers=None):
# def delete(self, id):
, which may contain function names, class names, or code. Output only the next line. | self._api = client.VitrageClient(session, service_type=service_type, |
Based on the snippet: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in 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 Client(object):
def __init__(self, session=None, service_type='rca', **kwargs):
logger = logging.getLogger(__name__)
self._api = client.VitrageClient(session, service_type=service_type,
logger=logger, **kwargs)
self.topology = topology.Topology(self._api)
self.resource = resource.Resource(self._api)
<|code_end|>
, predict the immediate next line with the help of imports:
import logging
from vitrageclient import client
from vitrageclient.v1 import alarm
from vitrageclient.v1 import event
from vitrageclient.v1 import healthcheck
from vitrageclient.v1 import rca
from vitrageclient.v1 import resource
from vitrageclient.v1 import service
from vitrageclient.v1 import status
from vitrageclient.v1 import template
from vitrageclient.v1 import topology
from vitrageclient.v1 import webhook
and context (classes, functions, sometimes code) from other files:
# Path: vitrageclient/client.py
# def Client(version, *args, **kwargs):
# def request(self, url, method, **kwargs):
# class VitrageClient(keystoneauth.Adapter):
#
# Path: vitrageclient/v1/alarm.py
# class Alarm(object):
# def __init__(self, api):
# def list(self, vitrage_id, all_tenants=False,
# limit=1000,
# sort_by=['start_timestamp', 'vitrage_id'],
# sort_dirs=['asc', 'asc'],
# filter_by=None,
# filter_vals=None,
# next_page=True,
# marker=None):
# def history(self, all_tenants=False,
# start=None,
# end=None,
# limit=1000,
# sort_by=('start_timestamp', 'vitrage_id'),
# sort_dirs=('asc', 'asc'),
# filter_by=None,
# filter_vals=None,
# next_page=True,
# marker=None):
# def get(self, vitrage_id):
# def count(self, all_tenants=False):
#
# Path: vitrageclient/v1/event.py
# class Event(object):
# URL = 'v1/event/'
# def __init__(self, api):
# def post(self, event_time, event_type, details):
#
# Path: vitrageclient/v1/healthcheck.py
# class HealthCheck(object):
# URL = 'healthcheck/'
# STATUS_CODE_OK = 200
# def __init__(self, api):
# def get(self):
#
# Path: vitrageclient/v1/rca.py
# class Rca(object):
# def __init__(self, api):
# def get(self, alarm_id, all_tenants=False):
#
# Path: vitrageclient/v1/resource.py
# class Resource(object):
# def __init__(self, api):
# def list(self, resource_type=None, all_tenants=False, query=None):
# def get(self, vitrage_id):
# def count(self, resource_type=None, all_tenants=False, query=None,
# group_by=None):
#
# Path: vitrageclient/v1/service.py
# class Service(object):
# def __init__(self, api):
# def list(self):
#
# Path: vitrageclient/v1/status.py
# class Status(object):
# URL = 'v1/status/'
# def __init__(self, api):
# def get(self):
#
# Path: vitrageclient/v1/template.py
# class Template(object):
# def __init__(self, api):
# def list(self):
# def versions(self):
# def show(self, _id):
# def add(self, path=None, template_type=None,
# params=None, template_str=None, overwrite=False):
# def delete(self, ids):
# def validate(self, path=None, template_type=None,
# params=None, template_str=None):
# def _load_yaml_files(cls, path):
# def _load_yaml_file(cls, path):
# def _load_yaml(cls, yaml_content):
# def _load_template(cls, path, template_str):
#
# Path: vitrageclient/v1/topology.py
# class Topology(object):
# URL = 'v1/topology/'
# def __init__(self, api):
# def get(self,
# limit=None,
# graph_type='graph',
# query=None,
# root=None,
# all_tenants=False):
#
# Path: vitrageclient/v1/webhook.py
# class Webhook(object):
# def __init__(self, api):
# def list(self, all_tenants=False):
# def show(self, id):
# def add(self, url, regex_filter=None, headers=None):
# def delete(self, id):
. Output only the next line. | self.alarm = alarm.Alarm(self._api) |
Using the snippet: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in 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 Client(object):
def __init__(self, session=None, service_type='rca', **kwargs):
logger = logging.getLogger(__name__)
self._api = client.VitrageClient(session, service_type=service_type,
logger=logger, **kwargs)
self.topology = topology.Topology(self._api)
self.resource = resource.Resource(self._api)
self.alarm = alarm.Alarm(self._api)
self.rca = rca.Rca(self._api)
self.template = template.Template(self._api)
<|code_end|>
, determine the next line of code. You have imports:
import logging
from vitrageclient import client
from vitrageclient.v1 import alarm
from vitrageclient.v1 import event
from vitrageclient.v1 import healthcheck
from vitrageclient.v1 import rca
from vitrageclient.v1 import resource
from vitrageclient.v1 import service
from vitrageclient.v1 import status
from vitrageclient.v1 import template
from vitrageclient.v1 import topology
from vitrageclient.v1 import webhook
and context (class names, function names, or code) available:
# Path: vitrageclient/client.py
# def Client(version, *args, **kwargs):
# def request(self, url, method, **kwargs):
# class VitrageClient(keystoneauth.Adapter):
#
# Path: vitrageclient/v1/alarm.py
# class Alarm(object):
# def __init__(self, api):
# def list(self, vitrage_id, all_tenants=False,
# limit=1000,
# sort_by=['start_timestamp', 'vitrage_id'],
# sort_dirs=['asc', 'asc'],
# filter_by=None,
# filter_vals=None,
# next_page=True,
# marker=None):
# def history(self, all_tenants=False,
# start=None,
# end=None,
# limit=1000,
# sort_by=('start_timestamp', 'vitrage_id'),
# sort_dirs=('asc', 'asc'),
# filter_by=None,
# filter_vals=None,
# next_page=True,
# marker=None):
# def get(self, vitrage_id):
# def count(self, all_tenants=False):
#
# Path: vitrageclient/v1/event.py
# class Event(object):
# URL = 'v1/event/'
# def __init__(self, api):
# def post(self, event_time, event_type, details):
#
# Path: vitrageclient/v1/healthcheck.py
# class HealthCheck(object):
# URL = 'healthcheck/'
# STATUS_CODE_OK = 200
# def __init__(self, api):
# def get(self):
#
# Path: vitrageclient/v1/rca.py
# class Rca(object):
# def __init__(self, api):
# def get(self, alarm_id, all_tenants=False):
#
# Path: vitrageclient/v1/resource.py
# class Resource(object):
# def __init__(self, api):
# def list(self, resource_type=None, all_tenants=False, query=None):
# def get(self, vitrage_id):
# def count(self, resource_type=None, all_tenants=False, query=None,
# group_by=None):
#
# Path: vitrageclient/v1/service.py
# class Service(object):
# def __init__(self, api):
# def list(self):
#
# Path: vitrageclient/v1/status.py
# class Status(object):
# URL = 'v1/status/'
# def __init__(self, api):
# def get(self):
#
# Path: vitrageclient/v1/template.py
# class Template(object):
# def __init__(self, api):
# def list(self):
# def versions(self):
# def show(self, _id):
# def add(self, path=None, template_type=None,
# params=None, template_str=None, overwrite=False):
# def delete(self, ids):
# def validate(self, path=None, template_type=None,
# params=None, template_str=None):
# def _load_yaml_files(cls, path):
# def _load_yaml_file(cls, path):
# def _load_yaml(cls, yaml_content):
# def _load_template(cls, path, template_str):
#
# Path: vitrageclient/v1/topology.py
# class Topology(object):
# URL = 'v1/topology/'
# def __init__(self, api):
# def get(self,
# limit=None,
# graph_type='graph',
# query=None,
# root=None,
# all_tenants=False):
#
# Path: vitrageclient/v1/webhook.py
# class Webhook(object):
# def __init__(self, api):
# def list(self, all_tenants=False):
# def show(self, id):
# def add(self, url, regex_filter=None, headers=None):
# def delete(self, id):
. Output only the next line. | self.event = event.Event(self._api) |
Given the code snippet: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in 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 Client(object):
def __init__(self, session=None, service_type='rca', **kwargs):
logger = logging.getLogger(__name__)
self._api = client.VitrageClient(session, service_type=service_type,
logger=logger, **kwargs)
self.topology = topology.Topology(self._api)
self.resource = resource.Resource(self._api)
self.alarm = alarm.Alarm(self._api)
self.rca = rca.Rca(self._api)
self.template = template.Template(self._api)
self.event = event.Event(self._api)
<|code_end|>
, generate the next line using the imports in this file:
import logging
from vitrageclient import client
from vitrageclient.v1 import alarm
from vitrageclient.v1 import event
from vitrageclient.v1 import healthcheck
from vitrageclient.v1 import rca
from vitrageclient.v1 import resource
from vitrageclient.v1 import service
from vitrageclient.v1 import status
from vitrageclient.v1 import template
from vitrageclient.v1 import topology
from vitrageclient.v1 import webhook
and context (functions, classes, or occasionally code) from other files:
# Path: vitrageclient/client.py
# def Client(version, *args, **kwargs):
# def request(self, url, method, **kwargs):
# class VitrageClient(keystoneauth.Adapter):
#
# Path: vitrageclient/v1/alarm.py
# class Alarm(object):
# def __init__(self, api):
# def list(self, vitrage_id, all_tenants=False,
# limit=1000,
# sort_by=['start_timestamp', 'vitrage_id'],
# sort_dirs=['asc', 'asc'],
# filter_by=None,
# filter_vals=None,
# next_page=True,
# marker=None):
# def history(self, all_tenants=False,
# start=None,
# end=None,
# limit=1000,
# sort_by=('start_timestamp', 'vitrage_id'),
# sort_dirs=('asc', 'asc'),
# filter_by=None,
# filter_vals=None,
# next_page=True,
# marker=None):
# def get(self, vitrage_id):
# def count(self, all_tenants=False):
#
# Path: vitrageclient/v1/event.py
# class Event(object):
# URL = 'v1/event/'
# def __init__(self, api):
# def post(self, event_time, event_type, details):
#
# Path: vitrageclient/v1/healthcheck.py
# class HealthCheck(object):
# URL = 'healthcheck/'
# STATUS_CODE_OK = 200
# def __init__(self, api):
# def get(self):
#
# Path: vitrageclient/v1/rca.py
# class Rca(object):
# def __init__(self, api):
# def get(self, alarm_id, all_tenants=False):
#
# Path: vitrageclient/v1/resource.py
# class Resource(object):
# def __init__(self, api):
# def list(self, resource_type=None, all_tenants=False, query=None):
# def get(self, vitrage_id):
# def count(self, resource_type=None, all_tenants=False, query=None,
# group_by=None):
#
# Path: vitrageclient/v1/service.py
# class Service(object):
# def __init__(self, api):
# def list(self):
#
# Path: vitrageclient/v1/status.py
# class Status(object):
# URL = 'v1/status/'
# def __init__(self, api):
# def get(self):
#
# Path: vitrageclient/v1/template.py
# class Template(object):
# def __init__(self, api):
# def list(self):
# def versions(self):
# def show(self, _id):
# def add(self, path=None, template_type=None,
# params=None, template_str=None, overwrite=False):
# def delete(self, ids):
# def validate(self, path=None, template_type=None,
# params=None, template_str=None):
# def _load_yaml_files(cls, path):
# def _load_yaml_file(cls, path):
# def _load_yaml(cls, yaml_content):
# def _load_template(cls, path, template_str):
#
# Path: vitrageclient/v1/topology.py
# class Topology(object):
# URL = 'v1/topology/'
# def __init__(self, api):
# def get(self,
# limit=None,
# graph_type='graph',
# query=None,
# root=None,
# all_tenants=False):
#
# Path: vitrageclient/v1/webhook.py
# class Webhook(object):
# def __init__(self, api):
# def list(self, all_tenants=False):
# def show(self, id):
# def add(self, url, regex_filter=None, headers=None):
# def delete(self, id):
. Output only the next line. | self.healthcheck = healthcheck.HealthCheck(self._api) |
Next line prediction: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in 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 Client(object):
def __init__(self, session=None, service_type='rca', **kwargs):
logger = logging.getLogger(__name__)
self._api = client.VitrageClient(session, service_type=service_type,
logger=logger, **kwargs)
self.topology = topology.Topology(self._api)
self.resource = resource.Resource(self._api)
self.alarm = alarm.Alarm(self._api)
<|code_end|>
. Use current file imports:
(import logging
from vitrageclient import client
from vitrageclient.v1 import alarm
from vitrageclient.v1 import event
from vitrageclient.v1 import healthcheck
from vitrageclient.v1 import rca
from vitrageclient.v1 import resource
from vitrageclient.v1 import service
from vitrageclient.v1 import status
from vitrageclient.v1 import template
from vitrageclient.v1 import topology
from vitrageclient.v1 import webhook)
and context including class names, function names, or small code snippets from other files:
# Path: vitrageclient/client.py
# def Client(version, *args, **kwargs):
# def request(self, url, method, **kwargs):
# class VitrageClient(keystoneauth.Adapter):
#
# Path: vitrageclient/v1/alarm.py
# class Alarm(object):
# def __init__(self, api):
# def list(self, vitrage_id, all_tenants=False,
# limit=1000,
# sort_by=['start_timestamp', 'vitrage_id'],
# sort_dirs=['asc', 'asc'],
# filter_by=None,
# filter_vals=None,
# next_page=True,
# marker=None):
# def history(self, all_tenants=False,
# start=None,
# end=None,
# limit=1000,
# sort_by=('start_timestamp', 'vitrage_id'),
# sort_dirs=('asc', 'asc'),
# filter_by=None,
# filter_vals=None,
# next_page=True,
# marker=None):
# def get(self, vitrage_id):
# def count(self, all_tenants=False):
#
# Path: vitrageclient/v1/event.py
# class Event(object):
# URL = 'v1/event/'
# def __init__(self, api):
# def post(self, event_time, event_type, details):
#
# Path: vitrageclient/v1/healthcheck.py
# class HealthCheck(object):
# URL = 'healthcheck/'
# STATUS_CODE_OK = 200
# def __init__(self, api):
# def get(self):
#
# Path: vitrageclient/v1/rca.py
# class Rca(object):
# def __init__(self, api):
# def get(self, alarm_id, all_tenants=False):
#
# Path: vitrageclient/v1/resource.py
# class Resource(object):
# def __init__(self, api):
# def list(self, resource_type=None, all_tenants=False, query=None):
# def get(self, vitrage_id):
# def count(self, resource_type=None, all_tenants=False, query=None,
# group_by=None):
#
# Path: vitrageclient/v1/service.py
# class Service(object):
# def __init__(self, api):
# def list(self):
#
# Path: vitrageclient/v1/status.py
# class Status(object):
# URL = 'v1/status/'
# def __init__(self, api):
# def get(self):
#
# Path: vitrageclient/v1/template.py
# class Template(object):
# def __init__(self, api):
# def list(self):
# def versions(self):
# def show(self, _id):
# def add(self, path=None, template_type=None,
# params=None, template_str=None, overwrite=False):
# def delete(self, ids):
# def validate(self, path=None, template_type=None,
# params=None, template_str=None):
# def _load_yaml_files(cls, path):
# def _load_yaml_file(cls, path):
# def _load_yaml(cls, yaml_content):
# def _load_template(cls, path, template_str):
#
# Path: vitrageclient/v1/topology.py
# class Topology(object):
# URL = 'v1/topology/'
# def __init__(self, api):
# def get(self,
# limit=None,
# graph_type='graph',
# query=None,
# root=None,
# all_tenants=False):
#
# Path: vitrageclient/v1/webhook.py
# class Webhook(object):
# def __init__(self, api):
# def list(self, all_tenants=False):
# def show(self, id):
# def add(self, url, regex_filter=None, headers=None):
# def delete(self, id):
. Output only the next line. | self.rca = rca.Rca(self._api) |
Given the following code snippet before the placeholder: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in 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 Client(object):
def __init__(self, session=None, service_type='rca', **kwargs):
logger = logging.getLogger(__name__)
self._api = client.VitrageClient(session, service_type=service_type,
logger=logger, **kwargs)
self.topology = topology.Topology(self._api)
<|code_end|>
, predict the next line using imports from the current file:
import logging
from vitrageclient import client
from vitrageclient.v1 import alarm
from vitrageclient.v1 import event
from vitrageclient.v1 import healthcheck
from vitrageclient.v1 import rca
from vitrageclient.v1 import resource
from vitrageclient.v1 import service
from vitrageclient.v1 import status
from vitrageclient.v1 import template
from vitrageclient.v1 import topology
from vitrageclient.v1 import webhook
and context including class names, function names, and sometimes code from other files:
# Path: vitrageclient/client.py
# def Client(version, *args, **kwargs):
# def request(self, url, method, **kwargs):
# class VitrageClient(keystoneauth.Adapter):
#
# Path: vitrageclient/v1/alarm.py
# class Alarm(object):
# def __init__(self, api):
# def list(self, vitrage_id, all_tenants=False,
# limit=1000,
# sort_by=['start_timestamp', 'vitrage_id'],
# sort_dirs=['asc', 'asc'],
# filter_by=None,
# filter_vals=None,
# next_page=True,
# marker=None):
# def history(self, all_tenants=False,
# start=None,
# end=None,
# limit=1000,
# sort_by=('start_timestamp', 'vitrage_id'),
# sort_dirs=('asc', 'asc'),
# filter_by=None,
# filter_vals=None,
# next_page=True,
# marker=None):
# def get(self, vitrage_id):
# def count(self, all_tenants=False):
#
# Path: vitrageclient/v1/event.py
# class Event(object):
# URL = 'v1/event/'
# def __init__(self, api):
# def post(self, event_time, event_type, details):
#
# Path: vitrageclient/v1/healthcheck.py
# class HealthCheck(object):
# URL = 'healthcheck/'
# STATUS_CODE_OK = 200
# def __init__(self, api):
# def get(self):
#
# Path: vitrageclient/v1/rca.py
# class Rca(object):
# def __init__(self, api):
# def get(self, alarm_id, all_tenants=False):
#
# Path: vitrageclient/v1/resource.py
# class Resource(object):
# def __init__(self, api):
# def list(self, resource_type=None, all_tenants=False, query=None):
# def get(self, vitrage_id):
# def count(self, resource_type=None, all_tenants=False, query=None,
# group_by=None):
#
# Path: vitrageclient/v1/service.py
# class Service(object):
# def __init__(self, api):
# def list(self):
#
# Path: vitrageclient/v1/status.py
# class Status(object):
# URL = 'v1/status/'
# def __init__(self, api):
# def get(self):
#
# Path: vitrageclient/v1/template.py
# class Template(object):
# def __init__(self, api):
# def list(self):
# def versions(self):
# def show(self, _id):
# def add(self, path=None, template_type=None,
# params=None, template_str=None, overwrite=False):
# def delete(self, ids):
# def validate(self, path=None, template_type=None,
# params=None, template_str=None):
# def _load_yaml_files(cls, path):
# def _load_yaml_file(cls, path):
# def _load_yaml(cls, yaml_content):
# def _load_template(cls, path, template_str):
#
# Path: vitrageclient/v1/topology.py
# class Topology(object):
# URL = 'v1/topology/'
# def __init__(self, api):
# def get(self,
# limit=None,
# graph_type='graph',
# query=None,
# root=None,
# all_tenants=False):
#
# Path: vitrageclient/v1/webhook.py
# class Webhook(object):
# def __init__(self, api):
# def list(self, all_tenants=False):
# def show(self, id):
# def add(self, url, regex_filter=None, headers=None):
# def delete(self, id):
. Output only the next line. | self.resource = resource.Resource(self._api) |
Continue the code snippet: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in 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 Client(object):
def __init__(self, session=None, service_type='rca', **kwargs):
logger = logging.getLogger(__name__)
self._api = client.VitrageClient(session, service_type=service_type,
logger=logger, **kwargs)
self.topology = topology.Topology(self._api)
self.resource = resource.Resource(self._api)
self.alarm = alarm.Alarm(self._api)
self.rca = rca.Rca(self._api)
self.template = template.Template(self._api)
self.event = event.Event(self._api)
self.healthcheck = healthcheck.HealthCheck(self._api)
self.webhook = webhook.Webhook(self._api)
<|code_end|>
. Use current file imports:
import logging
from vitrageclient import client
from vitrageclient.v1 import alarm
from vitrageclient.v1 import event
from vitrageclient.v1 import healthcheck
from vitrageclient.v1 import rca
from vitrageclient.v1 import resource
from vitrageclient.v1 import service
from vitrageclient.v1 import status
from vitrageclient.v1 import template
from vitrageclient.v1 import topology
from vitrageclient.v1 import webhook
and context (classes, functions, or code) from other files:
# Path: vitrageclient/client.py
# def Client(version, *args, **kwargs):
# def request(self, url, method, **kwargs):
# class VitrageClient(keystoneauth.Adapter):
#
# Path: vitrageclient/v1/alarm.py
# class Alarm(object):
# def __init__(self, api):
# def list(self, vitrage_id, all_tenants=False,
# limit=1000,
# sort_by=['start_timestamp', 'vitrage_id'],
# sort_dirs=['asc', 'asc'],
# filter_by=None,
# filter_vals=None,
# next_page=True,
# marker=None):
# def history(self, all_tenants=False,
# start=None,
# end=None,
# limit=1000,
# sort_by=('start_timestamp', 'vitrage_id'),
# sort_dirs=('asc', 'asc'),
# filter_by=None,
# filter_vals=None,
# next_page=True,
# marker=None):
# def get(self, vitrage_id):
# def count(self, all_tenants=False):
#
# Path: vitrageclient/v1/event.py
# class Event(object):
# URL = 'v1/event/'
# def __init__(self, api):
# def post(self, event_time, event_type, details):
#
# Path: vitrageclient/v1/healthcheck.py
# class HealthCheck(object):
# URL = 'healthcheck/'
# STATUS_CODE_OK = 200
# def __init__(self, api):
# def get(self):
#
# Path: vitrageclient/v1/rca.py
# class Rca(object):
# def __init__(self, api):
# def get(self, alarm_id, all_tenants=False):
#
# Path: vitrageclient/v1/resource.py
# class Resource(object):
# def __init__(self, api):
# def list(self, resource_type=None, all_tenants=False, query=None):
# def get(self, vitrage_id):
# def count(self, resource_type=None, all_tenants=False, query=None,
# group_by=None):
#
# Path: vitrageclient/v1/service.py
# class Service(object):
# def __init__(self, api):
# def list(self):
#
# Path: vitrageclient/v1/status.py
# class Status(object):
# URL = 'v1/status/'
# def __init__(self, api):
# def get(self):
#
# Path: vitrageclient/v1/template.py
# class Template(object):
# def __init__(self, api):
# def list(self):
# def versions(self):
# def show(self, _id):
# def add(self, path=None, template_type=None,
# params=None, template_str=None, overwrite=False):
# def delete(self, ids):
# def validate(self, path=None, template_type=None,
# params=None, template_str=None):
# def _load_yaml_files(cls, path):
# def _load_yaml_file(cls, path):
# def _load_yaml(cls, yaml_content):
# def _load_template(cls, path, template_str):
#
# Path: vitrageclient/v1/topology.py
# class Topology(object):
# URL = 'v1/topology/'
# def __init__(self, api):
# def get(self,
# limit=None,
# graph_type='graph',
# query=None,
# root=None,
# all_tenants=False):
#
# Path: vitrageclient/v1/webhook.py
# class Webhook(object):
# def __init__(self, api):
# def list(self, all_tenants=False):
# def show(self, id):
# def add(self, url, regex_filter=None, headers=None):
# def delete(self, id):
. Output only the next line. | self.service = service.Service(self._api) |
Continue the code snippet: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in 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 Client(object):
def __init__(self, session=None, service_type='rca', **kwargs):
logger = logging.getLogger(__name__)
self._api = client.VitrageClient(session, service_type=service_type,
logger=logger, **kwargs)
self.topology = topology.Topology(self._api)
self.resource = resource.Resource(self._api)
self.alarm = alarm.Alarm(self._api)
self.rca = rca.Rca(self._api)
self.template = template.Template(self._api)
self.event = event.Event(self._api)
self.healthcheck = healthcheck.HealthCheck(self._api)
self.webhook = webhook.Webhook(self._api)
self.service = service.Service(self._api)
<|code_end|>
. Use current file imports:
import logging
from vitrageclient import client
from vitrageclient.v1 import alarm
from vitrageclient.v1 import event
from vitrageclient.v1 import healthcheck
from vitrageclient.v1 import rca
from vitrageclient.v1 import resource
from vitrageclient.v1 import service
from vitrageclient.v1 import status
from vitrageclient.v1 import template
from vitrageclient.v1 import topology
from vitrageclient.v1 import webhook
and context (classes, functions, or code) from other files:
# Path: vitrageclient/client.py
# def Client(version, *args, **kwargs):
# def request(self, url, method, **kwargs):
# class VitrageClient(keystoneauth.Adapter):
#
# Path: vitrageclient/v1/alarm.py
# class Alarm(object):
# def __init__(self, api):
# def list(self, vitrage_id, all_tenants=False,
# limit=1000,
# sort_by=['start_timestamp', 'vitrage_id'],
# sort_dirs=['asc', 'asc'],
# filter_by=None,
# filter_vals=None,
# next_page=True,
# marker=None):
# def history(self, all_tenants=False,
# start=None,
# end=None,
# limit=1000,
# sort_by=('start_timestamp', 'vitrage_id'),
# sort_dirs=('asc', 'asc'),
# filter_by=None,
# filter_vals=None,
# next_page=True,
# marker=None):
# def get(self, vitrage_id):
# def count(self, all_tenants=False):
#
# Path: vitrageclient/v1/event.py
# class Event(object):
# URL = 'v1/event/'
# def __init__(self, api):
# def post(self, event_time, event_type, details):
#
# Path: vitrageclient/v1/healthcheck.py
# class HealthCheck(object):
# URL = 'healthcheck/'
# STATUS_CODE_OK = 200
# def __init__(self, api):
# def get(self):
#
# Path: vitrageclient/v1/rca.py
# class Rca(object):
# def __init__(self, api):
# def get(self, alarm_id, all_tenants=False):
#
# Path: vitrageclient/v1/resource.py
# class Resource(object):
# def __init__(self, api):
# def list(self, resource_type=None, all_tenants=False, query=None):
# def get(self, vitrage_id):
# def count(self, resource_type=None, all_tenants=False, query=None,
# group_by=None):
#
# Path: vitrageclient/v1/service.py
# class Service(object):
# def __init__(self, api):
# def list(self):
#
# Path: vitrageclient/v1/status.py
# class Status(object):
# URL = 'v1/status/'
# def __init__(self, api):
# def get(self):
#
# Path: vitrageclient/v1/template.py
# class Template(object):
# def __init__(self, api):
# def list(self):
# def versions(self):
# def show(self, _id):
# def add(self, path=None, template_type=None,
# params=None, template_str=None, overwrite=False):
# def delete(self, ids):
# def validate(self, path=None, template_type=None,
# params=None, template_str=None):
# def _load_yaml_files(cls, path):
# def _load_yaml_file(cls, path):
# def _load_yaml(cls, yaml_content):
# def _load_template(cls, path, template_str):
#
# Path: vitrageclient/v1/topology.py
# class Topology(object):
# URL = 'v1/topology/'
# def __init__(self, api):
# def get(self,
# limit=None,
# graph_type='graph',
# query=None,
# root=None,
# all_tenants=False):
#
# Path: vitrageclient/v1/webhook.py
# class Webhook(object):
# def __init__(self, api):
# def list(self, all_tenants=False):
# def show(self, id):
# def add(self, url, regex_filter=None, headers=None):
# def delete(self, id):
. Output only the next line. | self.status = status.Status(self._api) |
Continue the code snippet: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in 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 Client(object):
def __init__(self, session=None, service_type='rca', **kwargs):
logger = logging.getLogger(__name__)
self._api = client.VitrageClient(session, service_type=service_type,
logger=logger, **kwargs)
self.topology = topology.Topology(self._api)
self.resource = resource.Resource(self._api)
self.alarm = alarm.Alarm(self._api)
self.rca = rca.Rca(self._api)
<|code_end|>
. Use current file imports:
import logging
from vitrageclient import client
from vitrageclient.v1 import alarm
from vitrageclient.v1 import event
from vitrageclient.v1 import healthcheck
from vitrageclient.v1 import rca
from vitrageclient.v1 import resource
from vitrageclient.v1 import service
from vitrageclient.v1 import status
from vitrageclient.v1 import template
from vitrageclient.v1 import topology
from vitrageclient.v1 import webhook
and context (classes, functions, or code) from other files:
# Path: vitrageclient/client.py
# def Client(version, *args, **kwargs):
# def request(self, url, method, **kwargs):
# class VitrageClient(keystoneauth.Adapter):
#
# Path: vitrageclient/v1/alarm.py
# class Alarm(object):
# def __init__(self, api):
# def list(self, vitrage_id, all_tenants=False,
# limit=1000,
# sort_by=['start_timestamp', 'vitrage_id'],
# sort_dirs=['asc', 'asc'],
# filter_by=None,
# filter_vals=None,
# next_page=True,
# marker=None):
# def history(self, all_tenants=False,
# start=None,
# end=None,
# limit=1000,
# sort_by=('start_timestamp', 'vitrage_id'),
# sort_dirs=('asc', 'asc'),
# filter_by=None,
# filter_vals=None,
# next_page=True,
# marker=None):
# def get(self, vitrage_id):
# def count(self, all_tenants=False):
#
# Path: vitrageclient/v1/event.py
# class Event(object):
# URL = 'v1/event/'
# def __init__(self, api):
# def post(self, event_time, event_type, details):
#
# Path: vitrageclient/v1/healthcheck.py
# class HealthCheck(object):
# URL = 'healthcheck/'
# STATUS_CODE_OK = 200
# def __init__(self, api):
# def get(self):
#
# Path: vitrageclient/v1/rca.py
# class Rca(object):
# def __init__(self, api):
# def get(self, alarm_id, all_tenants=False):
#
# Path: vitrageclient/v1/resource.py
# class Resource(object):
# def __init__(self, api):
# def list(self, resource_type=None, all_tenants=False, query=None):
# def get(self, vitrage_id):
# def count(self, resource_type=None, all_tenants=False, query=None,
# group_by=None):
#
# Path: vitrageclient/v1/service.py
# class Service(object):
# def __init__(self, api):
# def list(self):
#
# Path: vitrageclient/v1/status.py
# class Status(object):
# URL = 'v1/status/'
# def __init__(self, api):
# def get(self):
#
# Path: vitrageclient/v1/template.py
# class Template(object):
# def __init__(self, api):
# def list(self):
# def versions(self):
# def show(self, _id):
# def add(self, path=None, template_type=None,
# params=None, template_str=None, overwrite=False):
# def delete(self, ids):
# def validate(self, path=None, template_type=None,
# params=None, template_str=None):
# def _load_yaml_files(cls, path):
# def _load_yaml_file(cls, path):
# def _load_yaml(cls, yaml_content):
# def _load_template(cls, path, template_str):
#
# Path: vitrageclient/v1/topology.py
# class Topology(object):
# URL = 'v1/topology/'
# def __init__(self, api):
# def get(self,
# limit=None,
# graph_type='graph',
# query=None,
# root=None,
# all_tenants=False):
#
# Path: vitrageclient/v1/webhook.py
# class Webhook(object):
# def __init__(self, api):
# def list(self, all_tenants=False):
# def show(self, id):
# def add(self, url, regex_filter=None, headers=None):
# def delete(self, id):
. Output only the next line. | self.template = template.Template(self._api) |
Predict the next line for this snippet: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in 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 Client(object):
def __init__(self, session=None, service_type='rca', **kwargs):
logger = logging.getLogger(__name__)
self._api = client.VitrageClient(session, service_type=service_type,
logger=logger, **kwargs)
<|code_end|>
with the help of current file imports:
import logging
from vitrageclient import client
from vitrageclient.v1 import alarm
from vitrageclient.v1 import event
from vitrageclient.v1 import healthcheck
from vitrageclient.v1 import rca
from vitrageclient.v1 import resource
from vitrageclient.v1 import service
from vitrageclient.v1 import status
from vitrageclient.v1 import template
from vitrageclient.v1 import topology
from vitrageclient.v1 import webhook
and context from other files:
# Path: vitrageclient/client.py
# def Client(version, *args, **kwargs):
# def request(self, url, method, **kwargs):
# class VitrageClient(keystoneauth.Adapter):
#
# Path: vitrageclient/v1/alarm.py
# class Alarm(object):
# def __init__(self, api):
# def list(self, vitrage_id, all_tenants=False,
# limit=1000,
# sort_by=['start_timestamp', 'vitrage_id'],
# sort_dirs=['asc', 'asc'],
# filter_by=None,
# filter_vals=None,
# next_page=True,
# marker=None):
# def history(self, all_tenants=False,
# start=None,
# end=None,
# limit=1000,
# sort_by=('start_timestamp', 'vitrage_id'),
# sort_dirs=('asc', 'asc'),
# filter_by=None,
# filter_vals=None,
# next_page=True,
# marker=None):
# def get(self, vitrage_id):
# def count(self, all_tenants=False):
#
# Path: vitrageclient/v1/event.py
# class Event(object):
# URL = 'v1/event/'
# def __init__(self, api):
# def post(self, event_time, event_type, details):
#
# Path: vitrageclient/v1/healthcheck.py
# class HealthCheck(object):
# URL = 'healthcheck/'
# STATUS_CODE_OK = 200
# def __init__(self, api):
# def get(self):
#
# Path: vitrageclient/v1/rca.py
# class Rca(object):
# def __init__(self, api):
# def get(self, alarm_id, all_tenants=False):
#
# Path: vitrageclient/v1/resource.py
# class Resource(object):
# def __init__(self, api):
# def list(self, resource_type=None, all_tenants=False, query=None):
# def get(self, vitrage_id):
# def count(self, resource_type=None, all_tenants=False, query=None,
# group_by=None):
#
# Path: vitrageclient/v1/service.py
# class Service(object):
# def __init__(self, api):
# def list(self):
#
# Path: vitrageclient/v1/status.py
# class Status(object):
# URL = 'v1/status/'
# def __init__(self, api):
# def get(self):
#
# Path: vitrageclient/v1/template.py
# class Template(object):
# def __init__(self, api):
# def list(self):
# def versions(self):
# def show(self, _id):
# def add(self, path=None, template_type=None,
# params=None, template_str=None, overwrite=False):
# def delete(self, ids):
# def validate(self, path=None, template_type=None,
# params=None, template_str=None):
# def _load_yaml_files(cls, path):
# def _load_yaml_file(cls, path):
# def _load_yaml(cls, yaml_content):
# def _load_template(cls, path, template_str):
#
# Path: vitrageclient/v1/topology.py
# class Topology(object):
# URL = 'v1/topology/'
# def __init__(self, api):
# def get(self,
# limit=None,
# graph_type='graph',
# query=None,
# root=None,
# all_tenants=False):
#
# Path: vitrageclient/v1/webhook.py
# class Webhook(object):
# def __init__(self, api):
# def list(self, all_tenants=False):
# def show(self, id):
# def add(self, url, regex_filter=None, headers=None):
# def delete(self, id):
, which may contain function names, class names, or code. Output only the next line. | self.topology = topology.Topology(self._api) |
Given the code snippet: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in 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 Client(object):
def __init__(self, session=None, service_type='rca', **kwargs):
logger = logging.getLogger(__name__)
self._api = client.VitrageClient(session, service_type=service_type,
logger=logger, **kwargs)
self.topology = topology.Topology(self._api)
self.resource = resource.Resource(self._api)
self.alarm = alarm.Alarm(self._api)
self.rca = rca.Rca(self._api)
self.template = template.Template(self._api)
self.event = event.Event(self._api)
self.healthcheck = healthcheck.HealthCheck(self._api)
<|code_end|>
, generate the next line using the imports in this file:
import logging
from vitrageclient import client
from vitrageclient.v1 import alarm
from vitrageclient.v1 import event
from vitrageclient.v1 import healthcheck
from vitrageclient.v1 import rca
from vitrageclient.v1 import resource
from vitrageclient.v1 import service
from vitrageclient.v1 import status
from vitrageclient.v1 import template
from vitrageclient.v1 import topology
from vitrageclient.v1 import webhook
and context (functions, classes, or occasionally code) from other files:
# Path: vitrageclient/client.py
# def Client(version, *args, **kwargs):
# def request(self, url, method, **kwargs):
# class VitrageClient(keystoneauth.Adapter):
#
# Path: vitrageclient/v1/alarm.py
# class Alarm(object):
# def __init__(self, api):
# def list(self, vitrage_id, all_tenants=False,
# limit=1000,
# sort_by=['start_timestamp', 'vitrage_id'],
# sort_dirs=['asc', 'asc'],
# filter_by=None,
# filter_vals=None,
# next_page=True,
# marker=None):
# def history(self, all_tenants=False,
# start=None,
# end=None,
# limit=1000,
# sort_by=('start_timestamp', 'vitrage_id'),
# sort_dirs=('asc', 'asc'),
# filter_by=None,
# filter_vals=None,
# next_page=True,
# marker=None):
# def get(self, vitrage_id):
# def count(self, all_tenants=False):
#
# Path: vitrageclient/v1/event.py
# class Event(object):
# URL = 'v1/event/'
# def __init__(self, api):
# def post(self, event_time, event_type, details):
#
# Path: vitrageclient/v1/healthcheck.py
# class HealthCheck(object):
# URL = 'healthcheck/'
# STATUS_CODE_OK = 200
# def __init__(self, api):
# def get(self):
#
# Path: vitrageclient/v1/rca.py
# class Rca(object):
# def __init__(self, api):
# def get(self, alarm_id, all_tenants=False):
#
# Path: vitrageclient/v1/resource.py
# class Resource(object):
# def __init__(self, api):
# def list(self, resource_type=None, all_tenants=False, query=None):
# def get(self, vitrage_id):
# def count(self, resource_type=None, all_tenants=False, query=None,
# group_by=None):
#
# Path: vitrageclient/v1/service.py
# class Service(object):
# def __init__(self, api):
# def list(self):
#
# Path: vitrageclient/v1/status.py
# class Status(object):
# URL = 'v1/status/'
# def __init__(self, api):
# def get(self):
#
# Path: vitrageclient/v1/template.py
# class Template(object):
# def __init__(self, api):
# def list(self):
# def versions(self):
# def show(self, _id):
# def add(self, path=None, template_type=None,
# params=None, template_str=None, overwrite=False):
# def delete(self, ids):
# def validate(self, path=None, template_type=None,
# params=None, template_str=None):
# def _load_yaml_files(cls, path):
# def _load_yaml_file(cls, path):
# def _load_yaml(cls, yaml_content):
# def _load_template(cls, path, template_str):
#
# Path: vitrageclient/v1/topology.py
# class Topology(object):
# URL = 'v1/topology/'
# def __init__(self, api):
# def get(self,
# limit=None,
# graph_type='graph',
# query=None,
# root=None,
# all_tenants=False):
#
# Path: vitrageclient/v1/webhook.py
# class Webhook(object):
# def __init__(self, api):
# def list(self, all_tenants=False):
# def show(self, id):
# def add(self, url, regex_filter=None, headers=None):
# def delete(self, id):
. Output only the next line. | self.webhook = webhook.Webhook(self._api) |
Given the code snippet: <|code_start|> 'Valid graph types: [tree, graph]')
parser.add_argument('--all-tenants',
default=False,
dest='all_tenants',
action='store_true',
help='Shows entities of all the tenants in the '
'entity graph')
return parser
@property
def formatter_namespace(self):
return 'vitrageclient.formatter.show'
@property
def formatter_default(self):
return 'json'
def take_action(self, parsed_args):
limit = parsed_args.limit
graph_type = parsed_args.type
query = parsed_args.filter
root = parsed_args.root
all_tenants = parsed_args.all_tenants
if graph_type == 'graph' and limit is not None and root is None:
raise exc.CommandError("Graph-type 'graph' "
"requires a 'root' with 'limit'.")
<|code_end|>
, generate the next line using the imports in this file:
import argparse
from cliff import show
from vitrageclient.common import utils
from vitrageclient import exceptions as exc
and context (functions, classes, or occasionally code) from other files:
# Path: vitrageclient/common/utils.py
# def args_to_dict(args, attrs):
# def list2cols(cols, objs):
# def list2cols_with_rename(names_and_keys, objs):
# def get_client(obj):
# def wait_for_action_to_end(timeout, func, **kwargs):
# def find_template_with_uuid(uuid, templates):
#
# Path: vitrageclient/exceptions.py
# class CommandError(Exception):
# class ClientException(Exception):
# def __init__(self, code, message=None, request_id=None,
# url=None, method=None):
# def __str__(self):
# def from_response(resp, url, method):
. Output only the next line. | topology = utils.get_client(self).topology.get(limit=limit, |
Continue the code snippet: <|code_start|> default='graph',
dest='type',
help='graph type. '
'Valid graph types: [tree, graph]')
parser.add_argument('--all-tenants',
default=False,
dest='all_tenants',
action='store_true',
help='Shows entities of all the tenants in the '
'entity graph')
return parser
@property
def formatter_namespace(self):
return 'vitrageclient.formatter.show'
@property
def formatter_default(self):
return 'json'
def take_action(self, parsed_args):
limit = parsed_args.limit
graph_type = parsed_args.type
query = parsed_args.filter
root = parsed_args.root
all_tenants = parsed_args.all_tenants
if graph_type == 'graph' and limit is not None and root is None:
<|code_end|>
. Use current file imports:
import argparse
from cliff import show
from vitrageclient.common import utils
from vitrageclient import exceptions as exc
and context (classes, functions, or code) from other files:
# Path: vitrageclient/common/utils.py
# def args_to_dict(args, attrs):
# def list2cols(cols, objs):
# def list2cols_with_rename(names_and_keys, objs):
# def get_client(obj):
# def wait_for_action_to_end(timeout, func, **kwargs):
# def find_template_with_uuid(uuid, templates):
#
# Path: vitrageclient/exceptions.py
# class CommandError(Exception):
# class ClientException(Exception):
# def __init__(self, code, message=None, request_id=None,
# url=None, method=None):
# def __str__(self):
# def from_response(resp, url, method):
. Output only the next line. | raise exc.CommandError("Graph-type 'graph' " |
Continue the code snippet: <|code_start|># noinspection PyAbstractClass
class TemplateValidate(show.ShowOne):
"""Validate a template file"""
def get_parser(self, prog_name):
parser = super(TemplateValidate, self).get_parser(prog_name)
parser.add_argument('--path',
required=True,
help='full path for template file or templates dir'
)
parser.add_argument('--type',
choices=['standard', 'definition', 'equivalence'],
help='Template type. Valid types:'
'[standard, definition, equivalence]')
parser.add_argument('--params', nargs='+',
help='Actual values for parameters of the '
'template. Several key=value pairs may be '
'used, for example: --params '
'template_name=cpu_problem '
'alarm_name=\'High CPU Load\'')
return parser
@property
def formatter_default(self):
return 'json'
def take_action(self, parsed_args):
cli_param_list = parsed_args.params
params = _parse_template_params(cli_param_list)
<|code_end|>
. Use current file imports:
import sys
from cliff import command
from cliff import lister
from cliff import show
from oslo_log import log
from vitrageclient.common import utils
from vitrageclient.common.utils import find_template_with_uuid
and context (classes, functions, or code) from other files:
# Path: vitrageclient/common/utils.py
# def args_to_dict(args, attrs):
# def list2cols(cols, objs):
# def list2cols_with_rename(names_and_keys, objs):
# def get_client(obj):
# def wait_for_action_to_end(timeout, func, **kwargs):
# def find_template_with_uuid(uuid, templates):
#
# Path: vitrageclient/common/utils.py
# def find_template_with_uuid(uuid, templates):
# return next(
# (
# template
# for template in templates
# if template['uuid'] == uuid
# ), None
# )
. Output only the next line. | result = utils.get_client(self).template.validate( |
Predict the next line for this snippet: <|code_start|> ), templates)
def _check_finished_loading(self, templates):
if all(
(
template['status'] == 'ERROR'
for template in templates
)
):
return True
try:
api_templates = utils.get_client(self).template.list()
self._update_templates_status(api_templates, templates)
if any(
(
template['status'] == 'LOADING'
for template in templates
)
):
return False
return True
except Exception:
return True
@staticmethod
def _update_templates_status(api_templates, templates):
for template in templates:
uuid = template.get('uuid')
if uuid:
<|code_end|>
with the help of current file imports:
import sys
from cliff import command
from cliff import lister
from cliff import show
from oslo_log import log
from vitrageclient.common import utils
from vitrageclient.common.utils import find_template_with_uuid
and context from other files:
# Path: vitrageclient/common/utils.py
# def args_to_dict(args, attrs):
# def list2cols(cols, objs):
# def list2cols_with_rename(names_and_keys, objs):
# def get_client(obj):
# def wait_for_action_to_end(timeout, func, **kwargs):
# def find_template_with_uuid(uuid, templates):
#
# Path: vitrageclient/common/utils.py
# def find_template_with_uuid(uuid, templates):
# return next(
# (
# template
# for template in templates
# if template['uuid'] == uuid
# ), None
# )
, which may contain function names, class names, or code. Output only the next line. | api_template = find_template_with_uuid(uuid, api_templates) |
Given snippet: <|code_start|> name: cpu problem
host:
type: nova.host
scenarios:
- condition: alarm [ on ] host
actions:
- set_state:
state: ERROR
target: host
"""
class TestTemplate(base.BaseTestCase):
def test_validate_by_path(self):
template_path = get_resources_dir() + '/template1.yaml'
template = Template(mock.Mock())
template.validate(path=template_path)
def test_validate_by_nonexisting_path(self):
template = Template(mock.Mock())
self.assertRaises(IOError, template.validate,
path='non_existing_template_path.yaml')
def test_validate_by_template(self):
template = Template(mock.Mock())
template.validate(template_str=TEMPLATE_STRING)
def test_validate_by_nothing(self):
template = Template(mock.Mock())
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from unittest import mock
from oslotest import base
from vitrageclient import exceptions as exc
from vitrageclient.tests.utils import get_resources_dir
from vitrageclient.v1.template import Template
and context:
# Path: vitrageclient/exceptions.py
# class CommandError(Exception):
# class ClientException(Exception):
# def __init__(self, code, message=None, request_id=None,
# url=None, method=None):
# def __str__(self):
# def from_response(resp, url, method):
#
# Path: vitrageclient/tests/utils.py
# def get_resources_dir():
# return path.join(path.dirname(__file__), 'resources')
#
# Path: vitrageclient/v1/template.py
# class Template(object):
#
# url = 'v1/template/'
#
# def __init__(self, api):
# self.api = api
#
# def list(self):
# """Get templates list"""
# return self.api.get(self.url).json()
#
# def versions(self):
# """Get templates versions"""
# return self.api.get(self.url + 'versions').json()
#
# def show(self, _id):
# """Show template content"""
#
# url = self.url + _id
# return self.api.get(url).json()
#
# def add(self, path=None, template_type=None,
# params=None, template_str=None, overwrite=False):
# """Add a new template
#
# :param path: (optional) The template file path or templates dir path
# :param template_type: (optional) The template type, in case it is not
# written inside the template metadata section
# :param params: (optional) Actual values for the template parameters
# :param template_str: (optional) A string representation of the template
# :param overwrite: (optional) overwrite the template if exists
# yaml
# Either path or template_str must exist (but not both)
#
# :return:
# """
# files_content = \
# self._load_template(path=path, template_str=template_str)
# api_params = dict(templates=files_content,
# template_type=template_type,
# params=params, overwrite=overwrite)
# return self.api.put(self.url, json=api_params).json()
#
# def delete(self, ids):
# """Delete existing"""
# params = dict(id=ids)
# return self.api.delete(self.url, json=params).json()
#
# def validate(self, path=None, template_type=None,
# params=None, template_str=None):
# """Template validation
#
# Make sure that the template file is correct in terms of syntax
# and content.
# It is possible to pass a specific file path in order to validate one
# template, or directory path for validation of several templates (the
# directory must contain only templates)
#
# :param path: (optional) The template file path or templates dir path
# :param template_type: (optional) The template type, in case it is not
# written inside the template metadata section
# :param params: (optional) Actual values for the template parameters
# :param template_str: (optional) A string representation of the template
# yaml
# Either path or template_str must exist (but not both)
#
# :return:
# """
# files_content = \
# self._load_template(path=path, template_str=template_str)
# api_params = dict(templates=files_content,
# template_type=template_type,
# params=params)
# return self.api.post(self.url, json=api_params).json()
#
# @classmethod
# def _load_yaml_files(cls, path):
# if os.path.isdir(path):
#
# files_content = []
# for file_name in os.listdir(path):
#
# file_path = '%s/%s' % (path, file_name)
# if os.path.isfile(file_path):
# template = cls._load_yaml_file(file_path)
# files_content.append((file_path, template))
# else:
# files_content = [(path, cls._load_yaml_file(path))]
#
# return files_content
#
# @classmethod
# def _load_yaml_file(cls, path):
# with open(path, 'r') as stream:
# return cls._load_yaml(stream)
#
# @classmethod
# def _load_yaml(cls, yaml_content):
# try:
# return yaml_utils.load(yaml_content)
# except ValueError as e:
# message = 'Could not load template: %s. Reason: %s' \
# % (yaml_content, e)
# raise exc.CommandError(message)
#
# @classmethod
# def _load_template(cls, path, template_str):
# if path:
# files_content = cls._load_yaml_files(path)
# elif template_str:
# files_content = [(None, cls._load_yaml(template_str))]
# else:
# raise exc.CommandError(
# 'Add template API must be called with either \'path\' or '
# '\'template_str\'')
#
# return files_content
which might include code, classes, or functions. Output only the next line. | self.assertRaises(exc.CommandError, template.validate) |
Here is a snippet: <|code_start|># WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
TEMPLATE_STRING = """
metadata:
version: 3
name: template1
description: simple template
type: standard
entities:
alarm:
name: cpu problem
host:
type: nova.host
scenarios:
- condition: alarm [ on ] host
actions:
- set_state:
state: ERROR
target: host
"""
class TestTemplate(base.BaseTestCase):
def test_validate_by_path(self):
<|code_end|>
. Write the next line using the current file imports:
from unittest import mock
from oslotest import base
from vitrageclient import exceptions as exc
from vitrageclient.tests.utils import get_resources_dir
from vitrageclient.v1.template import Template
and context from other files:
# Path: vitrageclient/exceptions.py
# class CommandError(Exception):
# class ClientException(Exception):
# def __init__(self, code, message=None, request_id=None,
# url=None, method=None):
# def __str__(self):
# def from_response(resp, url, method):
#
# Path: vitrageclient/tests/utils.py
# def get_resources_dir():
# return path.join(path.dirname(__file__), 'resources')
#
# Path: vitrageclient/v1/template.py
# class Template(object):
#
# url = 'v1/template/'
#
# def __init__(self, api):
# self.api = api
#
# def list(self):
# """Get templates list"""
# return self.api.get(self.url).json()
#
# def versions(self):
# """Get templates versions"""
# return self.api.get(self.url + 'versions').json()
#
# def show(self, _id):
# """Show template content"""
#
# url = self.url + _id
# return self.api.get(url).json()
#
# def add(self, path=None, template_type=None,
# params=None, template_str=None, overwrite=False):
# """Add a new template
#
# :param path: (optional) The template file path or templates dir path
# :param template_type: (optional) The template type, in case it is not
# written inside the template metadata section
# :param params: (optional) Actual values for the template parameters
# :param template_str: (optional) A string representation of the template
# :param overwrite: (optional) overwrite the template if exists
# yaml
# Either path or template_str must exist (but not both)
#
# :return:
# """
# files_content = \
# self._load_template(path=path, template_str=template_str)
# api_params = dict(templates=files_content,
# template_type=template_type,
# params=params, overwrite=overwrite)
# return self.api.put(self.url, json=api_params).json()
#
# def delete(self, ids):
# """Delete existing"""
# params = dict(id=ids)
# return self.api.delete(self.url, json=params).json()
#
# def validate(self, path=None, template_type=None,
# params=None, template_str=None):
# """Template validation
#
# Make sure that the template file is correct in terms of syntax
# and content.
# It is possible to pass a specific file path in order to validate one
# template, or directory path for validation of several templates (the
# directory must contain only templates)
#
# :param path: (optional) The template file path or templates dir path
# :param template_type: (optional) The template type, in case it is not
# written inside the template metadata section
# :param params: (optional) Actual values for the template parameters
# :param template_str: (optional) A string representation of the template
# yaml
# Either path or template_str must exist (but not both)
#
# :return:
# """
# files_content = \
# self._load_template(path=path, template_str=template_str)
# api_params = dict(templates=files_content,
# template_type=template_type,
# params=params)
# return self.api.post(self.url, json=api_params).json()
#
# @classmethod
# def _load_yaml_files(cls, path):
# if os.path.isdir(path):
#
# files_content = []
# for file_name in os.listdir(path):
#
# file_path = '%s/%s' % (path, file_name)
# if os.path.isfile(file_path):
# template = cls._load_yaml_file(file_path)
# files_content.append((file_path, template))
# else:
# files_content = [(path, cls._load_yaml_file(path))]
#
# return files_content
#
# @classmethod
# def _load_yaml_file(cls, path):
# with open(path, 'r') as stream:
# return cls._load_yaml(stream)
#
# @classmethod
# def _load_yaml(cls, yaml_content):
# try:
# return yaml_utils.load(yaml_content)
# except ValueError as e:
# message = 'Could not load template: %s. Reason: %s' \
# % (yaml_content, e)
# raise exc.CommandError(message)
#
# @classmethod
# def _load_template(cls, path, template_str):
# if path:
# files_content = cls._load_yaml_files(path)
# elif template_str:
# files_content = [(None, cls._load_yaml(template_str))]
# else:
# raise exc.CommandError(
# 'Add template API must be called with either \'path\' or '
# '\'template_str\'')
#
# return files_content
, which may include functions, classes, or code. Output only the next line. | template_path = get_resources_dir() + '/template1.yaml' |
Next line prediction: <|code_start|># License for the specific language governing permissions and limitations
# under the License.
TEMPLATE_STRING = """
metadata:
version: 3
name: template1
description: simple template
type: standard
entities:
alarm:
name: cpu problem
host:
type: nova.host
scenarios:
- condition: alarm [ on ] host
actions:
- set_state:
state: ERROR
target: host
"""
class TestTemplate(base.BaseTestCase):
def test_validate_by_path(self):
template_path = get_resources_dir() + '/template1.yaml'
<|code_end|>
. Use current file imports:
(from unittest import mock
from oslotest import base
from vitrageclient import exceptions as exc
from vitrageclient.tests.utils import get_resources_dir
from vitrageclient.v1.template import Template)
and context including class names, function names, or small code snippets from other files:
# Path: vitrageclient/exceptions.py
# class CommandError(Exception):
# class ClientException(Exception):
# def __init__(self, code, message=None, request_id=None,
# url=None, method=None):
# def __str__(self):
# def from_response(resp, url, method):
#
# Path: vitrageclient/tests/utils.py
# def get_resources_dir():
# return path.join(path.dirname(__file__), 'resources')
#
# Path: vitrageclient/v1/template.py
# class Template(object):
#
# url = 'v1/template/'
#
# def __init__(self, api):
# self.api = api
#
# def list(self):
# """Get templates list"""
# return self.api.get(self.url).json()
#
# def versions(self):
# """Get templates versions"""
# return self.api.get(self.url + 'versions').json()
#
# def show(self, _id):
# """Show template content"""
#
# url = self.url + _id
# return self.api.get(url).json()
#
# def add(self, path=None, template_type=None,
# params=None, template_str=None, overwrite=False):
# """Add a new template
#
# :param path: (optional) The template file path or templates dir path
# :param template_type: (optional) The template type, in case it is not
# written inside the template metadata section
# :param params: (optional) Actual values for the template parameters
# :param template_str: (optional) A string representation of the template
# :param overwrite: (optional) overwrite the template if exists
# yaml
# Either path or template_str must exist (but not both)
#
# :return:
# """
# files_content = \
# self._load_template(path=path, template_str=template_str)
# api_params = dict(templates=files_content,
# template_type=template_type,
# params=params, overwrite=overwrite)
# return self.api.put(self.url, json=api_params).json()
#
# def delete(self, ids):
# """Delete existing"""
# params = dict(id=ids)
# return self.api.delete(self.url, json=params).json()
#
# def validate(self, path=None, template_type=None,
# params=None, template_str=None):
# """Template validation
#
# Make sure that the template file is correct in terms of syntax
# and content.
# It is possible to pass a specific file path in order to validate one
# template, or directory path for validation of several templates (the
# directory must contain only templates)
#
# :param path: (optional) The template file path or templates dir path
# :param template_type: (optional) The template type, in case it is not
# written inside the template metadata section
# :param params: (optional) Actual values for the template parameters
# :param template_str: (optional) A string representation of the template
# yaml
# Either path or template_str must exist (but not both)
#
# :return:
# """
# files_content = \
# self._load_template(path=path, template_str=template_str)
# api_params = dict(templates=files_content,
# template_type=template_type,
# params=params)
# return self.api.post(self.url, json=api_params).json()
#
# @classmethod
# def _load_yaml_files(cls, path):
# if os.path.isdir(path):
#
# files_content = []
# for file_name in os.listdir(path):
#
# file_path = '%s/%s' % (path, file_name)
# if os.path.isfile(file_path):
# template = cls._load_yaml_file(file_path)
# files_content.append((file_path, template))
# else:
# files_content = [(path, cls._load_yaml_file(path))]
#
# return files_content
#
# @classmethod
# def _load_yaml_file(cls, path):
# with open(path, 'r') as stream:
# return cls._load_yaml(stream)
#
# @classmethod
# def _load_yaml(cls, yaml_content):
# try:
# return yaml_utils.load(yaml_content)
# except ValueError as e:
# message = 'Could not load template: %s. Reason: %s' \
# % (yaml_content, e)
# raise exc.CommandError(message)
#
# @classmethod
# def _load_template(cls, path, template_str):
# if path:
# files_content = cls._load_yaml_files(path)
# elif template_str:
# files_content = [(None, cls._load_yaml(template_str))]
# else:
# raise exc.CommandError(
# 'Add template API must be called with either \'path\' or '
# '\'template_str\'')
#
# return files_content
. Output only the next line. | template = Template(mock.Mock()) |
Predict the next line after this snippet: <|code_start|># Copyright 2019 - Nokia Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in 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 ServiceList(lister.Lister):
"""List all services"""
def get_parser(self, prog_name):
parser = super(ServiceList, self).get_parser(prog_name)
return parser
def take_action(self, parsed_args):
<|code_end|>
using the current file's imports:
from cliff import lister
from vitrageclient.common import utils
and any relevant context from other files:
# Path: vitrageclient/common/utils.py
# def args_to_dict(args, attrs):
# def list2cols(cols, objs):
# def list2cols_with_rename(names_and_keys, objs):
# def get_client(obj):
# def wait_for_action_to_end(timeout, func, **kwargs):
# def find_template_with_uuid(uuid, templates):
. Output only the next line. | service = utils.get_client(self).service.list() |
Given the code snippet: <|code_start|>
@mock.patch.object(ArgumentParser, "error")
def test_parser_topology_limit_with_a_negative_number(self, mock_parser):
mock_parser.side_effect = self._my_parser_error_func
parser = self.topology_show.get_parser('vitrage topology show')
with ExpectedException(ArgumentTypeError,
'argument --limit: -5 must be greater than 0'):
parser.parse_args(args=['--filter', 'bla',
'--limit', '-5',
'--root', 'blabla',
'--graph-type', 'tree'])
@mock.patch.object(ArgumentParser, "error")
def test_parser_topology_limit_with_a_string(self, mock_parser):
mock_parser.side_effect = self._my_parser_error_func
parser = self.topology_show.get_parser('vitrage topology show')
with ExpectedException(ArgumentTypeError,
'argument --limit: spam must be an integer'):
parser.parse_args(args=['--filter', 'bla',
'--limit', 'spam',
'--root', 'blabla',
'--graph-type', 'tree'])
def test_dot_emitter(self):
def dict2columns(data):
return zip(*sorted(data.items()))
out = io.StringIO()
<|code_end|>
, generate the next line using the imports in this file:
from argparse import ArgumentParser
from argparse import ArgumentTypeError
from unittest import mock
from testtools import ExpectedException
from vitrageclient.common.formatters import DOTFormatter
from vitrageclient.common.formatters import GraphMLFormatter
from vitrageclient.tests.cli.base import CliTestCase
from vitrageclient.v1.cli.topology import TopologyShow
import io
import json
and context (functions, classes, or occasionally code) from other files:
# Path: vitrageclient/common/formatters.py
# class DOTFormatter(GraphFormatter):
#
# def _write_format(self, graph, stdout):
# write_dot(graph, stdout)
#
# Path: vitrageclient/common/formatters.py
# class GraphMLFormatter(GraphFormatter):
#
# def _write_format(self, graph, stdout):
# writer = GraphMLWriter(graph=graph)
# writer.dump(stdout)
#
# Path: vitrageclient/tests/cli/base.py
# class CliTestCase(base.BaseTestCase):
#
# """Test case base class for all unit tests."""
#
# # original error method of argparse uses exit
# # I just want to raise an exception and get the error message
# # that exit outputs
# @staticmethod
# def _my_parser_error_func(message):
# raise argparse.ArgumentTypeError(message)
#
# Path: vitrageclient/v1/cli/topology.py
# class TopologyShow(show.ShowOne):
# """Show the topology of the system"""
#
# @staticmethod
# def positive_non_zero_int(argument_value):
# if argument_value is None:
# return None
# try:
# value = int(argument_value)
# except ValueError:
# msg = "%s must be an integer" % argument_value
# raise argparse.ArgumentTypeError(msg)
# if value <= 0:
# msg = "%s must be greater than 0" % argument_value
# raise argparse.ArgumentTypeError(msg)
# return value
#
# def get_parser(self, prog_name):
# parser = super(TopologyShow, self).get_parser(prog_name)
# parser.add_argument('--filter',
# metavar='<query>',
# help='query for the graph)')
#
# parser.add_argument('--limit',
# type=self.positive_non_zero_int,
# metavar='<depth>',
# help='the depth of the topology graph')
#
# parser.add_argument('--root',
# help='the root of the topology graph')
#
# parser.add_argument('--graph-type',
# choices=['tree', 'graph'],
# default='graph',
# dest='type',
# help='graph type. '
# 'Valid graph types: [tree, graph]')
#
# parser.add_argument('--all-tenants',
# default=False,
# dest='all_tenants',
# action='store_true',
# help='Shows entities of all the tenants in the '
# 'entity graph')
#
# return parser
#
# @property
# def formatter_namespace(self):
# return 'vitrageclient.formatter.show'
#
# @property
# def formatter_default(self):
# return 'json'
#
# def take_action(self, parsed_args):
# limit = parsed_args.limit
# graph_type = parsed_args.type
# query = parsed_args.filter
# root = parsed_args.root
# all_tenants = parsed_args.all_tenants
#
# if graph_type == 'graph' and limit is not None and root is None:
# raise exc.CommandError("Graph-type 'graph' "
# "requires a 'root' with 'limit'.")
#
# topology = utils.get_client(self).topology.get(limit=limit,
# graph_type=graph_type,
# query=query,
# root=root,
# all_tenants=all_tenants)
# return self.dict2columns(topology)
. Output only the next line. | formatter = DOTFormatter() |
Predict the next line after this snippet: <|code_start|> @mock.patch.object(ArgumentParser, "error")
def test_parser_topology_limit_with_a_string(self, mock_parser):
mock_parser.side_effect = self._my_parser_error_func
parser = self.topology_show.get_parser('vitrage topology show')
with ExpectedException(ArgumentTypeError,
'argument --limit: spam must be an integer'):
parser.parse_args(args=['--filter', 'bla',
'--limit', 'spam',
'--root', 'blabla',
'--graph-type', 'tree'])
def test_dot_emitter(self):
def dict2columns(data):
return zip(*sorted(data.items()))
out = io.StringIO()
formatter = DOTFormatter()
topology = json.loads(JSON_DATA)
columns, topology = dict2columns(topology)
formatter.emit_one(columns, topology, out)
self.assertEqual(DOT_DATA, out.getvalue())
def test_graphml_emitter(self):
def dict2columns(data):
return zip(*sorted(data.items()))
out = io.BytesIO()
<|code_end|>
using the current file's imports:
from argparse import ArgumentParser
from argparse import ArgumentTypeError
from unittest import mock
from testtools import ExpectedException
from vitrageclient.common.formatters import DOTFormatter
from vitrageclient.common.formatters import GraphMLFormatter
from vitrageclient.tests.cli.base import CliTestCase
from vitrageclient.v1.cli.topology import TopologyShow
import io
import json
and any relevant context from other files:
# Path: vitrageclient/common/formatters.py
# class DOTFormatter(GraphFormatter):
#
# def _write_format(self, graph, stdout):
# write_dot(graph, stdout)
#
# Path: vitrageclient/common/formatters.py
# class GraphMLFormatter(GraphFormatter):
#
# def _write_format(self, graph, stdout):
# writer = GraphMLWriter(graph=graph)
# writer.dump(stdout)
#
# Path: vitrageclient/tests/cli/base.py
# class CliTestCase(base.BaseTestCase):
#
# """Test case base class for all unit tests."""
#
# # original error method of argparse uses exit
# # I just want to raise an exception and get the error message
# # that exit outputs
# @staticmethod
# def _my_parser_error_func(message):
# raise argparse.ArgumentTypeError(message)
#
# Path: vitrageclient/v1/cli/topology.py
# class TopologyShow(show.ShowOne):
# """Show the topology of the system"""
#
# @staticmethod
# def positive_non_zero_int(argument_value):
# if argument_value is None:
# return None
# try:
# value = int(argument_value)
# except ValueError:
# msg = "%s must be an integer" % argument_value
# raise argparse.ArgumentTypeError(msg)
# if value <= 0:
# msg = "%s must be greater than 0" % argument_value
# raise argparse.ArgumentTypeError(msg)
# return value
#
# def get_parser(self, prog_name):
# parser = super(TopologyShow, self).get_parser(prog_name)
# parser.add_argument('--filter',
# metavar='<query>',
# help='query for the graph)')
#
# parser.add_argument('--limit',
# type=self.positive_non_zero_int,
# metavar='<depth>',
# help='the depth of the topology graph')
#
# parser.add_argument('--root',
# help='the root of the topology graph')
#
# parser.add_argument('--graph-type',
# choices=['tree', 'graph'],
# default='graph',
# dest='type',
# help='graph type. '
# 'Valid graph types: [tree, graph]')
#
# parser.add_argument('--all-tenants',
# default=False,
# dest='all_tenants',
# action='store_true',
# help='Shows entities of all the tenants in the '
# 'entity graph')
#
# return parser
#
# @property
# def formatter_namespace(self):
# return 'vitrageclient.formatter.show'
#
# @property
# def formatter_default(self):
# return 'json'
#
# def take_action(self, parsed_args):
# limit = parsed_args.limit
# graph_type = parsed_args.type
# query = parsed_args.filter
# root = parsed_args.root
# all_tenants = parsed_args.all_tenants
#
# if graph_type == 'graph' and limit is not None and root is None:
# raise exc.CommandError("Graph-type 'graph' "
# "requires a 'root' with 'limit'.")
#
# topology = utils.get_client(self).topology.get(limit=limit,
# graph_type=graph_type,
# query=query,
# root=root,
# all_tenants=all_tenants)
# return self.dict2columns(topology)
. Output only the next line. | formatter = GraphMLFormatter() |
Given snippet: <|code_start|> <data key="d2">2018-12-30T08:30:33Z</data>
<data key="d3">RESOURCE</data>
<data key="d4">neutron.network</data>
<data key="d5">OK</data>
<data key="d6">ACTIVE</data>
<data key="d7">a0eeca0ab2c865915e23319a2e6d0fd7</data>
<data key="d8">neutron.network</data>
<data key="d9">2018-12-31T13:44:04Z</data>
<data key="d12">public
neutron.network</data>
<data key="d10">ACTIVE</data>
<data key="d11">False</data>
<data key="d19">210140f1f5a94af99e0adf79a883b75a</data>
<data key="d13">cebf5d5b-d7b1-4cfb-86fa-f660306b4c1a</data>
<data key="d14">True</data>
</node>
<edge source="0" target="2">
<data key="d15">False</data>
<data key="d16">contains</data>
</edge>
<edge source="1" target="0">
<data key="d15">False</data>
<data key="d16">contains</data>
</edge>
</graph>
</graphml>
''' # noqa
# noinspection PyAttributeOutsideInit
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from argparse import ArgumentParser
from argparse import ArgumentTypeError
from unittest import mock
from testtools import ExpectedException
from vitrageclient.common.formatters import DOTFormatter
from vitrageclient.common.formatters import GraphMLFormatter
from vitrageclient.tests.cli.base import CliTestCase
from vitrageclient.v1.cli.topology import TopologyShow
import io
import json
and context:
# Path: vitrageclient/common/formatters.py
# class DOTFormatter(GraphFormatter):
#
# def _write_format(self, graph, stdout):
# write_dot(graph, stdout)
#
# Path: vitrageclient/common/formatters.py
# class GraphMLFormatter(GraphFormatter):
#
# def _write_format(self, graph, stdout):
# writer = GraphMLWriter(graph=graph)
# writer.dump(stdout)
#
# Path: vitrageclient/tests/cli/base.py
# class CliTestCase(base.BaseTestCase):
#
# """Test case base class for all unit tests."""
#
# # original error method of argparse uses exit
# # I just want to raise an exception and get the error message
# # that exit outputs
# @staticmethod
# def _my_parser_error_func(message):
# raise argparse.ArgumentTypeError(message)
#
# Path: vitrageclient/v1/cli/topology.py
# class TopologyShow(show.ShowOne):
# """Show the topology of the system"""
#
# @staticmethod
# def positive_non_zero_int(argument_value):
# if argument_value is None:
# return None
# try:
# value = int(argument_value)
# except ValueError:
# msg = "%s must be an integer" % argument_value
# raise argparse.ArgumentTypeError(msg)
# if value <= 0:
# msg = "%s must be greater than 0" % argument_value
# raise argparse.ArgumentTypeError(msg)
# return value
#
# def get_parser(self, prog_name):
# parser = super(TopologyShow, self).get_parser(prog_name)
# parser.add_argument('--filter',
# metavar='<query>',
# help='query for the graph)')
#
# parser.add_argument('--limit',
# type=self.positive_non_zero_int,
# metavar='<depth>',
# help='the depth of the topology graph')
#
# parser.add_argument('--root',
# help='the root of the topology graph')
#
# parser.add_argument('--graph-type',
# choices=['tree', 'graph'],
# default='graph',
# dest='type',
# help='graph type. '
# 'Valid graph types: [tree, graph]')
#
# parser.add_argument('--all-tenants',
# default=False,
# dest='all_tenants',
# action='store_true',
# help='Shows entities of all the tenants in the '
# 'entity graph')
#
# return parser
#
# @property
# def formatter_namespace(self):
# return 'vitrageclient.formatter.show'
#
# @property
# def formatter_default(self):
# return 'json'
#
# def take_action(self, parsed_args):
# limit = parsed_args.limit
# graph_type = parsed_args.type
# query = parsed_args.filter
# root = parsed_args.root
# all_tenants = parsed_args.all_tenants
#
# if graph_type == 'graph' and limit is not None and root is None:
# raise exc.CommandError("Graph-type 'graph' "
# "requires a 'root' with 'limit'.")
#
# topology = utils.get_client(self).topology.get(limit=limit,
# graph_type=graph_type,
# query=query,
# root=root,
# all_tenants=all_tenants)
# return self.dict2columns(topology)
which might include code, classes, or functions. Output only the next line. | class TopologyShowTest(CliTestCase): |
Using the snippet: <|code_start|> <data key="d6">ACTIVE</data>
<data key="d7">a0eeca0ab2c865915e23319a2e6d0fd7</data>
<data key="d8">neutron.network</data>
<data key="d9">2018-12-31T13:44:04Z</data>
<data key="d12">public
neutron.network</data>
<data key="d10">ACTIVE</data>
<data key="d11">False</data>
<data key="d19">210140f1f5a94af99e0adf79a883b75a</data>
<data key="d13">cebf5d5b-d7b1-4cfb-86fa-f660306b4c1a</data>
<data key="d14">True</data>
</node>
<edge source="0" target="2">
<data key="d15">False</data>
<data key="d16">contains</data>
</edge>
<edge source="1" target="0">
<data key="d15">False</data>
<data key="d16">contains</data>
</edge>
</graph>
</graphml>
''' # noqa
# noinspection PyAttributeOutsideInit
class TopologyShowTest(CliTestCase):
def setUp(self):
super(TopologyShowTest, self).setUp()
<|code_end|>
, determine the next line of code. You have imports:
from argparse import ArgumentParser
from argparse import ArgumentTypeError
from unittest import mock
from testtools import ExpectedException
from vitrageclient.common.formatters import DOTFormatter
from vitrageclient.common.formatters import GraphMLFormatter
from vitrageclient.tests.cli.base import CliTestCase
from vitrageclient.v1.cli.topology import TopologyShow
import io
import json
and context (class names, function names, or code) available:
# Path: vitrageclient/common/formatters.py
# class DOTFormatter(GraphFormatter):
#
# def _write_format(self, graph, stdout):
# write_dot(graph, stdout)
#
# Path: vitrageclient/common/formatters.py
# class GraphMLFormatter(GraphFormatter):
#
# def _write_format(self, graph, stdout):
# writer = GraphMLWriter(graph=graph)
# writer.dump(stdout)
#
# Path: vitrageclient/tests/cli/base.py
# class CliTestCase(base.BaseTestCase):
#
# """Test case base class for all unit tests."""
#
# # original error method of argparse uses exit
# # I just want to raise an exception and get the error message
# # that exit outputs
# @staticmethod
# def _my_parser_error_func(message):
# raise argparse.ArgumentTypeError(message)
#
# Path: vitrageclient/v1/cli/topology.py
# class TopologyShow(show.ShowOne):
# """Show the topology of the system"""
#
# @staticmethod
# def positive_non_zero_int(argument_value):
# if argument_value is None:
# return None
# try:
# value = int(argument_value)
# except ValueError:
# msg = "%s must be an integer" % argument_value
# raise argparse.ArgumentTypeError(msg)
# if value <= 0:
# msg = "%s must be greater than 0" % argument_value
# raise argparse.ArgumentTypeError(msg)
# return value
#
# def get_parser(self, prog_name):
# parser = super(TopologyShow, self).get_parser(prog_name)
# parser.add_argument('--filter',
# metavar='<query>',
# help='query for the graph)')
#
# parser.add_argument('--limit',
# type=self.positive_non_zero_int,
# metavar='<depth>',
# help='the depth of the topology graph')
#
# parser.add_argument('--root',
# help='the root of the topology graph')
#
# parser.add_argument('--graph-type',
# choices=['tree', 'graph'],
# default='graph',
# dest='type',
# help='graph type. '
# 'Valid graph types: [tree, graph]')
#
# parser.add_argument('--all-tenants',
# default=False,
# dest='all_tenants',
# action='store_true',
# help='Shows entities of all the tenants in the '
# 'entity graph')
#
# return parser
#
# @property
# def formatter_namespace(self):
# return 'vitrageclient.formatter.show'
#
# @property
# def formatter_default(self):
# return 'json'
#
# def take_action(self, parsed_args):
# limit = parsed_args.limit
# graph_type = parsed_args.type
# query = parsed_args.filter
# root = parsed_args.root
# all_tenants = parsed_args.all_tenants
#
# if graph_type == 'graph' and limit is not None and root is None:
# raise exc.CommandError("Graph-type 'graph' "
# "requires a 'root' with 'limit'.")
#
# topology = utils.get_client(self).topology.get(limit=limit,
# graph_type=graph_type,
# query=query,
# root=root,
# all_tenants=all_tenants)
# return self.dict2columns(topology)
. Output only the next line. | self.topology_show = TopologyShow(mock.Mock(), mock.Mock()) |
Given the code snippet: <|code_start|># Copyright 2017 Nokia
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in 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.
# noinspection PyPackageRequirements
# noinspection PyAttributeOutsideInit
class EventPostTest(CliTestCase):
def setUp(self):
super(EventPostTest, self).setUp()
self.app = mock.Mock()
<|code_end|>
, generate the next line using the imports in this file:
from argparse import ArgumentParser
from argparse import ArgumentTypeError
from unittest import mock
from datetime import datetime
from testtools import ExpectedException
from vitrageclient.tests.cli.base import CliTestCase
from vitrageclient.v1.cli.event import EventPost
and context (functions, classes, or occasionally code) from other files:
# Path: vitrageclient/tests/cli/base.py
# class CliTestCase(base.BaseTestCase):
#
# """Test case base class for all unit tests."""
#
# # original error method of argparse uses exit
# # I just want to raise an exception and get the error message
# # that exit outputs
# @staticmethod
# def _my_parser_error_func(message):
# raise argparse.ArgumentTypeError(message)
#
# Path: vitrageclient/v1/cli/event.py
# class EventPost(command.Command):
# """Post an event to Vitrage"""
#
# @staticmethod
# def iso8601(argument_value):
# try:
# if argument_value:
# iso8601.parse_date(argument_value)
# except ParseError:
# msg = "%s must be an iso8601 date" % argument_value
# raise argparse.ArgumentTypeError(msg)
#
# def get_parser(self, prog_name):
# parser = super(EventPost, self).get_parser(prog_name)
#
# parser.add_argument('--type',
# required=True,
# help='The type of the event')
#
# parser.add_argument('--time',
# default='',
# type=self.iso8601,
# help='The timestamp of the event in ISO 8601 '
# 'format: YYYY-MM-DDTHH:MM:SS.mmmmmm. '
# 'If not specified, the current time is used')
#
# parser.add_argument('--details',
# default='{}',
# help='A json string with the event details')
#
# return parser
#
# def take_action(self, parsed_args):
#
# if parsed_args.time:
# event_time = parsed_args.time
# else:
# event_time = datetime.now().isoformat()
#
# event_type = parsed_args.type
# details = parsed_args.details
#
# self.app.client.event.post(event_time=event_time,
# event_type=event_type,
# details=json.loads(details))
. Output only the next line. | self.event_post = EventPost(self.app, mock.Mock()) |
Using the snippet: <|code_start|>
# noinspection PyAbstractClass
class RcaShow(show.ShowOne):
"""Show the Root Cause Analysis for a certain alarm"""
def get_parser(self, prog_name):
parser = super(RcaShow, self).get_parser(prog_name)
parser.add_argument('alarm_vitrage_id',
help='ID of an alarm')
parser.add_argument('--all-tenants',
default=False,
dest='all_tenants',
action='store_true',
help='Shows alarms of all the tenants for the RCA')
return parser
@property
def formatter_namespace(self):
return 'vitrageclient.formatter.show'
@property
def formatter_default(self):
return 'json'
def take_action(self, parsed_args):
alarm_id = parsed_args.alarm_vitrage_id
all_tenants = parsed_args.all_tenants
<|code_end|>
, determine the next line of code. You have imports:
from cliff import show
from vitrageclient.common import utils
and context (class names, function names, or code) available:
# Path: vitrageclient/common/utils.py
# def args_to_dict(args, attrs):
# def list2cols(cols, objs):
# def list2cols_with_rename(names_and_keys, objs):
# def get_client(obj):
# def wait_for_action_to_end(timeout, func, **kwargs):
# def find_template_with_uuid(uuid, templates):
. Output only the next line. | alarm = utils.get_client(self).rca.get(alarm_id=alarm_id, |
Given snippet: <|code_start|># under the License.
profiler_web = importutils.try_import('osprofiler.web')
# noinspection PyPep8Naming
def Client(version, *args, **kwargs):
module = importutils.import_versioned_module('vitrageclient',
version, 'client')
client_class = getattr(module, 'Client')
return client_class(*args, **kwargs)
class VitrageClient(keystoneauth.Adapter):
def request(self, url, method, **kwargs):
headers = kwargs.setdefault('headers', {})
headers.setdefault('Accept', 'application/json')
if profiler_web:
# no header will be added if profiler is not initialized
headers.update(profiler_web.get_trace_id_headers())
raise_exc = kwargs.pop('raise_exc', True)
resp = super(VitrageClient, self).request(url, method,
raise_exc=False,
**kwargs)
if raise_exc and resp.status_code >= 400:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from vitrageclient import exceptions as exc
from keystoneauth1 import adapter as keystoneauth
from oslo_utils import importutils
and context:
# Path: vitrageclient/exceptions.py
# class CommandError(Exception):
# class ClientException(Exception):
# def __init__(self, code, message=None, request_id=None,
# url=None, method=None):
# def __str__(self):
# def from_response(resp, url, method):
which might include code, classes, or functions. Output only the next line. | raise exc.from_response(resp, url, method) |
Given the following code snippet before the placeholder: <|code_start|> parser.add_argument("vitrage_id",
default='all',
nargs='?',
metavar="<vitrage id>",
help="Vitrage id of the affected resource")
parser.add_argument('--all-tenants',
default=False,
dest='all_tenants',
action='store_true',
help='Shows alarms of all the tenants in the '
'entity graph')
parser.add_argument('--limit',
dest='limit',
help='Maximal number of alarms to show. Default '
'is 1000')
parser.add_argument('--marker',
dest='marker',
help='Marker for the next page')
return parser
def take_action(self, parsed_args):
vitrage_id = parsed_args.vitrage_id
all_tenants = parsed_args.all_tenants
limit = parsed_args.limit
marker = parsed_args.marker
<|code_end|>
, predict the next line using imports from the current file:
from cliff import lister
from cliff import show
from vitrageclient.common import utils
from vitrageclient import exceptions as exc
and context including class names, function names, and sometimes code from other files:
# Path: vitrageclient/common/utils.py
# def args_to_dict(args, attrs):
# def list2cols(cols, objs):
# def list2cols_with_rename(names_and_keys, objs):
# def get_client(obj):
# def wait_for_action_to_end(timeout, func, **kwargs):
# def find_template_with_uuid(uuid, templates):
#
# Path: vitrageclient/exceptions.py
# class CommandError(Exception):
# class ClientException(Exception):
# def __init__(self, code, message=None, request_id=None,
# url=None, method=None):
# def __str__(self):
# def from_response(resp, url, method):
. Output only the next line. | alarms = utils.get_client(self).alarm.list(vitrage_id=vitrage_id, |
Using the snippet: <|code_start|> help='Shows alarms of all the tenants in the '
'entity graph')
parser.add_argument('--limit',
dest='limit',
help='Maximal number of alarms to show. Default '
'is 1000')
parser.add_argument('--marker',
dest='marker',
help='Marker for the next page')
parser.add_argument('--start',
dest='start',
help='list alarm from this date')
parser.add_argument('--end',
dest='end',
help='list alarm until this date')
return parser
def take_action(self, parsed_args):
all_tenants = parsed_args.all_tenants
limit = parsed_args.limit
marker = parsed_args.marker
start = parsed_args.start
end = parsed_args.end
if end and not start:
<|code_end|>
, determine the next line of code. You have imports:
from cliff import lister
from cliff import show
from vitrageclient.common import utils
from vitrageclient import exceptions as exc
and context (class names, function names, or code) available:
# Path: vitrageclient/common/utils.py
# def args_to_dict(args, attrs):
# def list2cols(cols, objs):
# def list2cols_with_rename(names_and_keys, objs):
# def get_client(obj):
# def wait_for_action_to_end(timeout, func, **kwargs):
# def find_template_with_uuid(uuid, templates):
#
# Path: vitrageclient/exceptions.py
# class CommandError(Exception):
# class ClientException(Exception):
# def __init__(self, code, message=None, request_id=None,
# url=None, method=None):
# def __str__(self):
# def from_response(resp, url, method):
. Output only the next line. | raise exc.CommandError("--end argument must be used with --start") |
Using the snippet: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in 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.
# noinspection PyAbstractClass
class ResourceShow(show.ShowOne):
"""Show a resource"""
def get_parser(self, prog_name):
parser = super(ResourceShow, self).get_parser(prog_name)
parser.add_argument('vitrage_id', help='vitrage_id of a resource')
return parser
def take_action(self, parsed_args):
vitrage_id = parsed_args.vitrage_id
<|code_end|>
, determine the next line of code. You have imports:
from cliff import lister
from cliff import show
from vitrageclient.common import utils
and context (class names, function names, or code) available:
# Path: vitrageclient/common/utils.py
# def args_to_dict(args, attrs):
# def list2cols(cols, objs):
# def list2cols_with_rename(names_and_keys, objs):
# def get_client(obj):
# def wait_for_action_to_end(timeout, func, **kwargs):
# def find_template_with_uuid(uuid, templates):
. Output only the next line. | resource = utils.get_client(self).resource.get(vitrage_id=vitrage_id) |
Continue the code snippet: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in 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.
# noinspection PyAbstractClass
class WebhookShow(show.ShowOne):
"""Show a webhook """
def get_parser(self, prog_name):
parser = super(WebhookShow, self).get_parser(prog_name)
parser.add_argument('id', help='id of webhook to show')
return parser
def take_action(self, parsed_args):
id = parsed_args.id
<|code_end|>
. Use current file imports:
from cliff import lister
from cliff import show
from vitrageclient.common import utils
and context (classes, functions, or code) from other files:
# Path: vitrageclient/common/utils.py
# def args_to_dict(args, attrs):
# def list2cols(cols, objs):
# def list2cols_with_rename(names_and_keys, objs):
# def get_client(obj):
# def wait_for_action_to_end(timeout, func, **kwargs):
# def find_template_with_uuid(uuid, templates):
. Output only the next line. | webhook = utils.get_client(self).webhook.show(id=id) |
Predict the next line for this snippet: <|code_start|> self._load_template(path=path, template_str=template_str)
api_params = dict(templates=files_content,
template_type=template_type,
params=params)
return self.api.post(self.url, json=api_params).json()
@classmethod
def _load_yaml_files(cls, path):
if os.path.isdir(path):
files_content = []
for file_name in os.listdir(path):
file_path = '%s/%s' % (path, file_name)
if os.path.isfile(file_path):
template = cls._load_yaml_file(file_path)
files_content.append((file_path, template))
else:
files_content = [(path, cls._load_yaml_file(path))]
return files_content
@classmethod
def _load_yaml_file(cls, path):
with open(path, 'r') as stream:
return cls._load_yaml(stream)
@classmethod
def _load_yaml(cls, yaml_content):
try:
<|code_end|>
with the help of current file imports:
import os
from vitrageclient.common import yaml_utils
from vitrageclient import exceptions as exc
and context from other files:
# Path: vitrageclient/common/yaml_utils.py
# def load(stream):
#
# Path: vitrageclient/exceptions.py
# class CommandError(Exception):
# class ClientException(Exception):
# def __init__(self, code, message=None, request_id=None,
# url=None, method=None):
# def __str__(self):
# def from_response(resp, url, method):
, which may contain function names, class names, or code. Output only the next line. | return yaml_utils.load(yaml_content) |
Using the snippet: <|code_start|> return self.api.post(self.url, json=api_params).json()
@classmethod
def _load_yaml_files(cls, path):
if os.path.isdir(path):
files_content = []
for file_name in os.listdir(path):
file_path = '%s/%s' % (path, file_name)
if os.path.isfile(file_path):
template = cls._load_yaml_file(file_path)
files_content.append((file_path, template))
else:
files_content = [(path, cls._load_yaml_file(path))]
return files_content
@classmethod
def _load_yaml_file(cls, path):
with open(path, 'r') as stream:
return cls._load_yaml(stream)
@classmethod
def _load_yaml(cls, yaml_content):
try:
return yaml_utils.load(yaml_content)
except ValueError as e:
message = 'Could not load template: %s. Reason: %s' \
% (yaml_content, e)
<|code_end|>
, determine the next line of code. You have imports:
import os
from vitrageclient.common import yaml_utils
from vitrageclient import exceptions as exc
and context (class names, function names, or code) available:
# Path: vitrageclient/common/yaml_utils.py
# def load(stream):
#
# Path: vitrageclient/exceptions.py
# class CommandError(Exception):
# class ClientException(Exception):
# def __init__(self, code, message=None, request_id=None,
# url=None, method=None):
# def __str__(self):
# def from_response(resp, url, method):
. Output only the next line. | raise exc.CommandError(message) |
Next line prediction: <|code_start|> online_funcs.extend(['http.client.HTTPConnection.request',
'http.client.HTTPSConnection.request'])
for func in online_funcs:
monkeypatch.setattr(func, mock.Mock(side_effect=Exception('Online tests should use @pytest.mark.online')))
@pytest.fixture
def credentials():
return {
'application_id': os.environ.get('RAKUTEN_APP_ID', '<RAKUTEN_APP_ID>'),
'license_key': os.environ.get('RMS_LICENSE_KEY', '<RMS_LICENSE_KEY>'),
'secret_service': os.environ.get('RMS_SECRET_SERVICE', '<RMS_SECRET_SERVICE>'),
'shop_url': os.environ.get('RMS_SHOP_URL', '<RMS_SHOP_URL>'),
}
@pytest.fixture
def fake_credentials():
return {
'application_id': '<RAKUTEN_APP_ID>',
'license_key': '<RMS_LICENSE_KEY>',
'secret_service': '<RMS_SECRET_SERVICE>',
'shop_url': '<RMS_SHOP_URL>',
}
@pytest.fixture
def ws(credentials, request):
ws_debug = request.config.getoption("--ws-debug")
<|code_end|>
. Use current file imports:
(import re
import os
import sys
import json
import mock
import pytest
import httpretty as httpretty_module
from vcr import VCR
from rakuten_ws import RakutenWebService)
and context including class names, function names, or small code snippets from other files:
# Path: rakuten_ws/webservice.py
# class RakutenWebService(BaseWebService):
#
# rms = RmsService()
#
# ichiba = IchibaAPI()
# books = BooksAPI()
# travel = TravelAPI()
# auction = AuctionAPI()
# kobo = KoboAPI()
# gora = GoraAPI()
# recipe = RecipeAPI()
# other = OtherAPI()
. Output only the next line. | return RakutenWebService(debug=ws_debug, **credentials) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.