Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Given the code snippet: <|code_start|> class Lyrics(list): """A list that holds the contents of the lrc file""" def __init__(self, items=[]): self.artist = "" self.album = "" self.title = "" self.author = "" self.length = "" self.offset = "" self.extend(items) def is_enhanced_lrc(self): """ Checks if the subs is an enhanced lrc """ for sub in self: word = '<' + sub.text.split('<')[-1] <|code_end|> , generate the next line using the imports in this file: from .tools.timecode import is_timecode, timecode_to_srt from .tools.find_even_split import find_even_split and context (functions, classes, or occasionally code) from other files: # Path: operators/pylrc/tools/timecode.py # def is_timecode(timecode): # """Checks if a string is a proper lrc timecode""" # # timecode = timecode.replace('<', '[').replace('>', ']') # try: # x = datetime.strptime(timecode, '[%M:%S.%f]') # return True # # except ValueError: # return False # # def timecode_to_srt(timecode): # """convert timecode of format [MM:SS.ff] to an srt format timecode""" # secs = timecode_to_seconds(timecode) # # hours = "00" # minutes = "%02d" % int(secs / 60) # seconds = "%02d" % int(secs % 60) # millis = "%03d" % (round(secs - int(secs), 2) * 1000) # # return ''.join([hours, ':', minutes, ':', seconds, ',', millis]) # # Path: operators/pylrc/tools/find_even_split.py # def find_even_split(line): # """ # Given a string, splits it into two (almost) evenly spaced lines # """ # word_list = line.split(' ') # differences = [] # for i in range(len(word_list)): # group1 = ' '.join(word_list[0:i + 1]) # group2 = ' '.join(word_list[i + 1::]) # differences.append(abs(len(group1) - len(group2))) # index = differences.index(min(differences)) # for i in range(len(word_list)): # if i == index: # group1 = ' '.join(word_list[0:i+1]) # group2 = ' '.join(word_list[i+1::]) # # return ''.join([group1, '\n', group2]).rstrip() . Output only the next line.
if is_timecode(word[0:10]):
Based on the snippet: <|code_start|> else: srt = srt + self[i].text + '\n' output.append(srt) return '\n'.join(output).rstrip() def to_ESRT(self): """Convert ELRC to ESRT""" output = [] for i in range(len(self) - 1): sub_list = [] if not self[i].text == '': text = self[i].text base_text = self[i].text_without_tags if len(base_text) > 31: base_text = find_even_split(base_text) if not is_timecode(text[0:10]): time = self[i].lrc_time time = time.replace('[', '<').replace(']', '>') text = time + text if not is_timecode(text[-10::]): time = self[i + 1].lrc_time time = time.replace('[', '<').replace(']', '>') text = text + time if not text[0:10].replace('<', '[').replace('>', ']') == self[i].lrc_time: start = self[i].srt_time <|code_end|> , predict the immediate next line with the help of imports: from .tools.timecode import is_timecode, timecode_to_srt from .tools.find_even_split import find_even_split and context (classes, functions, sometimes code) from other files: # Path: operators/pylrc/tools/timecode.py # def is_timecode(timecode): # """Checks if a string is a proper lrc timecode""" # # timecode = timecode.replace('<', '[').replace('>', ']') # try: # x = datetime.strptime(timecode, '[%M:%S.%f]') # return True # # except ValueError: # return False # # def timecode_to_srt(timecode): # """convert timecode of format [MM:SS.ff] to an srt format timecode""" # secs = timecode_to_seconds(timecode) # # hours = "00" # minutes = "%02d" % int(secs / 60) # seconds = "%02d" % int(secs % 60) # millis = "%03d" % (round(secs - int(secs), 2) * 1000) # # return ''.join([hours, ':', minutes, ':', seconds, ',', millis]) # # Path: operators/pylrc/tools/find_even_split.py # def find_even_split(line): # """ # Given a string, splits it into two (almost) evenly spaced lines # """ # word_list = line.split(' ') # differences = [] # for i in range(len(word_list)): # group1 = ' '.join(word_list[0:i + 1]) # group2 = ' '.join(word_list[i + 1::]) # differences.append(abs(len(group1) - len(group2))) # index = differences.index(min(differences)) # for i in range(len(word_list)): # if i == index: # group1 = ' '.join(word_list[0:i+1]) # group2 = ' '.join(word_list[i+1::]) # # return ''.join([group1, '\n', group2]).rstrip() . Output only the next line.
end = timecode_to_srt(text[0:10])
Predict the next line after this snippet: <|code_start|> Checks if the subs is an enhanced lrc """ for sub in self: word = '<' + sub.text.split('<')[-1] if is_timecode(word[0:10]): return True return False def to_SRT(self): """Returns an SRT string of the LRC data""" if not self[-1].text.rstrip() == "": timecode = self[-1].lrc_timecode end_line = LyricLine(timecode, "") end_line.shift(seconds=5) self.append(end_line) if self.is_enhanced_lrc(): return self.to_ESRT() output = [] srt = "" for i in range(len(self) - 1): if not self[i].text == '': srt = str(i + 1) + '\n' start_timecode = self[i].srt_time end_timecode = self[i + 1].srt_time srt = srt + start_timecode + ' --> ' + end_timecode + '\n' if len(self[i].text) > 31: <|code_end|> using the current file's imports: from .tools.timecode import is_timecode, timecode_to_srt from .tools.find_even_split import find_even_split and any relevant context from other files: # Path: operators/pylrc/tools/timecode.py # def is_timecode(timecode): # """Checks if a string is a proper lrc timecode""" # # timecode = timecode.replace('<', '[').replace('>', ']') # try: # x = datetime.strptime(timecode, '[%M:%S.%f]') # return True # # except ValueError: # return False # # def timecode_to_srt(timecode): # """convert timecode of format [MM:SS.ff] to an srt format timecode""" # secs = timecode_to_seconds(timecode) # # hours = "00" # minutes = "%02d" % int(secs / 60) # seconds = "%02d" % int(secs % 60) # millis = "%03d" % (round(secs - int(secs), 2) * 1000) # # return ''.join([hours, ':', minutes, ':', seconds, ',', millis]) # # Path: operators/pylrc/tools/find_even_split.py # def find_even_split(line): # """ # Given a string, splits it into two (almost) evenly spaced lines # """ # word_list = line.split(' ') # differences = [] # for i in range(len(word_list)): # group1 = ' '.join(word_list[0:i + 1]) # group2 = ' '.join(word_list[i + 1::]) # differences.append(abs(len(group1) - len(group2))) # index = differences.index(min(differences)) # for i in range(len(word_list)): # if i == index: # group1 = ' '.join(word_list[0:i+1]) # group2 = ' '.join(word_list[i+1::]) # # return ''.join([group1, '\n', group2]).rstrip() . Output only the next line.
srt = srt + find_even_split(self[i].text) + '\n'
Predict the next line for this snippet: <|code_start|> @classmethod def stream(cls, source_file, error_handling=ERROR_PASS): """ stream(source_file, [error_handling]) This method yield SubRipItem instances a soon as they have been parsed without storing them. It is a kind of SAX parser for .srt files. `source_file` -> Any iterable that yield unicode strings, like a file opened with `codecs.open()` or an array of unicode. Example: >>> import pysrt >>> import codecs >>> file = codecs.open('movie.srt', encoding='utf-8') >>> for sub in pysrt.stream(file): ... sub.text += "\nHello !" ... print unicode(sub) """ string_buffer = [] for index, line in enumerate(chain(source_file, '\n')): if line.strip(): string_buffer.append(line) else: source = string_buffer string_buffer = [] if source and all(source): try: yield SubRipItem.from_lines(source) <|code_end|> with the help of current file imports: import os import sys import codecs from collections import UserList from UserList import UserList from itertools import chain from copy import copy from .srtexc import Error from .srtitem import SubRipItem from .compat import str and context from other files: # Path: operators/pysrt/srtexc.py # class Error(Exception): # """ # Pysrt's base exception # """ # pass # # Path: operators/pysrt/srtitem.py # class SubRipItem(ComparableMixin): # """ # SubRipItem(index, start, end, text, position) # # index -> int: index of item in file. 0 by default. # start, end -> SubRipTime or coercible. # text -> unicode: text content for item. # position -> unicode: raw srt/vtt "display coordinates" string # """ # ITEM_PATTERN = str('%s\n%s --> %s%s\n%s\n') # TIMESTAMP_SEPARATOR = '-->' # # def __init__(self, index=0, start=None, end=None, text='', position=''): # try: # self.index = int(index) # except (TypeError, ValueError): # try to cast as int, but it's not mandatory # self.index = index # # self.start = SubRipTime.coerce(start or 0) # self.end = SubRipTime.coerce(end or 0) # self.position = str(position) # self.text = str(text) # # @property # def duration(self): # return self.end - self.start # # @property # def text_without_tags(self): # RE_TAG = re.compile(r'<[^>]*?>') # return RE_TAG.sub('', self.text) # # @property # def characters_per_second(self): # characters_count = len(self.text_without_tags.replace('\n', '')) # try: # return characters_count / (self.duration.ordinal / 1000.0) # except ZeroDivisionError: # return 0.0 # # def __str__(self): # position = ' %s' % self.position if self.position.strip() else '' # return self.ITEM_PATTERN % (self.index, self.start, self.end, # position, self.text) # if is_py2: # __unicode__ = __str__ # # def __str__(self): # raise NotImplementedError('Use unicode() instead!') # # def _cmpkey(self): # return (self.start, self.end) # # def shift(self, *args, **kwargs): # """ # shift(hours, minutes, seconds, milliseconds, ratio) # # Add given values to start and end attributes. # All arguments are optional and have a default value of 0. # """ # self.start.shift(*args, **kwargs) # self.end.shift(*args, **kwargs) # # @classmethod # def from_string(cls, source): # return cls.from_lines(source.splitlines(True)) # # @classmethod # def from_lines(cls, lines): # if len(lines) < 2: # raise InvalidItem() # lines = [l.rstrip() for l in lines] # index = None # if cls.TIMESTAMP_SEPARATOR not in lines[0]: # index = lines.pop(0) # start, end, position = cls.split_timestamps(lines[0]) # body = '\n'.join(lines[1:]) # return cls(index, start, end, body, position) # # @classmethod # def split_timestamps(cls, line): # timestamps = line.split(cls.TIMESTAMP_SEPARATOR) # if len(timestamps) != 2: # raise InvalidItem() # start, end_and_position = timestamps # end_and_position = end_and_position.lstrip().split(' ', 1) # end = end_and_position[0] # position = end_and_position[1] if len(end_and_position) > 1 else '' # return (s.strip() for s in (start, end, position)) , which may contain function names, class names, or code. Output only the next line.
except Error as error:
Predict the next line after this snippet: <|code_start|> return self @classmethod def stream(cls, source_file, error_handling=ERROR_PASS): """ stream(source_file, [error_handling]) This method yield SubRipItem instances a soon as they have been parsed without storing them. It is a kind of SAX parser for .srt files. `source_file` -> Any iterable that yield unicode strings, like a file opened with `codecs.open()` or an array of unicode. Example: >>> import pysrt >>> import codecs >>> file = codecs.open('movie.srt', encoding='utf-8') >>> for sub in pysrt.stream(file): ... sub.text += "\nHello !" ... print unicode(sub) """ string_buffer = [] for index, line in enumerate(chain(source_file, '\n')): if line.strip(): string_buffer.append(line) else: source = string_buffer string_buffer = [] if source and all(source): try: <|code_end|> using the current file's imports: import os import sys import codecs from collections import UserList from UserList import UserList from itertools import chain from copy import copy from .srtexc import Error from .srtitem import SubRipItem from .compat import str and any relevant context from other files: # Path: operators/pysrt/srtexc.py # class Error(Exception): # """ # Pysrt's base exception # """ # pass # # Path: operators/pysrt/srtitem.py # class SubRipItem(ComparableMixin): # """ # SubRipItem(index, start, end, text, position) # # index -> int: index of item in file. 0 by default. # start, end -> SubRipTime or coercible. # text -> unicode: text content for item. # position -> unicode: raw srt/vtt "display coordinates" string # """ # ITEM_PATTERN = str('%s\n%s --> %s%s\n%s\n') # TIMESTAMP_SEPARATOR = '-->' # # def __init__(self, index=0, start=None, end=None, text='', position=''): # try: # self.index = int(index) # except (TypeError, ValueError): # try to cast as int, but it's not mandatory # self.index = index # # self.start = SubRipTime.coerce(start or 0) # self.end = SubRipTime.coerce(end or 0) # self.position = str(position) # self.text = str(text) # # @property # def duration(self): # return self.end - self.start # # @property # def text_without_tags(self): # RE_TAG = re.compile(r'<[^>]*?>') # return RE_TAG.sub('', self.text) # # @property # def characters_per_second(self): # characters_count = len(self.text_without_tags.replace('\n', '')) # try: # return characters_count / (self.duration.ordinal / 1000.0) # except ZeroDivisionError: # return 0.0 # # def __str__(self): # position = ' %s' % self.position if self.position.strip() else '' # return self.ITEM_PATTERN % (self.index, self.start, self.end, # position, self.text) # if is_py2: # __unicode__ = __str__ # # def __str__(self): # raise NotImplementedError('Use unicode() instead!') # # def _cmpkey(self): # return (self.start, self.end) # # def shift(self, *args, **kwargs): # """ # shift(hours, minutes, seconds, milliseconds, ratio) # # Add given values to start and end attributes. # All arguments are optional and have a default value of 0. # """ # self.start.shift(*args, **kwargs) # self.end.shift(*args, **kwargs) # # @classmethod # def from_string(cls, source): # return cls.from_lines(source.splitlines(True)) # # @classmethod # def from_lines(cls, lines): # if len(lines) < 2: # raise InvalidItem() # lines = [l.rstrip() for l in lines] # index = None # if cls.TIMESTAMP_SEPARATOR not in lines[0]: # index = lines.pop(0) # start, end, position = cls.split_timestamps(lines[0]) # body = '\n'.join(lines[1:]) # return cls(index, start, end, body, position) # # @classmethod # def split_timestamps(cls, line): # timestamps = line.split(cls.TIMESTAMP_SEPARATOR) # if len(timestamps) != 2: # raise InvalidItem() # start, end_and_position = timestamps # end_and_position = end_and_position.lstrip().split(' ', 1) # end = end_and_position[0] # position = end_and_position[1] if len(end_and_position) > 1 else '' # return (s.strip() for s in (start, end, position)) . Output only the next line.
yield SubRipItem.from_lines(source)
Based on the snippet: <|code_start|> if len(text_strips) > 0: return True else: return False except AttributeError: return False def execute(self, context): scene = context.scene words = collect_words(scene) found_words = [] not_founds = [] if scene.use_dictionary_syllabification: dictionary = get_dictionary( lang=scene.syllabification_language) for i in range(len(words)): try: words[i] = dictionary[words[i]] found_words.append(words[i]) except KeyError: not_founds.append(words[i]) if len(not_founds) > 0: print('=================\nNot in Dictionary\n=================') not_founds = list(set(not_founds)) for i in range(len(not_founds)): print(not_founds[i].encode('ascii', errors='replace').decode('ascii')) if scene.use_algorithmic_syllabification: <|code_end|> , predict the immediate next line with the help of imports: import bpy import os from bpy_extras.io_utils import ExportHelper from .hyphenator.hyphenator import Hyphenator from .hyphenator.get_dictionary import get_dictionary from .tools.get_text_strips import get_text_strips from .tools.remove_punctuation import remove_punctuation and context (classes, functions, sometimes code) from other files: # Path: operators/hyphenator/hyphenator.py # class Hyphenator: # def __init__(self): # self.tree = {} # self.patterns = "" # self.text_exceptions = "" # # def setup_patterns(self): # for pattern in self.patterns.split(): # self._insert_pattern(pattern) # # self.exceptions = {} # for ex in self.text_exceptions.split(): # # Convert the hyphenated pattern into a point array for use later. # self.exceptions[ex.replace('-', '')] = [0] + [ int(h == '-') for h in re.split(r"[a-z]", ex) ] # # def _insert_pattern(self, pattern): # # Convert the a pattern like 'a1bc3d4' into a string of chars 'abcd' # # and a list of points [ 0, 1, 0, 3, 4 ]. # chars = re.sub('[0-9]', '', pattern) # points = [ int(d or 0) for d in re.split("[.a-z]", pattern) ] # # # Insert the pattern into the tree. Each character finds a dict # # another level down in the tree, and leaf nodes have the list of # # points. # t = self.tree # for c in chars: # if c not in t: # t[c] = {} # t = t[c] # t[None] = points # # def hyphenate_word(self, word): # """ Given a word, returns a list of pieces, broken at the possible # hyphenation points. # """ # # If the word is an exception, get the stored points. # if word.lower() in self.exceptions: # points = self.exceptions[word.lower()] # else: # work = '.' + word.lower() + '.' # points = [0] * (len(work)+1) # for i in range(len(work)): # t = self.tree # for c in work[i:]: # if c in t: # t = t[c] # if None in t: # p = t[None] # for j in range(len(p)): # points[i+j] = max(points[i+j], p[j]) # else: # break # # No hyphens in the first two chars or the last two. # points[1] = points[2] = points[-2] = points[-3] = 0 # # # Examine the points to build the pieces list. # pieces = [''] # for c, p in zip(word, points[2:]): # pieces[-1] += c # if p % 2: # pieces.append('') # return pieces # # Path: operators/hyphenator/get_dictionary.py # def get_dictionary(dic_path=None, lang='en-us'): # """Collect the words from the default dictionary""" # # if dic_path == None: # module_path = os.path.dirname(__file__) # dic_path = os.path.join(module_path, 'dictionaries', lang + '.txt') # # dictionary = {} # # try: # f = open(dic_path, 'r') # lines = f.readlines() # f.close() # # for line in lines: # word = line.rstrip().replace(' ', '') # dictionary[word] = line.rstrip() # # except FileNotFoundError: # dictionary = {} # # return dictionary # # Path: operators/tools/get_text_strips.py # def get_text_strips(scene, channel=None): # """Get all the text strips in the edit channel""" # # if channel == None: # channel = scene.subtitle_edit_channel # # all_strips = list(sorted(scene.sequence_editor.sequences, # key=lambda x: x.frame_start)) # # text_strips = [] # for strip in all_strips: # if (strip.channel == channel and # strip.type == 'TEXT'): # text_strips.append(strip) # # return text_strips # # Path: operators/tools/remove_punctuation.py # def remove_punctuation(word): # """Remove punctuation from the beginning and end of a word""" # # puncs = ['\\', '/', ':', '*', '?', '"', '<', '>', '|', '\n', '(', # ')', '!', '@', '#', '$', '%', '^', '-', '+', '=', "'", # ';', ',', '.', '{', '}','[', ']'] # # while len(word) > 0 and word[0] in puncs: # word = word[1::] # # while len(word) > 0 and word[-1] in puncs: # word = word[0:-1] # # return word . Output only the next line.
hyphenator = Hyphenator()
Here is a snippet: <|code_start|> class SEQUENCER_OT_syllabify(bpy.types.Operator, ExportHelper): bl_label = 'Syllabify' bl_idname = 'sequencerextra.syllabify' bl_description = "Create a list of words, separated by syllables.\nNeeded for splitting words with accurate syllable differentiation" filename_ext = ".txt" @classmethod def poll(self, context): scene = context.scene try: text_strips = get_text_strips(scene) if len(text_strips) > 0: return True else: return False except AttributeError: return False def execute(self, context): scene = context.scene words = collect_words(scene) found_words = [] not_founds = [] if scene.use_dictionary_syllabification: <|code_end|> . Write the next line using the current file imports: import bpy import os from bpy_extras.io_utils import ExportHelper from .hyphenator.hyphenator import Hyphenator from .hyphenator.get_dictionary import get_dictionary from .tools.get_text_strips import get_text_strips from .tools.remove_punctuation import remove_punctuation and context from other files: # Path: operators/hyphenator/hyphenator.py # class Hyphenator: # def __init__(self): # self.tree = {} # self.patterns = "" # self.text_exceptions = "" # # def setup_patterns(self): # for pattern in self.patterns.split(): # self._insert_pattern(pattern) # # self.exceptions = {} # for ex in self.text_exceptions.split(): # # Convert the hyphenated pattern into a point array for use later. # self.exceptions[ex.replace('-', '')] = [0] + [ int(h == '-') for h in re.split(r"[a-z]", ex) ] # # def _insert_pattern(self, pattern): # # Convert the a pattern like 'a1bc3d4' into a string of chars 'abcd' # # and a list of points [ 0, 1, 0, 3, 4 ]. # chars = re.sub('[0-9]', '', pattern) # points = [ int(d or 0) for d in re.split("[.a-z]", pattern) ] # # # Insert the pattern into the tree. Each character finds a dict # # another level down in the tree, and leaf nodes have the list of # # points. # t = self.tree # for c in chars: # if c not in t: # t[c] = {} # t = t[c] # t[None] = points # # def hyphenate_word(self, word): # """ Given a word, returns a list of pieces, broken at the possible # hyphenation points. # """ # # If the word is an exception, get the stored points. # if word.lower() in self.exceptions: # points = self.exceptions[word.lower()] # else: # work = '.' + word.lower() + '.' # points = [0] * (len(work)+1) # for i in range(len(work)): # t = self.tree # for c in work[i:]: # if c in t: # t = t[c] # if None in t: # p = t[None] # for j in range(len(p)): # points[i+j] = max(points[i+j], p[j]) # else: # break # # No hyphens in the first two chars or the last two. # points[1] = points[2] = points[-2] = points[-3] = 0 # # # Examine the points to build the pieces list. # pieces = [''] # for c, p in zip(word, points[2:]): # pieces[-1] += c # if p % 2: # pieces.append('') # return pieces # # Path: operators/hyphenator/get_dictionary.py # def get_dictionary(dic_path=None, lang='en-us'): # """Collect the words from the default dictionary""" # # if dic_path == None: # module_path = os.path.dirname(__file__) # dic_path = os.path.join(module_path, 'dictionaries', lang + '.txt') # # dictionary = {} # # try: # f = open(dic_path, 'r') # lines = f.readlines() # f.close() # # for line in lines: # word = line.rstrip().replace(' ', '') # dictionary[word] = line.rstrip() # # except FileNotFoundError: # dictionary = {} # # return dictionary # # Path: operators/tools/get_text_strips.py # def get_text_strips(scene, channel=None): # """Get all the text strips in the edit channel""" # # if channel == None: # channel = scene.subtitle_edit_channel # # all_strips = list(sorted(scene.sequence_editor.sequences, # key=lambda x: x.frame_start)) # # text_strips = [] # for strip in all_strips: # if (strip.channel == channel and # strip.type == 'TEXT'): # text_strips.append(strip) # # return text_strips # # Path: operators/tools/remove_punctuation.py # def remove_punctuation(word): # """Remove punctuation from the beginning and end of a word""" # # puncs = ['\\', '/', ':', '*', '?', '"', '<', '>', '|', '\n', '(', # ')', '!', '@', '#', '$', '%', '^', '-', '+', '=', "'", # ';', ',', '.', '{', '}','[', ']'] # # while len(word) > 0 and word[0] in puncs: # word = word[1::] # # while len(word) > 0 and word[-1] in puncs: # word = word[0:-1] # # return word , which may include functions, classes, or code. Output only the next line.
dictionary = get_dictionary(
Predict the next line after this snippet: <|code_start|> def collect_words(scene): """Collect, clean, and alphabetize the words in the subtitles""" words = [] text_strips = get_text_strips(scene) for strip in text_strips: strip_words = strip.text.lower().replace('--', ' ').replace('\n', ' ').split(' ') words.extend(strip_words) i = 0 while i < len(words): if words[i].rstrip() == '': words.pop(i) else: i += 1 words = set(words) words = list(sorted(words)) for i in range(len(words)): <|code_end|> using the current file's imports: import bpy import os from bpy_extras.io_utils import ExportHelper from .hyphenator.hyphenator import Hyphenator from .hyphenator.get_dictionary import get_dictionary from .tools.get_text_strips import get_text_strips from .tools.remove_punctuation import remove_punctuation and any relevant context from other files: # Path: operators/hyphenator/hyphenator.py # class Hyphenator: # def __init__(self): # self.tree = {} # self.patterns = "" # self.text_exceptions = "" # # def setup_patterns(self): # for pattern in self.patterns.split(): # self._insert_pattern(pattern) # # self.exceptions = {} # for ex in self.text_exceptions.split(): # # Convert the hyphenated pattern into a point array for use later. # self.exceptions[ex.replace('-', '')] = [0] + [ int(h == '-') for h in re.split(r"[a-z]", ex) ] # # def _insert_pattern(self, pattern): # # Convert the a pattern like 'a1bc3d4' into a string of chars 'abcd' # # and a list of points [ 0, 1, 0, 3, 4 ]. # chars = re.sub('[0-9]', '', pattern) # points = [ int(d or 0) for d in re.split("[.a-z]", pattern) ] # # # Insert the pattern into the tree. Each character finds a dict # # another level down in the tree, and leaf nodes have the list of # # points. # t = self.tree # for c in chars: # if c not in t: # t[c] = {} # t = t[c] # t[None] = points # # def hyphenate_word(self, word): # """ Given a word, returns a list of pieces, broken at the possible # hyphenation points. # """ # # If the word is an exception, get the stored points. # if word.lower() in self.exceptions: # points = self.exceptions[word.lower()] # else: # work = '.' + word.lower() + '.' # points = [0] * (len(work)+1) # for i in range(len(work)): # t = self.tree # for c in work[i:]: # if c in t: # t = t[c] # if None in t: # p = t[None] # for j in range(len(p)): # points[i+j] = max(points[i+j], p[j]) # else: # break # # No hyphens in the first two chars or the last two. # points[1] = points[2] = points[-2] = points[-3] = 0 # # # Examine the points to build the pieces list. # pieces = [''] # for c, p in zip(word, points[2:]): # pieces[-1] += c # if p % 2: # pieces.append('') # return pieces # # Path: operators/hyphenator/get_dictionary.py # def get_dictionary(dic_path=None, lang='en-us'): # """Collect the words from the default dictionary""" # # if dic_path == None: # module_path = os.path.dirname(__file__) # dic_path = os.path.join(module_path, 'dictionaries', lang + '.txt') # # dictionary = {} # # try: # f = open(dic_path, 'r') # lines = f.readlines() # f.close() # # for line in lines: # word = line.rstrip().replace(' ', '') # dictionary[word] = line.rstrip() # # except FileNotFoundError: # dictionary = {} # # return dictionary # # Path: operators/tools/get_text_strips.py # def get_text_strips(scene, channel=None): # """Get all the text strips in the edit channel""" # # if channel == None: # channel = scene.subtitle_edit_channel # # all_strips = list(sorted(scene.sequence_editor.sequences, # key=lambda x: x.frame_start)) # # text_strips = [] # for strip in all_strips: # if (strip.channel == channel and # strip.type == 'TEXT'): # text_strips.append(strip) # # return text_strips # # Path: operators/tools/remove_punctuation.py # def remove_punctuation(word): # """Remove punctuation from the beginning and end of a word""" # # puncs = ['\\', '/', ':', '*', '?', '"', '<', '>', '|', '\n', '(', # ')', '!', '@', '#', '$', '%', '^', '-', '+', '=', "'", # ';', ',', '.', '{', '}','[', ']'] # # while len(word) > 0 and word[0] in puncs: # word = word[1::] # # while len(word) > 0 and word[-1] in puncs: # word = word[0:-1] # # return word . Output only the next line.
words[i] = remove_punctuation(words[i])
Here is a snippet: <|code_start|> class SEQUENCER_OT_refresh_font_data(bpy.types.Operator): bl_label = "Refresh Font Data" bl_idname = 'sequencerextra.refresh_font_data' bl_description = "Refresh the font size for all text strips on the edit channel" @classmethod def poll(self, context): scene = context.scene try: <|code_end|> . Write the next line using the current file imports: import bpy from .tools.get_text_strips import get_text_strips from .tools.get_font import get_font and context from other files: # Path: operators/tools/get_text_strips.py # def get_text_strips(scene, channel=None): # """Get all the text strips in the edit channel""" # # if channel == None: # channel = scene.subtitle_edit_channel # # all_strips = list(sorted(scene.sequence_editor.sequences, # key=lambda x: x.frame_start)) # # text_strips = [] # for strip in all_strips: # if (strip.channel == channel and # strip.type == 'TEXT'): # text_strips.append(strip) # # return text_strips # # Path: operators/tools/get_font.py # def get_font(font_path): # # if os.path.isfile(font_path): # return bpy.data.fonts.load(font_path, check_existing=True) # else: # return None , which may include functions, classes, or code. Output only the next line.
text_strips = get_text_strips(scene)
Predict the next line after this snippet: <|code_start|> class SEQUENCER_OT_refresh_font_data(bpy.types.Operator): bl_label = "Refresh Font Data" bl_idname = 'sequencerextra.refresh_font_data' bl_description = "Refresh the font size for all text strips on the edit channel" @classmethod def poll(self, context): scene = context.scene try: text_strips = get_text_strips(scene) if len(text_strips) > 0: return True else: return False except AttributeError: return False def execute(self, context): scene = context.scene text_strips = get_text_strips(scene) for strip in text_strips: strip.font_size = scene.subtitle_font_size <|code_end|> using the current file's imports: import bpy from .tools.get_text_strips import get_text_strips from .tools.get_font import get_font and any relevant context from other files: # Path: operators/tools/get_text_strips.py # def get_text_strips(scene, channel=None): # """Get all the text strips in the edit channel""" # # if channel == None: # channel = scene.subtitle_edit_channel # # all_strips = list(sorted(scene.sequence_editor.sequences, # key=lambda x: x.frame_start)) # # text_strips = [] # for strip in all_strips: # if (strip.channel == channel and # strip.type == 'TEXT'): # text_strips.append(strip) # # return text_strips # # Path: operators/tools/get_font.py # def get_font(font_path): # # if os.path.isfile(font_path): # return bpy.data.fonts.load(font_path, check_existing=True) # else: # return None . Output only the next line.
strip.font = get_font(scene.subtitle_font)
Predict the next line for this snippet: <|code_start|> class SEQUENCER_OT_save_syllables(bpy.types.Operator): bl_label = 'Save' bl_idname = 'sequencerextra.save_syllables' bl_description = "Add the syllables to the default syllable dictionary" @classmethod def poll(self, context): scene = context.scene path = bpy.path.abspath(scene.syllable_dictionary_path) if os.path.isfile(path): return True else: return False def execute(self, context): scene = context.scene <|code_end|> with the help of current file imports: import bpy import os from .hyphenator.get_dictionary import get_dictionary and context from other files: # Path: operators/hyphenator/get_dictionary.py # def get_dictionary(dic_path=None, lang='en-us'): # """Collect the words from the default dictionary""" # # if dic_path == None: # module_path = os.path.dirname(__file__) # dic_path = os.path.join(module_path, 'dictionaries', lang + '.txt') # # dictionary = {} # # try: # f = open(dic_path, 'r') # lines = f.readlines() # f.close() # # for line in lines: # word = line.rstrip().replace(' ', '') # dictionary[word] = line.rstrip() # # except FileNotFoundError: # dictionary = {} # # return dictionary , which may contain function names, class names, or code. Output only the next line.
dictionary = get_dictionary(
Here is a snippet: <|code_start|> file_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) sys.path.insert(0, os.path.abspath(file_path)) class TestTextParser(unittest.TestCase): def setUp(self): self.static_path = os.path.join(file_path, 'tests', 'static') lyrics_path = os.path.join(self.static_path, 'I Move On.txt') f = open(lyrics_path) self.lyrics = f.read() f.close() lyrics_output_path = os.path.join( self.static_path, 'I Move On_unsynchronized.srt') f = open(lyrics_output_path) self.output = f.read().rstrip() f.close() def test_parsing(self): self.maxDiff = None <|code_end|> . Write the next line using the current file imports: import os import sys import unittest from operators.textparser.parser import text_to_srt and context from other files: # Path: operators/textparser/parser.py # def text_to_srt(text, fps, reflow_long_lines=False): # """ # Creates an SRT string out of plain text, with 1 second for each # segment # """ # text = text.strip() # lines = text.split('\n') # # output = [] # sec_time = 0 # for i in range(len(lines)): # seg = str(i + 1) + '\n' # # start = seconds_to_srt_timecode(i + 0.00000001) # sec_time = i + 1.00000001 # end = seconds_to_srt_timecode(sec_time) # seg += start + ' --> ' + end + '\n' # # if len(lines[i].rstrip()) > 31 and reflow_long_lines: # lines[i] = find_even_split(lines[i].rstrip()) # # seg += lines[i] + '\n' # output.append(seg) # # return '\n'.join(output).rstrip() , which may include functions, classes, or code. Output only the next line.
self.assertEqual(text_to_srt(self.lyrics), self.output)
Given snippet: <|code_start|> def text_to_srt(text, fps, reflow_long_lines=False): """ Creates an SRT string out of plain text, with 1 second for each segment """ text = text.strip() lines = text.split('\n') output = [] sec_time = 0 for i in range(len(lines)): seg = str(i + 1) + '\n' start = seconds_to_srt_timecode(i + 0.00000001) sec_time = i + 1.00000001 end = seconds_to_srt_timecode(sec_time) seg += start + ' --> ' + end + '\n' if len(lines[i].rstrip()) > 31 and reflow_long_lines: <|code_end|> , continue by predicting the next line. Consider current file imports: from .tools.find_even_split import find_even_split from .tools.seconds_to_srt_timecode import seconds_to_srt_timecode and context: # Path: operators/textparser/tools/find_even_split.py # def find_even_split(line): # max_line_length = 31 # output = make_lines(line, max_line_length) # max_lines = len(output) # space = max_line_length - 1 # while len(make_lines(line, space)) == max_lines: # space -= 1 # lines = make_lines(line, space + 1) # return '\n'.join(make_lines(line, space + 1)) # # Path: operators/textparser/tools/seconds_to_srt_timecode.py # def seconds_to_srt_timecode(sec_time): # """ # Converts time (in seconds) into a timecode with the format # 23:59:59,999 # """ # hours = int(sec_time / 3600) # minutes = int((sec_time % 3600) / 60) # seconds = int((((sec_time % 3600) / 60) - minutes) * 60) # milliseconds = int((sec_time - int(sec_time)) * 1000) # # hours = "%02d" % hours # minutes = "%02d" % minutes # seconds = "%02d" % seconds # milliseconds = "%03d" % milliseconds # # return ''.join([hours, ':', minutes, ':', seconds, ',', # milliseconds]) which might include code, classes, or functions. Output only the next line.
lines[i] = find_even_split(lines[i].rstrip())
Given the following code snippet before the placeholder: <|code_start|> def text_to_srt(text, fps, reflow_long_lines=False): """ Creates an SRT string out of plain text, with 1 second for each segment """ text = text.strip() lines = text.split('\n') output = [] sec_time = 0 for i in range(len(lines)): seg = str(i + 1) + '\n' <|code_end|> , predict the next line using imports from the current file: from .tools.find_even_split import find_even_split from .tools.seconds_to_srt_timecode import seconds_to_srt_timecode and context including class names, function names, and sometimes code from other files: # Path: operators/textparser/tools/find_even_split.py # def find_even_split(line): # max_line_length = 31 # output = make_lines(line, max_line_length) # max_lines = len(output) # space = max_line_length - 1 # while len(make_lines(line, space)) == max_lines: # space -= 1 # lines = make_lines(line, space + 1) # return '\n'.join(make_lines(line, space + 1)) # # Path: operators/textparser/tools/seconds_to_srt_timecode.py # def seconds_to_srt_timecode(sec_time): # """ # Converts time (in seconds) into a timecode with the format # 23:59:59,999 # """ # hours = int(sec_time / 3600) # minutes = int((sec_time % 3600) / 60) # seconds = int((((sec_time % 3600) / 60) - minutes) * 60) # milliseconds = int((sec_time - int(sec_time)) * 1000) # # hours = "%02d" % hours # minutes = "%02d" % minutes # seconds = "%02d" % seconds # milliseconds = "%03d" % milliseconds # # return ''.join([hours, ':', minutes, ':', seconds, ',', # milliseconds]) . Output only the next line.
start = seconds_to_srt_timecode(i + 0.00000001)
Given the following code snippet before the placeholder: <|code_start|> class LyricLine(): """An object that holds a lyric line and it's time""" def __init__(self, timecode, text=""): self.hours = 0 <|code_end|> , predict the next line using imports from the current file: from .tools.timecode import unpack_timecode import re and context including class names, function names, and sometimes code from other files: # Path: operators/pylrc/tools/timecode.py # def unpack_timecode(timecode): # """unpacks a timecode to minutes, seconds, and milliseconds""" # timecode = timecode.replace('<', '[').replace('>', ']') # x = datetime.strptime(timecode, '[%M:%S.%f]') # # minutes = x.minute # seconds = x.second # milliseconds = int(x.microsecond / 1000) # return minutes, seconds, milliseconds . Output only the next line.
self.minutes, self.seconds, self.milliseconds = unpack_timecode(timecode)
Given the code snippet: <|code_start|> def subtitles_to_sequencer(context, subs): """Add subtitles to the video sequencer""" scene = context.scene fps = scene.render.fps / scene.render.fps_base <|code_end|> , generate the next line using the imports in this file: import bpy from .get_open_channel import get_open_channel from .get_font import get_font and context (functions, classes, or occasionally code) from other files: # Path: operators/tools/get_open_channel.py # def get_open_channel(scene): # """Get a channel with nothing in it""" # channels = [] # try: # for strip in scene.sequence_editor.sequences_all: # channels.append(strip.channel) # if len(channels) > 0: # return max(channels) + 1 # else: # return 1 # except AttributeError: # return 1 # # Path: operators/tools/get_font.py # def get_font(font_path): # # if os.path.isfile(font_path): # return bpy.data.fonts.load(font_path, check_existing=True) # else: # return None . Output only the next line.
open_channel = get_open_channel(scene)
Here is a snippet: <|code_start|> scene.sequence_editor_create() wm = context.window_manager wm.progress_begin(0, 100.0) added_strips = [] for i in range(len(subs)): start_time = subs[i].start.to_millis() / 1000 strip_start = round(start_time * fps, 0) end_time = subs[i].end.to_millis() / 1000 strip_end = round(end_time * fps, 0) sub_name = str(open_channel) + '_' + str(i + 1) try: if '[locked start]' in subs[i].name: sub_name = '[locked start]' + sub_name if '[locked end]' in subs[i].name: sub_name += '[locked end]' except AttributeError: pass text_strip = scene.sequence_editor.sequences.new_effect( name=sub_name, type='TEXT', channel=open_channel, frame_start=strip_start, frame_end=strip_end ) <|code_end|> . Write the next line using the current file imports: import bpy from .get_open_channel import get_open_channel from .get_font import get_font and context from other files: # Path: operators/tools/get_open_channel.py # def get_open_channel(scene): # """Get a channel with nothing in it""" # channels = [] # try: # for strip in scene.sequence_editor.sequences_all: # channels.append(strip.channel) # if len(channels) > 0: # return max(channels) + 1 # else: # return 1 # except AttributeError: # return 1 # # Path: operators/tools/get_font.py # def get_font(font_path): # # if os.path.isfile(font_path): # return bpy.data.fonts.load(font_path, check_existing=True) # else: # return None , which may include functions, classes, or code. Output only the next line.
text_strip.font = get_font(scene.subtitle_font)
Using the snippet: <|code_start|> class SEQUENCER_OT_refresh_highlight(bpy.types.Operator): bl_label = "" bl_idname = 'sequencerextra.refresh_highlight' bl_description = "Refresh the color of highlighted words" @classmethod def poll(self, context): scene = context.scene try: <|code_end|> , determine the next line of code. You have imports: import bpy from .tools.get_text_strips import get_text_strips and context (class names, function names, or code) available: # Path: operators/tools/get_text_strips.py # def get_text_strips(scene, channel=None): # """Get all the text strips in the edit channel""" # # if channel == None: # channel = scene.subtitle_edit_channel # # all_strips = list(sorted(scene.sequence_editor.sequences, # key=lambda x: x.frame_start)) # # text_strips = [] # for strip in all_strips: # if (strip.channel == channel and # strip.type == 'TEXT'): # text_strips.append(strip) # # return text_strips . Output only the next line.
text_strips = get_text_strips(scene)
Given the code snippet: <|code_start|> yield self.hours yield self.minutes yield self.seconds yield self.milliseconds def shift(self, *args, **kwargs): """ shift(hours, minutes, seconds, milliseconds) All arguments are optional and have a default value of 0. """ if 'ratio' in kwargs: self *= kwargs.pop('ratio') self += self.__class__(*args, **kwargs) @classmethod def from_ordinal(cls, ordinal): """ int -> SubRipTime corresponding to a total count of milliseconds """ return cls(milliseconds=int(ordinal)) @classmethod def from_string(cls, source): """ str/unicode(HH:MM:SS,mmm) -> SubRipTime corresponding to serial raise InvalidTimeString """ items = cls.RE_TIME_SEP.split(source) if len(items) != 4: <|code_end|> , generate the next line using the imports in this file: import re from datetime import time from .srtexc import InvalidTimeString from .comparablemixin import ComparableMixin from .compat import str, basestring and context (functions, classes, or occasionally code) from other files: # Path: operators/pysrt/srtexc.py # class InvalidTimeString(Error): # """ # Raised when parser fail on bad formated time strings # """ # pass . Output only the next line.
raise InvalidTimeString
Continue the code snippet: <|code_start|> class SEQUENCER_OT_duration_x_2(bpy.types.Operator): bl_label = 'Dur x 2' bl_idname = 'sequencerextra.duration_x_two' bl_description = 'Make all text strips in subtitle edit channel twice as long' @classmethod def poll(self, context): scene = context.scene try: <|code_end|> . Use current file imports: import bpy from .tools.get_text_strips import get_text_strips and context (classes, functions, or code) from other files: # Path: operators/tools/get_text_strips.py # def get_text_strips(scene, channel=None): # """Get all the text strips in the edit channel""" # # if channel == None: # channel = scene.subtitle_edit_channel # # all_strips = list(sorted(scene.sequence_editor.sequences, # key=lambda x: x.frame_start)) # # text_strips = [] # for strip in all_strips: # if (strip.channel == channel and # strip.type == 'TEXT'): # text_strips.append(strip) # # return text_strips . Output only the next line.
text_strips = get_text_strips(scene)
Using the snippet: <|code_start|> text_strips = get_text_strips(scene) if len(text_strips) == 0: return {"FINISHED"} except AttributeError: return {"FINISHED"} current_frame = scene.frame_current base_channel = text_strips[0].channel - 1 base_strips = get_text_strips(scene, channel=base_channel) for i in range(len(text_strips)): strip = text_strips[i] start = strip.frame_final_start end = strip.frame_final_end if current_frame >= start and current_frame < end: strip.frame_final_start = current_frame return {"FINISHED"} elif current_frame < start: if not strip.name.startswith('[locked start]'): strip.frame_final_start = current_frame return {"FINISHED"} elif len(base_strips) == 0: strip.frame_final_start = current_frame return {"FINISHED"} else: <|code_end|> , determine the next line of code. You have imports: import bpy from .tools.get_base_strip import get_base_strip from .tools.get_text_strips import get_text_strips and context (class names, function names, or code) available: # Path: operators/tools/get_base_strip.py # def get_base_strip(strip, base_strips): # """Get the strip's base strip""" # for i in range(len(base_strips)): # if base_strips[i].frame_start <= strip.frame_start: # if base_strips[i].frame_final_end >= strip.frame_final_end: # return base_strips[i] # # Path: operators/tools/get_text_strips.py # def get_text_strips(scene, channel=None): # """Get all the text strips in the edit channel""" # # if channel == None: # channel = scene.subtitle_edit_channel # # all_strips = list(sorted(scene.sequence_editor.sequences, # key=lambda x: x.frame_start)) # # text_strips = [] # for strip in all_strips: # if (strip.channel == channel and # strip.type == 'TEXT'): # text_strips.append(strip) # # return text_strips . Output only the next line.
base = get_base_strip(strip, base_strips)
Using the snippet: <|code_start|> class SEQUENCER_OT_shift_frame_start(bpy.types.Operator): bl_idname = "sequencerextra.shift_frame_start" bl_label = "Shift Frame Start of Next Text Strip" bl_description = "Shifts frame start of text strip to the current frame" def execute(self, context): scene = context.scene try: <|code_end|> , determine the next line of code. You have imports: import bpy from .tools.get_base_strip import get_base_strip from .tools.get_text_strips import get_text_strips and context (class names, function names, or code) available: # Path: operators/tools/get_base_strip.py # def get_base_strip(strip, base_strips): # """Get the strip's base strip""" # for i in range(len(base_strips)): # if base_strips[i].frame_start <= strip.frame_start: # if base_strips[i].frame_final_end >= strip.frame_final_end: # return base_strips[i] # # Path: operators/tools/get_text_strips.py # def get_text_strips(scene, channel=None): # """Get all the text strips in the edit channel""" # # if channel == None: # channel = scene.subtitle_edit_channel # # all_strips = list(sorted(scene.sequence_editor.sequences, # key=lambda x: x.frame_start)) # # text_strips = [] # for strip in all_strips: # if (strip.channel == channel and # strip.type == 'TEXT'): # text_strips.append(strip) # # return text_strips . Output only the next line.
text_strips = get_text_strips(scene)
Next line prediction: <|code_start|>#!/usr/bin/python # *****BatteryMonitor Getdata from battery cells getdata.py***** # Copyright (C) 2020 Simon Richard Matthews # Project loaction https://github.com/simat/BatteryMonitor # 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; either version 2 of the License, or # any later version. # 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 Street, Fifth Floor, Boston, MA 02110-1301 USA. IBatZero = 0.0 # 'Zero' battery current flow to calculate available power minmaxdemandpwr = [0,0] def solaravailable(batdata): """Returns max amount of surpus solar energy available without using battery Power Calculates the difference between amount of power being consumed vesus power that could be consumed to get battery current=IBatZero""" global minmaxdemandpwr ibatminuteav=batdata.ibatminute/batdata.ibatnuminmin batdata.ibatminute = 0.0 batdata.ibatnuminmin = 0 <|code_end|> . Use current file imports: (from config import config) and context including class names, function names, or small code snippets from other files: # Path: config.py # def editbatconfig(section,item,itemvalue): # def loadconfig(): . Output only the next line.
minsoc = config['battery']['targetsoc'] -config['battery']['minsocdif']
Using the snippet: <|code_start|> summaryfile = SafeConfigParser() def tail(file, n=1, bs=1024): f = open(file) f.seek(-1,2) l = 1-f.read(1).count('\n') # If file doesn't end in \n, count it anyway. B = f.tell() while n >= l and B > 0: block = min(bs, B) B -= block f.seek(B, 0) l += f.read(block).count('\n') f.seek(B, 0) l = min(l,n) # discard first (incomplete) line if l > n lines = f.readlines()[-l:] f.close() return lines def getavi(): istr="" avi = [ 0.0 for i in range(numiin)] endlog=tail(config['files']['logfile'],11) for line in range(10): lineargs = str(endlog[line]).split(' ') for iin in range(numiin): avi[iin] = avi[iin] + float(lineargs[1+numcells+2+iin])/10 for iin in range(numiin): istr =istr+str(round(avi[iin],3)) + ", " print('Average readings for last 100 seconds: ' + istr) <|code_end|> , determine the next line of code. You have imports: import sys import time from os import rename from shutil import copy as filecopy from copy import deepcopy from ast import literal_eval from configparser import SafeConfigParser from config import config, loadconfig and context (class names, function names, or code) available: # Path: config.py # def editbatconfig(section,item,itemvalue): # def loadconfig(): . Output only the next line.
loadconfig()
Based on the snippet: <|code_start|> return v def getv(): global voltages try: summaryfile.read(config['files']['summaryfile']) except IOError: pass voltages=literal_eval(summaryfile.get('current','maxvoltages')) vprint = '' for i in range(numcells+1): vprint = vprint + str(i+1) + '=' + str(voltages[i]).ljust(5,'0') + ', ' print(vprint) print(config['calibrate']['delta']) def main(): print('Usage: Pressing just the [Enter] key will display the latest voltage readings, type ^C to exit') print(' Type in the cell # that you want to calibrate followed by [Enter]') print(' Then type in the mesured voltage for that cell followed by [Enter]') print() print(' Make sure the Battery Monitoring software is running otherwise the summary file will not be current') print(' This program uses the data from the log file generated by the Battery Monitoring software') print(' Make sure that the Battery Monitoring software is logging to a real file and not /dev/null') print(' This program averages the data from the log file for the last 100 seconds.') print(' To make sure that the calibration is accurate make sure the input voltages are not varying') avvolts=[] while True: try: <|code_end|> , predict the immediate next line with the help of imports: import sys import time from os import rename from shutil import copy as filecopy from copy import deepcopy from ast import literal_eval from configparser import SafeConfigParser from config import config,loadconfig and context (classes, functions, sometimes code) from other files: # Path: config.py # def editbatconfig(section,item,itemvalue): # def loadconfig(): . Output only the next line.
loadconfig()
Given the following code snippet before the placeholder: <|code_start|> def avv(): vstr="" v=[0.0 for i in range(numcells+1)] endlog=tail(config['files']['logfile'],11) for j in range(1,numcells+1): for i in range(10): x=float(endlog[i][(j-1)*6+15:(j-1)*6+20])+config['calibrate']['delta'][j-1] v[j]=v[j]+x for i in range(1,len(v)): v[i]=v[i]/10+v[i-1] vstr=vstr+str(i) + "=" +str(round(v[i],3)).ljust(5,'0') + ", " print(vstr) print(config['calibrate']['measured']) print(config['calibrate']['displayed']) return v def main(): print('Usage: Pressing just the [Enter] key will display the latest voltage readings, type ^C to exit') print(' Type in the cell # that you want to calibrate followed by [Enter]') print(' Then type in the mesured voltage for that cell followed by [Enter]') print() print(' Make sure the Battery Monitoring software is running otherwise the summary file will not be current') print(' This program uses the data from the log file generated by the Battery Monitoring software') print(' Make sure that the Battery Monitoring software is logging to a real file and not /dev/null') print(' This program averages the data from the log file for the last 100 seconds.') print(' To make sure that the calibration is accurate make sure the input voltages are not varying') avvolts=[] while True: try: <|code_end|> , predict the next line using imports from the current file: import sys import time from os import rename from shutil import copy as filecopy from copy import deepcopy from ast import literal_eval from configparser import SafeConfigParser from config import config,loadconfig and context including class names, function names, and sometimes code from other files: # Path: config.py # def editbatconfig(section,item,itemvalue): # def loadconfig(): . Output only the next line.
loadconfig()
Continue the code snippet: <|code_start|># *****BatteryMonitor main file batteries.py***** # Copyright (C) 2014 Simon Richard Matthews # Project loaction https://github.com/simat/BatteryMonitor # 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; either version 2 of the License, or # any later version. # 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 Street, Fifth Floor, Boston, MA 02110-1301 USA. #!/usr/bin/python #self.summary=summary log = logger.logging.getLogger(__name__) log.setLevel(logger.logging.INFO) log.addHandler(logger.alarmfile) class Alarms: # Initialise and compile alarms def __init__(self,batdata,summary): self.summary=summary self.alarmtriggered={} <|code_end|> . Use current file imports: import sys import serial import binascii import logger from time import localtime from config import config and context (classes, functions, or code) from other files: # Path: config.py # def editbatconfig(section,item,itemvalue): # def loadconfig(): . Output only the next line.
for i in config['alarms']:
Using the snippet: <|code_start|> def getv(): global voltages try: summaryfile.read(config['files']['summaryfile']) except IOError: pass voltages=literal_eval(summaryfile.get('current','maxvoltages')) vprint = '' for i in range(numcells+1): vprint = vprint + str(i+1) + '=' + str(voltages[i]).ljust(5,'0') + ', ' print(vprint) print(config['calibrate']['delta']) def main(): print('Usage: Pressing just the [Enter] key will display the latest voltage readings, type ^C to exit') print(' Press any other key to change the voltage calibration of all the voltage readings') print() print(' Make sure the Battery Monitoring software is running otherwise the summary file will not be current') print(' This program uses the data from the log file generated by the Battery Monitoring software') print(' Make sure that the Battery Monitoring software is logging to a real file and not /dev/null') print(' This program averages the data from the log file for the last 100 seconds.') print(' To make sure that the calibration is accurate make sure the input voltages are not varying') avvolts=[] while True: try: <|code_end|> , determine the next line of code. You have imports: import sys import time from os import rename from shutil import copy as filecopy from copy import deepcopy from ast import literal_eval from configparser import SafeConfigParser from config import config,loadconfig and context (class names, function names, or code) available: # Path: config.py # def editbatconfig(section,item,itemvalue): # def loadconfig(): . Output only the next line.
loadconfig()
Given the following code snippet before the placeholder: <|code_start|># *****BatteryMonitor MQTT client***** # Copyright (C) 2021 Simon Richard Matthews # Project loaction https://github.com/simat/BatteryMonitor # 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; either version 2 of the License, or # any later version. # 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 Street, Fifth Floor, Boston, MA 02110-1301 USA. log = logger.logging.getLogger(__name__) log.setLevel(logger.logging.DEBUG) log.addHandler(logger.errfile) def on_message(client,userata,message): """Executed when any subscribed MQTT message arives At present assumes payload is item to change in battery.config makes change and rewrites config file""" payload=eval(str(message.payload.decode("utf-8"))) print (payload) for section in payload: for item in payload[section]: # print (section,item,payload[section][item]) <|code_end|> , predict the next line using imports from the current file: from paho.mqtt import client as mqtt_client from time import sleep from config import editbatconfig, config import logger and context including class names, function names, and sometimes code from other files: # Path: config.py # def editbatconfig(section,item,itemvalue): # def loadconfig(): . Output only the next line.
editbatconfig(section,item,payload[section][item])
Given snippet: <|code_start|>log = logger.logging.getLogger(__name__) log.setLevel(logger.logging.DEBUG) log.addHandler(logger.errfile) def on_message(client,userata,message): """Executed when any subscribed MQTT message arives At present assumes payload is item to change in battery.config makes change and rewrites config file""" payload=eval(str(message.payload.decode("utf-8"))) print (payload) for section in payload: for item in payload[section]: # print (section,item,payload[section][item]) editbatconfig(section,item,payload[section][item]) def on_disconnect(client, userdata, rc): if rc: log.error('MQTT server disconnect, Restart MQTT') def connect_mqtt(): def on_connect(client, userdata, flags, rc): if rc == 0: print("Connected to MQTT Broker!") else: fail=f"Failed to connect, return code {rc}" print(fail) log.error(fail) <|code_end|> , continue by predicting the next line. Consider current file imports: from paho.mqtt import client as mqtt_client from time import sleep from config import editbatconfig, config import logger and context: # Path: config.py # def editbatconfig(section,item,itemvalue): # def loadconfig(): which might include code, classes, or functions. Output only the next line.
client = mqtt_client.Client(config['mqtt']['clientname'],clean_session=False)
Predict the next line after this snippet: <|code_start|> def render_node(node, context=None, edit=True): """ Render node as html for templates, with edit tagging. """ output = node.render(**context or {}) or u'' if edit: return u'<span data-i18n="{0}">{1}</span>'.format(node.uri.clone(scheme=None, ext=None, version=None), output) else: return output <|code_end|> using the current file's imports: import cio import six import textwrap from django import template from django.template import TemplateSyntaxError from .template import register from ..compat import parse_bits and any relevant context from other files: # Path: djedi/templatetags/template.py # def lazy_tag(self, func=None, takes_context=None, name=None, node_class=None): # def dec(func): # def __init__(self, takes_context, args, kwargs): # def get_resolved_arguments(self, context): # def render(self, context): # class SimpleNode(Node): # # Path: djedi/compat.py # def parse_bits(parser, bits, params, varargs, varkw, defaults, # takes_context, name): # from django.template import library # return library.parse_bits( # parser=parser, bits=bits, params=params, varargs=varargs, # varkw=varkw, defaults=defaults, kwonly=(), kwonly_defaults=(), # takes_context=takes_context, name=name) . Output only the next line.
@register.lazy_tag
Based on the snippet: <|code_start|> """ output = node.render(**context or {}) or u'' if edit: return u'<span data-i18n="{0}">{1}</span>'.format(node.uri.clone(scheme=None, ext=None, version=None), output) else: return output @register.lazy_tag def node(key, default=None, edit=True): """ Simple node tag: {% node 'page/title' default='Lorem ipsum' edit=True %} """ node = cio.get(key, default=default or u'') return lambda _: render_node(node, edit=edit) class BlockNode(template.Node): """ Block node tag using body content as default: {% blocknode 'page/title' edit=True %} Lorem ipsum {% endblocknode %} """ @classmethod def tag(cls, parser, token): # Parse tag args and kwargs bits = token.split_contents()[1:] params = ('uri', 'edit') <|code_end|> , predict the immediate next line with the help of imports: import cio import six import textwrap from django import template from django.template import TemplateSyntaxError from .template import register from ..compat import parse_bits and context (classes, functions, sometimes code) from other files: # Path: djedi/templatetags/template.py # def lazy_tag(self, func=None, takes_context=None, name=None, node_class=None): # def dec(func): # def __init__(self, takes_context, args, kwargs): # def get_resolved_arguments(self, context): # def render(self, context): # class SimpleNode(Node): # # Path: djedi/compat.py # def parse_bits(parser, bits, params, varargs, varkw, defaults, # takes_context, name): # from django.template import library # return library.parse_bits( # parser=parser, bits=bits, params=params, varargs=varargs, # varkw=varkw, defaults=defaults, kwonly=(), kwonly_defaults=(), # takes_context=takes_context, name=name) . Output only the next line.
args, kwargs = parse_bits(parser, bits, params, None, True, (True,), None, 'blocknode')
Next line prediction: <|code_start|> class PanelTest(ClientTest): def test_embed(self): url = reverse('index') response = self.client.get(url) <|code_end|> . Use current file imports: (from unittest import skip from djedi.utils.encoding import smart_unicode from djedi.tests.base import ClientTest from ..compat import reverse from django.contrib.admin.templatetags.log import AdminLogNode import cio.conf) and context including class names, function names, or small code snippets from other files: # Path: djedi/utils/encoding.py # # Path: djedi/tests/base.py # class ClientTest(DjediTest, UserMixin, AssertionMixin): # # def setUp(self): # super(ClientTest, self).setUp() # master = self.create_djedi_master() # client = Client(enforce_csrf_checks=True) # client.login(username=master.username, password='test') # self.client = client # # Path: djedi/compat.py # def patterns(*urls): # def parse_bits(parser, bits, params, varargs, varkw, defaults, # takes_context, name): # def generic_tag_compiler(parser, token, params, varargs, varkw, defaults, # name, takes_context, node_class): # def __init__(self, *args, **kwargs): # def get_cache(name): # def getargspec(func): # class TemplateResponse(BaseTemplateResponse): . Output only the next line.
self.assertIn(u'Djedi Test', smart_unicode(response.content))
Continue the code snippet: <|code_start|> app_name = 'rest' def not_found(*args, **kwargs): raise Http404 <|code_end|> . Use current file imports: from django.http import Http404 from ..compat import patterns, url from .api import EmbedApi, NodesApi and context (classes, functions, or code) from other files: # Path: djedi/compat.py # def patterns(*urls): # def parse_bits(parser, bits, params, varargs, varkw, defaults, # takes_context, name): # def generic_tag_compiler(parser, token, params, varargs, varkw, defaults, # name, takes_context, node_class): # def __init__(self, *args, **kwargs): # def get_cache(name): # def getargspec(func): # class TemplateResponse(BaseTemplateResponse): # # Path: djedi/rest/api.py # class EmbedApi(View): # # def get(self, request): # if has_permission(request): # return render_embed(request=request) # else: # # We used to `raise PermissionDenied` here (which might seem more # # appropriate), but that has the annoying side effect of being # # logged as an error in the browser dev tools, making people think # # something is wrong. # return HttpResponse(status=204) # # class NodesApi(APIView): # """ # JSON Response: # {uri: content, uri: content, ...} # """ # @never_cache # def post(self, request): # # Disable caching gets in CachePipe, defaults through this api is not trusted # cio.conf.settings.configure( # local=True, # CACHE={ # 'PIPE': { # 'CACHE_ON_GET': False # } # } # ) # # nodes = [] # for uri, default in six.iteritems(json.loads(request.body)): # node = cio.get(uri, default=default) # nodes.append(node) # # data = dict((node.uri, node.content) for node in nodes) # # return self.render_to_json(data) . Output only the next line.
urlpatterns = patterns(
Next line prediction: <|code_start|> app_name = 'rest' def not_found(*args, **kwargs): raise Http404 urlpatterns = patterns( <|code_end|> . Use current file imports: (from django.http import Http404 from ..compat import patterns, url from .api import EmbedApi, NodesApi) and context including class names, function names, or small code snippets from other files: # Path: djedi/compat.py # def patterns(*urls): # def parse_bits(parser, bits, params, varargs, varkw, defaults, # takes_context, name): # def generic_tag_compiler(parser, token, params, varargs, varkw, defaults, # name, takes_context, node_class): # def __init__(self, *args, **kwargs): # def get_cache(name): # def getargspec(func): # class TemplateResponse(BaseTemplateResponse): # # Path: djedi/rest/api.py # class EmbedApi(View): # # def get(self, request): # if has_permission(request): # return render_embed(request=request) # else: # # We used to `raise PermissionDenied` here (which might seem more # # appropriate), but that has the annoying side effect of being # # logged as an error in the browser dev tools, making people think # # something is wrong. # return HttpResponse(status=204) # # class NodesApi(APIView): # """ # JSON Response: # {uri: content, uri: content, ...} # """ # @never_cache # def post(self, request): # # Disable caching gets in CachePipe, defaults through this api is not trusted # cio.conf.settings.configure( # local=True, # CACHE={ # 'PIPE': { # 'CACHE_ON_GET': False # } # } # ) # # nodes = [] # for uri, default in six.iteritems(json.loads(request.body)): # node = cio.get(uri, default=default) # nodes.append(node) # # data = dict((node.uri, node.content) for node in nodes) # # return self.render_to_json(data) . Output only the next line.
url(r'^$', not_found, name='api-base'),
Next line prediction: <|code_start|> app_name = 'rest' def not_found(*args, **kwargs): raise Http404 urlpatterns = patterns( url(r'^$', not_found, name='api-base'), <|code_end|> . Use current file imports: (from django.http import Http404 from ..compat import patterns, url from .api import EmbedApi, NodesApi) and context including class names, function names, or small code snippets from other files: # Path: djedi/compat.py # def patterns(*urls): # def parse_bits(parser, bits, params, varargs, varkw, defaults, # takes_context, name): # def generic_tag_compiler(parser, token, params, varargs, varkw, defaults, # name, takes_context, node_class): # def __init__(self, *args, **kwargs): # def get_cache(name): # def getargspec(func): # class TemplateResponse(BaseTemplateResponse): # # Path: djedi/rest/api.py # class EmbedApi(View): # # def get(self, request): # if has_permission(request): # return render_embed(request=request) # else: # # We used to `raise PermissionDenied` here (which might seem more # # appropriate), but that has the annoying side effect of being # # logged as an error in the browser dev tools, making people think # # something is wrong. # return HttpResponse(status=204) # # class NodesApi(APIView): # """ # JSON Response: # {uri: content, uri: content, ...} # """ # @never_cache # def post(self, request): # # Disable caching gets in CachePipe, defaults through this api is not trusted # cio.conf.settings.configure( # local=True, # CACHE={ # 'PIPE': { # 'CACHE_ON_GET': False # } # } # ) # # nodes = [] # for uri, default in six.iteritems(json.loads(request.body)): # node = cio.get(uri, default=default) # nodes.append(node) # # data = dict((node.uri, node.content) for node in nodes) # # return self.render_to_json(data) . Output only the next line.
url(r'^embed/$', EmbedApi.as_view(), name='embed'),
Given snippet: <|code_start|> app_name = 'rest' def not_found(*args, **kwargs): raise Http404 urlpatterns = patterns( url(r'^$', not_found, name='api-base'), url(r'^embed/$', EmbedApi.as_view(), name='embed'), <|code_end|> , continue by predicting the next line. Consider current file imports: from django.http import Http404 from ..compat import patterns, url from .api import EmbedApi, NodesApi and context: # Path: djedi/compat.py # def patterns(*urls): # def parse_bits(parser, bits, params, varargs, varkw, defaults, # takes_context, name): # def generic_tag_compiler(parser, token, params, varargs, varkw, defaults, # name, takes_context, node_class): # def __init__(self, *args, **kwargs): # def get_cache(name): # def getargspec(func): # class TemplateResponse(BaseTemplateResponse): # # Path: djedi/rest/api.py # class EmbedApi(View): # # def get(self, request): # if has_permission(request): # return render_embed(request=request) # else: # # We used to `raise PermissionDenied` here (which might seem more # # appropriate), but that has the annoying side effect of being # # logged as an error in the browser dev tools, making people think # # something is wrong. # return HttpResponse(status=204) # # class NodesApi(APIView): # """ # JSON Response: # {uri: content, uri: content, ...} # """ # @never_cache # def post(self, request): # # Disable caching gets in CachePipe, defaults through this api is not trusted # cio.conf.settings.configure( # local=True, # CACHE={ # 'PIPE': { # 'CACHE_ON_GET': False # } # } # ) # # nodes = [] # for uri, default in six.iteritems(json.loads(request.body)): # node = cio.get(uri, default=default) # nodes.append(node) # # data = dict((node.uri, node.content) for node in nodes) # # return self.render_to_json(data) which might include code, classes, or functions. Output only the next line.
url(r'^nodes/$', NodesApi.as_view(), name='nodes'),
Using the snippet: <|code_start|> self._cache = cache def clear(self): self._cache.clear() def _get(self, key): return self._cache.get(key) def _get_many(self, keys): return self._cache.get_many(keys) def _set(self, key, value): self._cache.set(key, value, timeout=None) # TODO: Fix eternal timeout like viewlet def _set_many(self, data): self._cache.set_many(data, timeout=None) # TODO: Fix eternal timeout like viewlet def _delete(self, key): self._cache.delete(key) def _delete_many(self, keys): self._cache.delete_many(keys) def _encode_content(self, uri, content): """ Join node uri and content as string and convert to bytes to ensure no pickling in memcached. """ if content is None: content = self.NONE <|code_end|> , determine the next line of code. You have imports: import six from django.core.cache import InvalidCacheBackendError from djedi.utils.encoding import smart_str, smart_unicode from cio.backends.base import CacheBackend from django.core.cache.backends.locmem import LocMemCache from djedi.compat import get_cache from django.core.cache import cache and context (class names, function names, or code) available: # Path: djedi/utils/encoding.py # # Path: djedi/compat.py # def get_cache(name): # return caches[name] . Output only the next line.
return smart_str('|'.join([six.text_type(uri), content]))
Here is a snippet: <|code_start|> def _get(self, key): return self._cache.get(key) def _get_many(self, keys): return self._cache.get_many(keys) def _set(self, key, value): self._cache.set(key, value, timeout=None) # TODO: Fix eternal timeout like viewlet def _set_many(self, data): self._cache.set_many(data, timeout=None) # TODO: Fix eternal timeout like viewlet def _delete(self, key): self._cache.delete(key) def _delete_many(self, keys): self._cache.delete_many(keys) def _encode_content(self, uri, content): """ Join node uri and content as string and convert to bytes to ensure no pickling in memcached. """ if content is None: content = self.NONE return smart_str('|'.join([six.text_type(uri), content])) def _decode_content(self, content): """ Split node string to uri and content and convert back to unicode. """ <|code_end|> . Write the next line using the current file imports: import six from django.core.cache import InvalidCacheBackendError from djedi.utils.encoding import smart_str, smart_unicode from cio.backends.base import CacheBackend from django.core.cache.backends.locmem import LocMemCache from djedi.compat import get_cache from django.core.cache import cache and context from other files: # Path: djedi/utils/encoding.py # # Path: djedi/compat.py # def get_cache(name): # return caches[name] , which may include functions, classes, or code. Output only the next line.
content = smart_unicode(content)
Using the snippet: <|code_start|> class DjangoCacheBackend(CacheBackend): def __init__(self, **config): """ Get cache backend. Look for djedi specific cache first, then fallback on default """ super(DjangoCacheBackend, self).__init__(**config) try: cache_name = self.config.get('NAME', 'djedi') <|code_end|> , determine the next line of code. You have imports: import six from django.core.cache import InvalidCacheBackendError from djedi.utils.encoding import smart_str, smart_unicode from cio.backends.base import CacheBackend from django.core.cache.backends.locmem import LocMemCache from djedi.compat import get_cache from django.core.cache import cache and context (class names, function names, or code) available: # Path: djedi/utils/encoding.py # # Path: djedi/compat.py # def get_cache(name): # return caches[name] . Output only the next line.
cache = get_cache(cache_name)
Given snippet: <|code_start|> admin.autodiscover() if django.VERSION < (2, 0): admin_urls = include(admin.site.urls) else: admin_urls = admin.site.urls <|code_end|> , continue by predicting the next line. Consider current file imports: import django from django.contrib import admin from django.shortcuts import render_to_response from ..compat import include, patterns, url and context: # Path: djedi/compat.py # def patterns(*urls): # def parse_bits(parser, bits, params, varargs, varkw, defaults, # takes_context, name): # def generic_tag_compiler(parser, token, params, varargs, varkw, defaults, # name, takes_context, node_class): # def __init__(self, *args, **kwargs): # def get_cache(name): # def getargspec(func): # class TemplateResponse(BaseTemplateResponse): which might include code, classes, or functions. Output only the next line.
urlpatterns = patterns(
Continue the code snippet: <|code_start|> admin.autodiscover() if django.VERSION < (2, 0): admin_urls = include(admin.site.urls) else: admin_urls = admin.site.urls urlpatterns = patterns( <|code_end|> . Use current file imports: import django from django.contrib import admin from django.shortcuts import render_to_response from ..compat import include, patterns, url and context (classes, functions, or code) from other files: # Path: djedi/compat.py # def patterns(*urls): # def parse_bits(parser, bits, params, varargs, varkw, defaults, # takes_context, name): # def generic_tag_compiler(parser, token, params, varargs, varkw, defaults, # name, takes_context, node_class): # def __init__(self, *args, **kwargs): # def get_cache(name): # def getargspec(func): # class TemplateResponse(BaseTemplateResponse): . Output only the next line.
url(r'^$', lambda r: render_to_response('index.html'), name='index'),
Given the code snippet: <|code_start|> return render """ def dec(func): params, varargs, varkw, defaults = getargspec(func) class SimpleNode(Node): def __init__(self, takes_context, args, kwargs): self.takes_context = takes_context self.args = args self.kwargs = kwargs resolved_args, resolved_kwargs = self.get_resolved_arguments(Context({})) self.resolved_args = resolved_args self.resolved_kwargs = resolved_kwargs self.render_func = func(*resolved_args, **resolved_kwargs) def get_resolved_arguments(self, context): resolved_args = [var.resolve(context) for var in self.args] if self.takes_context: resolved_args = [context] + resolved_args resolved_kwargs = dict((k, v.resolve(context)) for k, v in self.kwargs.items()) return resolved_args, resolved_kwargs def render(self, context): return self.render_func(context) function_name = (name or getattr(func, '_decorated_function', func).__name__) <|code_end|> , generate the next line using the imports in this file: from functools import partial from django import template from django.template import Context from django.template.base import Node, TemplateSyntaxError from ..compat import generic_tag_compiler, getargspec and context (functions, classes, or occasionally code) from other files: # Path: djedi/compat.py # def generic_tag_compiler(parser, token, params, varargs, varkw, defaults, # name, takes_context, node_class): # """ # Returns a template.Node subclass. # # This got inlined into django.template.library since Django since 1.9, this here # is a copypasta replacement: # https://github.com/django/django/blob/stable/1.8.x/django/template/base.py#L1089 # """ # bits = token.split_contents()[1:] # args, kwargs = parse_bits(parser, bits, params, varargs, varkw, # defaults, takes_context, name) # return node_class(takes_context, args, kwargs) # # def getargspec(func): # spec = getfullargspec(func) # return ArgSpec( # args=spec.args, # varargs=spec.varargs, # keywords=spec.varkw, # defaults=spec.defaults, # ) . Output only the next line.
compile_func = partial(generic_tag_compiler,
Predict the next line after this snippet: <|code_start|> register = template.Library() def lazy_tag(self, func=None, takes_context=None, name=None, node_class=None): """ A tag function decorator, injected on Django's template tag library, similar to simple_tag(). The decorated function gets called when the template node tree is built and should return another function, responsible for the output, that later will be called within the rendering phase. Note: if decorated with takes_context=True, context will not be available in the init phase. @register.lazy_tag(takes_context=True) def x(context, a, b, c=True, d=False): # Init phase (no context) def render(context): # Render phase return u'Content of argument a: %s' % a return render """ def dec(func): <|code_end|> using the current file's imports: from functools import partial from django import template from django.template import Context from django.template.base import Node, TemplateSyntaxError from ..compat import generic_tag_compiler, getargspec and any relevant context from other files: # Path: djedi/compat.py # def generic_tag_compiler(parser, token, params, varargs, varkw, defaults, # name, takes_context, node_class): # """ # Returns a template.Node subclass. # # This got inlined into django.template.library since Django since 1.9, this here # is a copypasta replacement: # https://github.com/django/django/blob/stable/1.8.x/django/template/base.py#L1089 # """ # bits = token.split_contents()[1:] # args, kwargs = parse_bits(parser, bits, params, varargs, varkw, # defaults, takes_context, name) # return node_class(takes_context, args, kwargs) # # def getargspec(func): # spec = getfullargspec(func) # return ArgSpec( # args=spec.args, # varargs=spec.varargs, # keywords=spec.varkw, # defaults=spec.defaults, # ) . Output only the next line.
params, varargs, varkw, defaults = getargspec(func)
Given the code snippet: <|code_start|> app_name = 'djedi' urlpatterns = patterns( url(r'^$', DjediCMS.as_view(), name='cms'), url(r'^node/(?P<uri>.+)/editor$', NodeEditor.as_view(), name='cms.editor'), <|code_end|> , generate the next line using the imports in this file: from ..compat import include, patterns, url from .api import LoadApi, NodeApi, NodeEditor, PublishApi, RenderApi, RevisionsApi from .cms import DjediCMS and context (functions, classes, or occasionally code) from other files: # Path: djedi/compat.py # def patterns(*urls): # def parse_bits(parser, bits, params, varargs, varkw, defaults, # takes_context, name): # def generic_tag_compiler(parser, token, params, varargs, varkw, defaults, # name, takes_context, node_class): # def __init__(self, *args, **kwargs): # def get_cache(name): # def getargspec(func): # class TemplateResponse(BaseTemplateResponse): # # Path: djedi/admin/api.py # class LoadApi(JSONResponseMixin, APIView): # # @never_cache # def get(self, request, uri): # """ # Load raw node source from storage. # # JSON Response: # {uri: x, data: y} # """ # uri = self.decode_uri(uri) # node = cio.load(uri) # return self.render_to_json(node) # # class NodeApi(JSONResponseMixin, APIView): # # @never_cache # def get(self, request, uri): # """ # Return published node or specified version. # # JSON Response: # {uri: x, content: y} # """ # uri = self.decode_uri(uri) # node = cio.get(uri, lazy=False) # # if node.content is None: # raise Http404 # # return self.render_to_json({ # 'uri': node.uri, # 'content': node.content # }) # # def post(self, request, uri): # """ # Set node data for uri, return rendered content. # # JSON Response: # {uri: x, content: y} # """ # uri = self.decode_uri(uri) # data, meta = self.get_post_data(request) # meta['author'] = auth.get_username(request) # node = cio.set(uri, data, publish=False, **meta) # return self.render_to_json(node) # # def delete(self, request, uri): # """ # Delete versioned uri and return empty text response on success. # """ # uri = self.decode_uri(uri) # uris = cio.delete(uri) # # if uri not in uris: # raise Http404 # # return self.render_to_response() # # class NodeEditor(JSONResponseMixin, DjediContextMixin, APIView): # # @never_cache # @xframe_options_exempt # def get(self, request, uri): # try: # uri = self.decode_uri(uri) # uri = URI(uri) # plugin = plugins.resolve(uri) # plugin_context = self.get_context_data(uri=uri) # # if isinstance(plugin, DjediPlugin): # plugin_context = plugin.get_editor_context(**plugin_context) # # except UnknownPlugin: # raise Http404 # else: # return self.render_plugin(request, plugin_context) # # @never_cache # def post(self, request, uri): # uri = self.decode_uri(uri) # data, meta = self.get_post_data(request) # meta['author'] = auth.get_username(request) # node = cio.set(uri, data, publish=False, **meta) # # context = cio.load(node.uri) # context['content'] = node.content # # if request.is_ajax(): # return self.render_to_json(context) # else: # return self.render_plugin(request, context) # # def render_plugin(self, request, context): # return TemplateResponse(request, [ # 'djedi/plugins/%s/editor.html' % context['uri'].ext, # 'djedi/plugins/base/editor.html' # ], self.get_context_data(**context)) # # class PublishApi(JSONResponseMixin, APIView): # # def put(self, request, uri): # """ # Publish versioned uri. # # JSON Response: # {uri: x, content: y} # """ # uri = self.decode_uri(uri) # node = cio.publish(uri) # # if not node: # raise Http404 # # return self.render_to_json(node) # # class RenderApi(APIView): # # def post(self, request, ext): # """ # Render data for plugin and return text response. # """ # try: # plugin = plugins.get(ext) # data, meta = self.get_post_data(request) # data = plugin.load(data) # except UnknownPlugin: # raise Http404 # else: # content = plugin.render(data) # return self.render_to_response(content) # # class RevisionsApi(JSONResponseMixin, APIView): # # def get(self, request, uri): # """ # List uri revisions. # # JSON Response: # [[uri, state], ...] # """ # uri = self.decode_uri(uri) # revisions = cio.revisions(uri) # revisions = [list(revision) for revision in revisions] # Convert tuples to lists # return self.render_to_json(revisions) # # Path: djedi/admin/cms.py # class DjediCMS(DjediContextMixin, View): # # @xframe_options_exempt # def get(self, request): # if has_permission(request): # return render(request, 'djedi/cms/cms.html', self.get_context_data()) # else: # raise PermissionDenied . Output only the next line.
url(r'^node/(?P<uri>.+)/load$', LoadApi.as_view(), name='api.load'),
Here is a snippet: <|code_start|> app_name = 'djedi' urlpatterns = patterns( url(r'^$', DjediCMS.as_view(), name='cms'), url(r'^node/(?P<uri>.+)/editor$', NodeEditor.as_view(), name='cms.editor'), url(r'^node/(?P<uri>.+)/load$', LoadApi.as_view(), name='api.load'), url(r'^node/(?P<uri>.+)/publish$', PublishApi.as_view(), name='api.publish'), url(r'^node/(?P<uri>.+)/revisions$', RevisionsApi.as_view(), name='api.revisions'), <|code_end|> . Write the next line using the current file imports: from ..compat import include, patterns, url from .api import LoadApi, NodeApi, NodeEditor, PublishApi, RenderApi, RevisionsApi from .cms import DjediCMS and context from other files: # Path: djedi/compat.py # def patterns(*urls): # def parse_bits(parser, bits, params, varargs, varkw, defaults, # takes_context, name): # def generic_tag_compiler(parser, token, params, varargs, varkw, defaults, # name, takes_context, node_class): # def __init__(self, *args, **kwargs): # def get_cache(name): # def getargspec(func): # class TemplateResponse(BaseTemplateResponse): # # Path: djedi/admin/api.py # class LoadApi(JSONResponseMixin, APIView): # # @never_cache # def get(self, request, uri): # """ # Load raw node source from storage. # # JSON Response: # {uri: x, data: y} # """ # uri = self.decode_uri(uri) # node = cio.load(uri) # return self.render_to_json(node) # # class NodeApi(JSONResponseMixin, APIView): # # @never_cache # def get(self, request, uri): # """ # Return published node or specified version. # # JSON Response: # {uri: x, content: y} # """ # uri = self.decode_uri(uri) # node = cio.get(uri, lazy=False) # # if node.content is None: # raise Http404 # # return self.render_to_json({ # 'uri': node.uri, # 'content': node.content # }) # # def post(self, request, uri): # """ # Set node data for uri, return rendered content. # # JSON Response: # {uri: x, content: y} # """ # uri = self.decode_uri(uri) # data, meta = self.get_post_data(request) # meta['author'] = auth.get_username(request) # node = cio.set(uri, data, publish=False, **meta) # return self.render_to_json(node) # # def delete(self, request, uri): # """ # Delete versioned uri and return empty text response on success. # """ # uri = self.decode_uri(uri) # uris = cio.delete(uri) # # if uri not in uris: # raise Http404 # # return self.render_to_response() # # class NodeEditor(JSONResponseMixin, DjediContextMixin, APIView): # # @never_cache # @xframe_options_exempt # def get(self, request, uri): # try: # uri = self.decode_uri(uri) # uri = URI(uri) # plugin = plugins.resolve(uri) # plugin_context = self.get_context_data(uri=uri) # # if isinstance(plugin, DjediPlugin): # plugin_context = plugin.get_editor_context(**plugin_context) # # except UnknownPlugin: # raise Http404 # else: # return self.render_plugin(request, plugin_context) # # @never_cache # def post(self, request, uri): # uri = self.decode_uri(uri) # data, meta = self.get_post_data(request) # meta['author'] = auth.get_username(request) # node = cio.set(uri, data, publish=False, **meta) # # context = cio.load(node.uri) # context['content'] = node.content # # if request.is_ajax(): # return self.render_to_json(context) # else: # return self.render_plugin(request, context) # # def render_plugin(self, request, context): # return TemplateResponse(request, [ # 'djedi/plugins/%s/editor.html' % context['uri'].ext, # 'djedi/plugins/base/editor.html' # ], self.get_context_data(**context)) # # class PublishApi(JSONResponseMixin, APIView): # # def put(self, request, uri): # """ # Publish versioned uri. # # JSON Response: # {uri: x, content: y} # """ # uri = self.decode_uri(uri) # node = cio.publish(uri) # # if not node: # raise Http404 # # return self.render_to_json(node) # # class RenderApi(APIView): # # def post(self, request, ext): # """ # Render data for plugin and return text response. # """ # try: # plugin = plugins.get(ext) # data, meta = self.get_post_data(request) # data = plugin.load(data) # except UnknownPlugin: # raise Http404 # else: # content = plugin.render(data) # return self.render_to_response(content) # # class RevisionsApi(JSONResponseMixin, APIView): # # def get(self, request, uri): # """ # List uri revisions. # # JSON Response: # [[uri, state], ...] # """ # uri = self.decode_uri(uri) # revisions = cio.revisions(uri) # revisions = [list(revision) for revision in revisions] # Convert tuples to lists # return self.render_to_json(revisions) # # Path: djedi/admin/cms.py # class DjediCMS(DjediContextMixin, View): # # @xframe_options_exempt # def get(self, request): # if has_permission(request): # return render(request, 'djedi/cms/cms.html', self.get_context_data()) # else: # raise PermissionDenied , which may include functions, classes, or code. Output only the next line.
url(r'^node/(?P<uri>.+)$', NodeApi.as_view(), name='api'),
Next line prediction: <|code_start|> app_name = 'djedi' urlpatterns = patterns( url(r'^$', DjediCMS.as_view(), name='cms'), <|code_end|> . Use current file imports: (from ..compat import include, patterns, url from .api import LoadApi, NodeApi, NodeEditor, PublishApi, RenderApi, RevisionsApi from .cms import DjediCMS) and context including class names, function names, or small code snippets from other files: # Path: djedi/compat.py # def patterns(*urls): # def parse_bits(parser, bits, params, varargs, varkw, defaults, # takes_context, name): # def generic_tag_compiler(parser, token, params, varargs, varkw, defaults, # name, takes_context, node_class): # def __init__(self, *args, **kwargs): # def get_cache(name): # def getargspec(func): # class TemplateResponse(BaseTemplateResponse): # # Path: djedi/admin/api.py # class LoadApi(JSONResponseMixin, APIView): # # @never_cache # def get(self, request, uri): # """ # Load raw node source from storage. # # JSON Response: # {uri: x, data: y} # """ # uri = self.decode_uri(uri) # node = cio.load(uri) # return self.render_to_json(node) # # class NodeApi(JSONResponseMixin, APIView): # # @never_cache # def get(self, request, uri): # """ # Return published node or specified version. # # JSON Response: # {uri: x, content: y} # """ # uri = self.decode_uri(uri) # node = cio.get(uri, lazy=False) # # if node.content is None: # raise Http404 # # return self.render_to_json({ # 'uri': node.uri, # 'content': node.content # }) # # def post(self, request, uri): # """ # Set node data for uri, return rendered content. # # JSON Response: # {uri: x, content: y} # """ # uri = self.decode_uri(uri) # data, meta = self.get_post_data(request) # meta['author'] = auth.get_username(request) # node = cio.set(uri, data, publish=False, **meta) # return self.render_to_json(node) # # def delete(self, request, uri): # """ # Delete versioned uri and return empty text response on success. # """ # uri = self.decode_uri(uri) # uris = cio.delete(uri) # # if uri not in uris: # raise Http404 # # return self.render_to_response() # # class NodeEditor(JSONResponseMixin, DjediContextMixin, APIView): # # @never_cache # @xframe_options_exempt # def get(self, request, uri): # try: # uri = self.decode_uri(uri) # uri = URI(uri) # plugin = plugins.resolve(uri) # plugin_context = self.get_context_data(uri=uri) # # if isinstance(plugin, DjediPlugin): # plugin_context = plugin.get_editor_context(**plugin_context) # # except UnknownPlugin: # raise Http404 # else: # return self.render_plugin(request, plugin_context) # # @never_cache # def post(self, request, uri): # uri = self.decode_uri(uri) # data, meta = self.get_post_data(request) # meta['author'] = auth.get_username(request) # node = cio.set(uri, data, publish=False, **meta) # # context = cio.load(node.uri) # context['content'] = node.content # # if request.is_ajax(): # return self.render_to_json(context) # else: # return self.render_plugin(request, context) # # def render_plugin(self, request, context): # return TemplateResponse(request, [ # 'djedi/plugins/%s/editor.html' % context['uri'].ext, # 'djedi/plugins/base/editor.html' # ], self.get_context_data(**context)) # # class PublishApi(JSONResponseMixin, APIView): # # def put(self, request, uri): # """ # Publish versioned uri. # # JSON Response: # {uri: x, content: y} # """ # uri = self.decode_uri(uri) # node = cio.publish(uri) # # if not node: # raise Http404 # # return self.render_to_json(node) # # class RenderApi(APIView): # # def post(self, request, ext): # """ # Render data for plugin and return text response. # """ # try: # plugin = plugins.get(ext) # data, meta = self.get_post_data(request) # data = plugin.load(data) # except UnknownPlugin: # raise Http404 # else: # content = plugin.render(data) # return self.render_to_response(content) # # class RevisionsApi(JSONResponseMixin, APIView): # # def get(self, request, uri): # """ # List uri revisions. # # JSON Response: # [[uri, state], ...] # """ # uri = self.decode_uri(uri) # revisions = cio.revisions(uri) # revisions = [list(revision) for revision in revisions] # Convert tuples to lists # return self.render_to_json(revisions) # # Path: djedi/admin/cms.py # class DjediCMS(DjediContextMixin, View): # # @xframe_options_exempt # def get(self, request): # if has_permission(request): # return render(request, 'djedi/cms/cms.html', self.get_context_data()) # else: # raise PermissionDenied . Output only the next line.
url(r'^node/(?P<uri>.+)/editor$', NodeEditor.as_view(), name='cms.editor'),
Predict the next line after this snippet: <|code_start|> app_name = 'djedi' urlpatterns = patterns( url(r'^$', DjediCMS.as_view(), name='cms'), url(r'^node/(?P<uri>.+)/editor$', NodeEditor.as_view(), name='cms.editor'), url(r'^node/(?P<uri>.+)/load$', LoadApi.as_view(), name='api.load'), <|code_end|> using the current file's imports: from ..compat import include, patterns, url from .api import LoadApi, NodeApi, NodeEditor, PublishApi, RenderApi, RevisionsApi from .cms import DjediCMS and any relevant context from other files: # Path: djedi/compat.py # def patterns(*urls): # def parse_bits(parser, bits, params, varargs, varkw, defaults, # takes_context, name): # def generic_tag_compiler(parser, token, params, varargs, varkw, defaults, # name, takes_context, node_class): # def __init__(self, *args, **kwargs): # def get_cache(name): # def getargspec(func): # class TemplateResponse(BaseTemplateResponse): # # Path: djedi/admin/api.py # class LoadApi(JSONResponseMixin, APIView): # # @never_cache # def get(self, request, uri): # """ # Load raw node source from storage. # # JSON Response: # {uri: x, data: y} # """ # uri = self.decode_uri(uri) # node = cio.load(uri) # return self.render_to_json(node) # # class NodeApi(JSONResponseMixin, APIView): # # @never_cache # def get(self, request, uri): # """ # Return published node or specified version. # # JSON Response: # {uri: x, content: y} # """ # uri = self.decode_uri(uri) # node = cio.get(uri, lazy=False) # # if node.content is None: # raise Http404 # # return self.render_to_json({ # 'uri': node.uri, # 'content': node.content # }) # # def post(self, request, uri): # """ # Set node data for uri, return rendered content. # # JSON Response: # {uri: x, content: y} # """ # uri = self.decode_uri(uri) # data, meta = self.get_post_data(request) # meta['author'] = auth.get_username(request) # node = cio.set(uri, data, publish=False, **meta) # return self.render_to_json(node) # # def delete(self, request, uri): # """ # Delete versioned uri and return empty text response on success. # """ # uri = self.decode_uri(uri) # uris = cio.delete(uri) # # if uri not in uris: # raise Http404 # # return self.render_to_response() # # class NodeEditor(JSONResponseMixin, DjediContextMixin, APIView): # # @never_cache # @xframe_options_exempt # def get(self, request, uri): # try: # uri = self.decode_uri(uri) # uri = URI(uri) # plugin = plugins.resolve(uri) # plugin_context = self.get_context_data(uri=uri) # # if isinstance(plugin, DjediPlugin): # plugin_context = plugin.get_editor_context(**plugin_context) # # except UnknownPlugin: # raise Http404 # else: # return self.render_plugin(request, plugin_context) # # @never_cache # def post(self, request, uri): # uri = self.decode_uri(uri) # data, meta = self.get_post_data(request) # meta['author'] = auth.get_username(request) # node = cio.set(uri, data, publish=False, **meta) # # context = cio.load(node.uri) # context['content'] = node.content # # if request.is_ajax(): # return self.render_to_json(context) # else: # return self.render_plugin(request, context) # # def render_plugin(self, request, context): # return TemplateResponse(request, [ # 'djedi/plugins/%s/editor.html' % context['uri'].ext, # 'djedi/plugins/base/editor.html' # ], self.get_context_data(**context)) # # class PublishApi(JSONResponseMixin, APIView): # # def put(self, request, uri): # """ # Publish versioned uri. # # JSON Response: # {uri: x, content: y} # """ # uri = self.decode_uri(uri) # node = cio.publish(uri) # # if not node: # raise Http404 # # return self.render_to_json(node) # # class RenderApi(APIView): # # def post(self, request, ext): # """ # Render data for plugin and return text response. # """ # try: # plugin = plugins.get(ext) # data, meta = self.get_post_data(request) # data = plugin.load(data) # except UnknownPlugin: # raise Http404 # else: # content = plugin.render(data) # return self.render_to_response(content) # # class RevisionsApi(JSONResponseMixin, APIView): # # def get(self, request, uri): # """ # List uri revisions. # # JSON Response: # [[uri, state], ...] # """ # uri = self.decode_uri(uri) # revisions = cio.revisions(uri) # revisions = [list(revision) for revision in revisions] # Convert tuples to lists # return self.render_to_json(revisions) # # Path: djedi/admin/cms.py # class DjediCMS(DjediContextMixin, View): # # @xframe_options_exempt # def get(self, request): # if has_permission(request): # return render(request, 'djedi/cms/cms.html', self.get_context_data()) # else: # raise PermissionDenied . Output only the next line.
url(r'^node/(?P<uri>.+)/publish$', PublishApi.as_view(), name='api.publish'),
Predict the next line for this snippet: <|code_start|> app_name = 'djedi' urlpatterns = patterns( url(r'^$', DjediCMS.as_view(), name='cms'), url(r'^node/(?P<uri>.+)/editor$', NodeEditor.as_view(), name='cms.editor'), url(r'^node/(?P<uri>.+)/load$', LoadApi.as_view(), name='api.load'), url(r'^node/(?P<uri>.+)/publish$', PublishApi.as_view(), name='api.publish'), url(r'^node/(?P<uri>.+)/revisions$', RevisionsApi.as_view(), name='api.revisions'), url(r'^node/(?P<uri>.+)$', NodeApi.as_view(), name='api'), <|code_end|> with the help of current file imports: from ..compat import include, patterns, url from .api import LoadApi, NodeApi, NodeEditor, PublishApi, RenderApi, RevisionsApi from .cms import DjediCMS and context from other files: # Path: djedi/compat.py # def patterns(*urls): # def parse_bits(parser, bits, params, varargs, varkw, defaults, # takes_context, name): # def generic_tag_compiler(parser, token, params, varargs, varkw, defaults, # name, takes_context, node_class): # def __init__(self, *args, **kwargs): # def get_cache(name): # def getargspec(func): # class TemplateResponse(BaseTemplateResponse): # # Path: djedi/admin/api.py # class LoadApi(JSONResponseMixin, APIView): # # @never_cache # def get(self, request, uri): # """ # Load raw node source from storage. # # JSON Response: # {uri: x, data: y} # """ # uri = self.decode_uri(uri) # node = cio.load(uri) # return self.render_to_json(node) # # class NodeApi(JSONResponseMixin, APIView): # # @never_cache # def get(self, request, uri): # """ # Return published node or specified version. # # JSON Response: # {uri: x, content: y} # """ # uri = self.decode_uri(uri) # node = cio.get(uri, lazy=False) # # if node.content is None: # raise Http404 # # return self.render_to_json({ # 'uri': node.uri, # 'content': node.content # }) # # def post(self, request, uri): # """ # Set node data for uri, return rendered content. # # JSON Response: # {uri: x, content: y} # """ # uri = self.decode_uri(uri) # data, meta = self.get_post_data(request) # meta['author'] = auth.get_username(request) # node = cio.set(uri, data, publish=False, **meta) # return self.render_to_json(node) # # def delete(self, request, uri): # """ # Delete versioned uri and return empty text response on success. # """ # uri = self.decode_uri(uri) # uris = cio.delete(uri) # # if uri not in uris: # raise Http404 # # return self.render_to_response() # # class NodeEditor(JSONResponseMixin, DjediContextMixin, APIView): # # @never_cache # @xframe_options_exempt # def get(self, request, uri): # try: # uri = self.decode_uri(uri) # uri = URI(uri) # plugin = plugins.resolve(uri) # plugin_context = self.get_context_data(uri=uri) # # if isinstance(plugin, DjediPlugin): # plugin_context = plugin.get_editor_context(**plugin_context) # # except UnknownPlugin: # raise Http404 # else: # return self.render_plugin(request, plugin_context) # # @never_cache # def post(self, request, uri): # uri = self.decode_uri(uri) # data, meta = self.get_post_data(request) # meta['author'] = auth.get_username(request) # node = cio.set(uri, data, publish=False, **meta) # # context = cio.load(node.uri) # context['content'] = node.content # # if request.is_ajax(): # return self.render_to_json(context) # else: # return self.render_plugin(request, context) # # def render_plugin(self, request, context): # return TemplateResponse(request, [ # 'djedi/plugins/%s/editor.html' % context['uri'].ext, # 'djedi/plugins/base/editor.html' # ], self.get_context_data(**context)) # # class PublishApi(JSONResponseMixin, APIView): # # def put(self, request, uri): # """ # Publish versioned uri. # # JSON Response: # {uri: x, content: y} # """ # uri = self.decode_uri(uri) # node = cio.publish(uri) # # if not node: # raise Http404 # # return self.render_to_json(node) # # class RenderApi(APIView): # # def post(self, request, ext): # """ # Render data for plugin and return text response. # """ # try: # plugin = plugins.get(ext) # data, meta = self.get_post_data(request) # data = plugin.load(data) # except UnknownPlugin: # raise Http404 # else: # content = plugin.render(data) # return self.render_to_response(content) # # class RevisionsApi(JSONResponseMixin, APIView): # # def get(self, request, uri): # """ # List uri revisions. # # JSON Response: # [[uri, state], ...] # """ # uri = self.decode_uri(uri) # revisions = cio.revisions(uri) # revisions = [list(revision) for revision in revisions] # Convert tuples to lists # return self.render_to_json(revisions) # # Path: djedi/admin/cms.py # class DjediCMS(DjediContextMixin, View): # # @xframe_options_exempt # def get(self, request): # if has_permission(request): # return render(request, 'djedi/cms/cms.html', self.get_context_data()) # else: # raise PermissionDenied , which may contain function names, class names, or code. Output only the next line.
url(r'^plugin/(?P<ext>\w+)$', RenderApi.as_view(), name='api.render'),
Using the snippet: <|code_start|> app_name = 'djedi' urlpatterns = patterns( url(r'^$', DjediCMS.as_view(), name='cms'), url(r'^node/(?P<uri>.+)/editor$', NodeEditor.as_view(), name='cms.editor'), url(r'^node/(?P<uri>.+)/load$', LoadApi.as_view(), name='api.load'), url(r'^node/(?P<uri>.+)/publish$', PublishApi.as_view(), name='api.publish'), <|code_end|> , determine the next line of code. You have imports: from ..compat import include, patterns, url from .api import LoadApi, NodeApi, NodeEditor, PublishApi, RenderApi, RevisionsApi from .cms import DjediCMS and context (class names, function names, or code) available: # Path: djedi/compat.py # def patterns(*urls): # def parse_bits(parser, bits, params, varargs, varkw, defaults, # takes_context, name): # def generic_tag_compiler(parser, token, params, varargs, varkw, defaults, # name, takes_context, node_class): # def __init__(self, *args, **kwargs): # def get_cache(name): # def getargspec(func): # class TemplateResponse(BaseTemplateResponse): # # Path: djedi/admin/api.py # class LoadApi(JSONResponseMixin, APIView): # # @never_cache # def get(self, request, uri): # """ # Load raw node source from storage. # # JSON Response: # {uri: x, data: y} # """ # uri = self.decode_uri(uri) # node = cio.load(uri) # return self.render_to_json(node) # # class NodeApi(JSONResponseMixin, APIView): # # @never_cache # def get(self, request, uri): # """ # Return published node or specified version. # # JSON Response: # {uri: x, content: y} # """ # uri = self.decode_uri(uri) # node = cio.get(uri, lazy=False) # # if node.content is None: # raise Http404 # # return self.render_to_json({ # 'uri': node.uri, # 'content': node.content # }) # # def post(self, request, uri): # """ # Set node data for uri, return rendered content. # # JSON Response: # {uri: x, content: y} # """ # uri = self.decode_uri(uri) # data, meta = self.get_post_data(request) # meta['author'] = auth.get_username(request) # node = cio.set(uri, data, publish=False, **meta) # return self.render_to_json(node) # # def delete(self, request, uri): # """ # Delete versioned uri and return empty text response on success. # """ # uri = self.decode_uri(uri) # uris = cio.delete(uri) # # if uri not in uris: # raise Http404 # # return self.render_to_response() # # class NodeEditor(JSONResponseMixin, DjediContextMixin, APIView): # # @never_cache # @xframe_options_exempt # def get(self, request, uri): # try: # uri = self.decode_uri(uri) # uri = URI(uri) # plugin = plugins.resolve(uri) # plugin_context = self.get_context_data(uri=uri) # # if isinstance(plugin, DjediPlugin): # plugin_context = plugin.get_editor_context(**plugin_context) # # except UnknownPlugin: # raise Http404 # else: # return self.render_plugin(request, plugin_context) # # @never_cache # def post(self, request, uri): # uri = self.decode_uri(uri) # data, meta = self.get_post_data(request) # meta['author'] = auth.get_username(request) # node = cio.set(uri, data, publish=False, **meta) # # context = cio.load(node.uri) # context['content'] = node.content # # if request.is_ajax(): # return self.render_to_json(context) # else: # return self.render_plugin(request, context) # # def render_plugin(self, request, context): # return TemplateResponse(request, [ # 'djedi/plugins/%s/editor.html' % context['uri'].ext, # 'djedi/plugins/base/editor.html' # ], self.get_context_data(**context)) # # class PublishApi(JSONResponseMixin, APIView): # # def put(self, request, uri): # """ # Publish versioned uri. # # JSON Response: # {uri: x, content: y} # """ # uri = self.decode_uri(uri) # node = cio.publish(uri) # # if not node: # raise Http404 # # return self.render_to_json(node) # # class RenderApi(APIView): # # def post(self, request, ext): # """ # Render data for plugin and return text response. # """ # try: # plugin = plugins.get(ext) # data, meta = self.get_post_data(request) # data = plugin.load(data) # except UnknownPlugin: # raise Http404 # else: # content = plugin.render(data) # return self.render_to_response(content) # # class RevisionsApi(JSONResponseMixin, APIView): # # def get(self, request, uri): # """ # List uri revisions. # # JSON Response: # [[uri, state], ...] # """ # uri = self.decode_uri(uri) # revisions = cio.revisions(uri) # revisions = [list(revision) for revision in revisions] # Convert tuples to lists # return self.render_to_json(revisions) # # Path: djedi/admin/cms.py # class DjediCMS(DjediContextMixin, View): # # @xframe_options_exempt # def get(self, request): # if has_permission(request): # return render(request, 'djedi/cms/cms.html', self.get_context_data()) # else: # raise PermissionDenied . Output only the next line.
url(r'^node/(?P<uri>.+)/revisions$', RevisionsApi.as_view(), name='api.revisions'),
Predict the next line after this snippet: <|code_start|> {% endblocknode %} """ context = {'user': User(first_name=u'Jonas', last_name=u'Lundberg')} html = self.render(source, context) assert html == u'Hej Jonas Lundberg!' with cio.env(i18n='en-us'): html = self.render(source, context) assert html == u'Hello Jonas Lundberg!' html = self.render(u""" {% blocknode 'page/title' edit=False %} Hello {name}! {% endblocknode %} """) assert html == u'Hej {name}!' def test_collected_nodes(self): source = u""" {% node 'page/title' edit=False %} {% node 'page/title' default='fallback' edit=False %} {% node 'page/body' edit=False %} """ pipeline.history.clear() self.render(source) assert len(pipeline.history) == 2 def test_invalid_lazy_tag(self): with self.assertRaises(TemplateSyntaxError): <|code_end|> using the current file's imports: import cio from django.contrib.auth.models import User from django.template import TemplateSyntaxError from cio.backends import cache from cio.pipeline import pipeline from djedi.templatetags.template import register from djedi.tests.base import DjediTest, AssertionMixin from .compat import cmpt_context, get_template_from_string and any relevant context from other files: # Path: djedi/templatetags/template.py # def lazy_tag(self, func=None, takes_context=None, name=None, node_class=None): # def dec(func): # def __init__(self, takes_context, args, kwargs): # def get_resolved_arguments(self, context): # def render(self, context): # class SimpleNode(Node): # # Path: djedi/tests/base.py # class DjediTest(TransactionTestCase): # # def setUp(self): # from cio.environment import env # from cio.backends import cache # from cio.pipeline import pipeline # from cio.plugins import plugins # # env.reset() # cache.clear() # pipeline.clear() # plugins.load() # # def tearDown(self): # shutil.rmtree(settings.MEDIA_ROOT, ignore_errors=True) # # @contextmanager # def settings(self, *args, **kwargs): # with super(DjediTest, self).settings(*args, **kwargs): # with cio_settings(): # configure() # yield # # class AssertionMixin(object): # # def assertKeys(self, dict, *keys): # self.assertEqual(set(dict.keys()), set(keys)) # # @contextmanager # def assertCache(self, calls=-1, hits=-1, misses=-1, sets=-1): # from cio.backends import cache # # _cache = cache.backend._cache # # _cache.calls = 0 # _cache.hits = 0 # _cache.misses = 0 # _cache.sets = 0 # # yield # # if calls >= 0: # assert _cache.calls == calls, '%s != %s' % (_cache.calls, calls) # if hits >= 0: # assert _cache.hits == hits, '%s != %s' % (_cache.hits, hits) # if misses >= 0: # assert _cache.misses == misses, '%s != %s' % (_cache.misses, misses) # if sets >= 0: # assert _cache.sets == sets, '%s != %s' % (_cache.sets, sets) # # @contextmanager # def assertDB(self, calls=-1, selects=-1, inserts=-1, updates=-1): # from django.db import connection # # pre_debug_cursor = getattr(connection, DEBUG_CURSOR_ATTR) # setattr(connection, DEBUG_CURSOR_ATTR, True) # pre_num_queries = len(connection.queries) # # yield # # queries = connection.queries[pre_num_queries:] # num_queries = len(queries) # setattr(connection, DEBUG_CURSOR_ATTR, pre_debug_cursor) # # if calls >= 0: # assert num_queries == calls, '%s != %s' % (num_queries, calls) # if selects >= 0: # num_selects = len([q for q in queries if q['sql'].startswith('SELECT')]) # assert num_selects == selects, '%s != %s' % (num_selects, selects) # if inserts >= 0: # num_inserts = len([q for q in queries if q['sql'].startswith('INSERT')]) # assert num_inserts == inserts, '%s != %s' % (num_inserts, inserts) # if updates >= 0: # num_updates = len([q for q in queries if q['sql'].startswith('UPDATE')]) # assert num_updates == updates, '%s != %s' % (num_updates, updates) # # def assertRenderedMarkdown(self, value, source): # if cio.PY26: # self.assertEqual(value, source) # Markdown lacks Support for python 2.6 # else: # from markdown import markdown # rendered = markdown(source) # self.assertEqual(value, rendered) # # Path: djedi/tests/compat.py # def cmpt_context(context): # if django.VERSION >= (1, 8): # return context # # from django.template import Context # return Context(context) # # def get_template_from_string(template_code): # return engines['django'].from_string(template_code) . Output only the next line.
register.lazy_tag('')
Predict the next line for this snippet: <|code_start|> class TagTest(DjediTest, AssertionMixin): def render(self, source, context=None): source = u'{% load djedi_tags %}' + source.strip() <|code_end|> with the help of current file imports: import cio from django.contrib.auth.models import User from django.template import TemplateSyntaxError from cio.backends import cache from cio.pipeline import pipeline from djedi.templatetags.template import register from djedi.tests.base import DjediTest, AssertionMixin from .compat import cmpt_context, get_template_from_string and context from other files: # Path: djedi/templatetags/template.py # def lazy_tag(self, func=None, takes_context=None, name=None, node_class=None): # def dec(func): # def __init__(self, takes_context, args, kwargs): # def get_resolved_arguments(self, context): # def render(self, context): # class SimpleNode(Node): # # Path: djedi/tests/base.py # class DjediTest(TransactionTestCase): # # def setUp(self): # from cio.environment import env # from cio.backends import cache # from cio.pipeline import pipeline # from cio.plugins import plugins # # env.reset() # cache.clear() # pipeline.clear() # plugins.load() # # def tearDown(self): # shutil.rmtree(settings.MEDIA_ROOT, ignore_errors=True) # # @contextmanager # def settings(self, *args, **kwargs): # with super(DjediTest, self).settings(*args, **kwargs): # with cio_settings(): # configure() # yield # # class AssertionMixin(object): # # def assertKeys(self, dict, *keys): # self.assertEqual(set(dict.keys()), set(keys)) # # @contextmanager # def assertCache(self, calls=-1, hits=-1, misses=-1, sets=-1): # from cio.backends import cache # # _cache = cache.backend._cache # # _cache.calls = 0 # _cache.hits = 0 # _cache.misses = 0 # _cache.sets = 0 # # yield # # if calls >= 0: # assert _cache.calls == calls, '%s != %s' % (_cache.calls, calls) # if hits >= 0: # assert _cache.hits == hits, '%s != %s' % (_cache.hits, hits) # if misses >= 0: # assert _cache.misses == misses, '%s != %s' % (_cache.misses, misses) # if sets >= 0: # assert _cache.sets == sets, '%s != %s' % (_cache.sets, sets) # # @contextmanager # def assertDB(self, calls=-1, selects=-1, inserts=-1, updates=-1): # from django.db import connection # # pre_debug_cursor = getattr(connection, DEBUG_CURSOR_ATTR) # setattr(connection, DEBUG_CURSOR_ATTR, True) # pre_num_queries = len(connection.queries) # # yield # # queries = connection.queries[pre_num_queries:] # num_queries = len(queries) # setattr(connection, DEBUG_CURSOR_ATTR, pre_debug_cursor) # # if calls >= 0: # assert num_queries == calls, '%s != %s' % (num_queries, calls) # if selects >= 0: # num_selects = len([q for q in queries if q['sql'].startswith('SELECT')]) # assert num_selects == selects, '%s != %s' % (num_selects, selects) # if inserts >= 0: # num_inserts = len([q for q in queries if q['sql'].startswith('INSERT')]) # assert num_inserts == inserts, '%s != %s' % (num_inserts, inserts) # if updates >= 0: # num_updates = len([q for q in queries if q['sql'].startswith('UPDATE')]) # assert num_updates == updates, '%s != %s' % (num_updates, updates) # # def assertRenderedMarkdown(self, value, source): # if cio.PY26: # self.assertEqual(value, source) # Markdown lacks Support for python 2.6 # else: # from markdown import markdown # rendered = markdown(source) # self.assertEqual(value, rendered) # # Path: djedi/tests/compat.py # def cmpt_context(context): # if django.VERSION >= (1, 8): # return context # # from django.template import Context # return Context(context) # # def get_template_from_string(template_code): # return engines['django'].from_string(template_code) , which may contain function names, class names, or code. Output only the next line.
context = cmpt_context(context or {})
Here is a snippet: <|code_start|> class TagTest(DjediTest, AssertionMixin): def render(self, source, context=None): source = u'{% load djedi_tags %}' + source.strip() context = cmpt_context(context or {}) <|code_end|> . Write the next line using the current file imports: import cio from django.contrib.auth.models import User from django.template import TemplateSyntaxError from cio.backends import cache from cio.pipeline import pipeline from djedi.templatetags.template import register from djedi.tests.base import DjediTest, AssertionMixin from .compat import cmpt_context, get_template_from_string and context from other files: # Path: djedi/templatetags/template.py # def lazy_tag(self, func=None, takes_context=None, name=None, node_class=None): # def dec(func): # def __init__(self, takes_context, args, kwargs): # def get_resolved_arguments(self, context): # def render(self, context): # class SimpleNode(Node): # # Path: djedi/tests/base.py # class DjediTest(TransactionTestCase): # # def setUp(self): # from cio.environment import env # from cio.backends import cache # from cio.pipeline import pipeline # from cio.plugins import plugins # # env.reset() # cache.clear() # pipeline.clear() # plugins.load() # # def tearDown(self): # shutil.rmtree(settings.MEDIA_ROOT, ignore_errors=True) # # @contextmanager # def settings(self, *args, **kwargs): # with super(DjediTest, self).settings(*args, **kwargs): # with cio_settings(): # configure() # yield # # class AssertionMixin(object): # # def assertKeys(self, dict, *keys): # self.assertEqual(set(dict.keys()), set(keys)) # # @contextmanager # def assertCache(self, calls=-1, hits=-1, misses=-1, sets=-1): # from cio.backends import cache # # _cache = cache.backend._cache # # _cache.calls = 0 # _cache.hits = 0 # _cache.misses = 0 # _cache.sets = 0 # # yield # # if calls >= 0: # assert _cache.calls == calls, '%s != %s' % (_cache.calls, calls) # if hits >= 0: # assert _cache.hits == hits, '%s != %s' % (_cache.hits, hits) # if misses >= 0: # assert _cache.misses == misses, '%s != %s' % (_cache.misses, misses) # if sets >= 0: # assert _cache.sets == sets, '%s != %s' % (_cache.sets, sets) # # @contextmanager # def assertDB(self, calls=-1, selects=-1, inserts=-1, updates=-1): # from django.db import connection # # pre_debug_cursor = getattr(connection, DEBUG_CURSOR_ATTR) # setattr(connection, DEBUG_CURSOR_ATTR, True) # pre_num_queries = len(connection.queries) # # yield # # queries = connection.queries[pre_num_queries:] # num_queries = len(queries) # setattr(connection, DEBUG_CURSOR_ATTR, pre_debug_cursor) # # if calls >= 0: # assert num_queries == calls, '%s != %s' % (num_queries, calls) # if selects >= 0: # num_selects = len([q for q in queries if q['sql'].startswith('SELECT')]) # assert num_selects == selects, '%s != %s' % (num_selects, selects) # if inserts >= 0: # num_inserts = len([q for q in queries if q['sql'].startswith('INSERT')]) # assert num_inserts == inserts, '%s != %s' % (num_inserts, inserts) # if updates >= 0: # num_updates = len([q for q in queries if q['sql'].startswith('UPDATE')]) # assert num_updates == updates, '%s != %s' % (num_updates, updates) # # def assertRenderedMarkdown(self, value, source): # if cio.PY26: # self.assertEqual(value, source) # Markdown lacks Support for python 2.6 # else: # from markdown import markdown # rendered = markdown(source) # self.assertEqual(value, rendered) # # Path: djedi/tests/compat.py # def cmpt_context(context): # if django.VERSION >= (1, 8): # return context # # from django.template import Context # return Context(context) # # def get_template_from_string(template_code): # return engines['django'].from_string(template_code) , which may include functions, classes, or code. Output only the next line.
return get_template_from_string(source).render(context).strip()
Given the following code snippet before the placeholder: <|code_start|>def get_custom_render_widget(cls): class CustomRenderWidget(cls): def render(self, *args, **kwargs): name = kwargs.pop("name", None) if not name: name = args[0] args = args[1:] name = deprefix(name) return super(CustomRenderWidget, self).render( "data[%s]" % name, *args, **kwargs ) return CustomRenderWidget class BaseEditorForm(forms.Form): def __init__(self, *args, **kwargs): super(BaseEditorForm, self).__init__(*args, **kwargs) for field in list(self.fields.keys()): self.fields[field].widget.__class__ = get_custom_render_widget( self.fields[field].widget.__class__ ) <|code_end|> , predict the next line using imports from the current file: import json from djedi.plugins.base import DjediPlugin from django import forms and context including class names, function names, and sometimes code from other files: # Path: djedi/plugins/base.py # class DjediPlugin(BasePlugin): # def get_editor_context(self, **kwargs): # """ # Returns custom context # """ # return kwargs . Output only the next line.
class FormsBasePlugin(DjediPlugin):
Predict the next line for this snippet: <|code_start|> def render_embed(nodes=None, request=None): context = {} if nodes is None: try: prefix = request.build_absolute_uri("/").rstrip("/") context.update( { "cms_url": prefix + reverse("admin:djedi:cms"), "exclude_json_nodes": True, } ) output = render(request, "djedi/cms/embed.html", context) <|code_end|> with the help of current file imports: import json from django.core.exceptions import ImproperlyConfigured from ..compat import NoReverseMatch, render, render_to_string, reverse and context from other files: # Path: djedi/compat.py # def patterns(*urls): # def parse_bits(parser, bits, params, varargs, varkw, defaults, # takes_context, name): # def generic_tag_compiler(parser, token, params, varargs, varkw, defaults, # name, takes_context, node_class): # def __init__(self, *args, **kwargs): # def get_cache(name): # def getargspec(func): # class TemplateResponse(BaseTemplateResponse): , which may contain function names, class names, or code. Output only the next line.
except NoReverseMatch:
Predict the next line after this snippet: <|code_start|> def render_embed(nodes=None, request=None): context = {} if nodes is None: try: prefix = request.build_absolute_uri("/").rstrip("/") context.update( { "cms_url": prefix + reverse("admin:djedi:cms"), "exclude_json_nodes": True, } ) <|code_end|> using the current file's imports: import json from django.core.exceptions import ImproperlyConfigured from ..compat import NoReverseMatch, render, render_to_string, reverse and any relevant context from other files: # Path: djedi/compat.py # def patterns(*urls): # def parse_bits(parser, bits, params, varargs, varkw, defaults, # takes_context, name): # def generic_tag_compiler(parser, token, params, varargs, varkw, defaults, # name, takes_context, node_class): # def __init__(self, *args, **kwargs): # def get_cache(name): # def getargspec(func): # class TemplateResponse(BaseTemplateResponse): . Output only the next line.
output = render(request, "djedi/cms/embed.html", context)
Given the following code snippet before the placeholder: <|code_start|> def render_embed(nodes=None, request=None): context = {} if nodes is None: try: prefix = request.build_absolute_uri("/").rstrip("/") context.update( { "cms_url": prefix + reverse("admin:djedi:cms"), "exclude_json_nodes": True, } ) output = render(request, "djedi/cms/embed.html", context) except NoReverseMatch: raise ImproperlyConfigured( "Could not find djedi in your url conf, " "enable django admin or include " "djedi.urls within the admin namespace." ) else: context.update( { "cms_url": reverse("admin:djedi:cms"), "exclude_json_nodes": False, "json_nodes": json.dumps(nodes).replace("</", "\\x3C/"), } ) <|code_end|> , predict the next line using imports from the current file: import json from django.core.exceptions import ImproperlyConfigured from ..compat import NoReverseMatch, render, render_to_string, reverse and context including class names, function names, and sometimes code from other files: # Path: djedi/compat.py # def patterns(*urls): # def parse_bits(parser, bits, params, varargs, varkw, defaults, # takes_context, name): # def generic_tag_compiler(parser, token, params, varargs, varkw, defaults, # name, takes_context, node_class): # def __init__(self, *args, **kwargs): # def get_cache(name): # def getargspec(func): # class TemplateResponse(BaseTemplateResponse): . Output only the next line.
output = render_to_string("djedi/cms/embed.html", context)
Based on the snippet: <|code_start|> def render_embed(nodes=None, request=None): context = {} if nodes is None: try: prefix = request.build_absolute_uri("/").rstrip("/") context.update( { <|code_end|> , predict the immediate next line with the help of imports: import json from django.core.exceptions import ImproperlyConfigured from ..compat import NoReverseMatch, render, render_to_string, reverse and context (classes, functions, sometimes code) from other files: # Path: djedi/compat.py # def patterns(*urls): # def parse_bits(parser, bits, params, varargs, varkw, defaults, # takes_context, name): # def generic_tag_compiler(parser, token, params, varargs, varkw, defaults, # name, takes_context, node_class): # def __init__(self, *args, **kwargs): # def get_cache(name): # def getargspec(func): # class TemplateResponse(BaseTemplateResponse): . Output only the next line.
"cms_url": prefix + reverse("admin:djedi:cms"),
Given snippet: <|code_start|> def test_render(self): response = self.post('api.render', 'foo', {'data': u'# Djedi'}) assert response.status_code == 404 response = self.post('api.render', 'md', {'data': u'# Djedi'}) assert response.status_code == 200 self.assertRenderedMarkdown(smart_unicode(response.content), u'# Djedi') response = self.post('api.render', 'img', {'data': json.dumps({ 'url': '/foo/bar.png', 'width': '64', 'height': '64' })}) self.assertEqual(response.status_code, 200) self.assertEqual(smart_unicode(response.content), u'<img alt="" height="64" src="/foo/bar.png" width="64" />') def test_editor(self): response = self.get('cms.editor', 'sv-se@page/title.foo') self.assertEqual(response.status_code, 404) response = self.get('cms.editor', 'sv-se@page/title') self.assertEqual(response.status_code, 404) for ext in plugins: response = self.get('cms.editor', 'sv-se@page/title.' + ext) self.assertEqual(response.status_code, 200) if ext == 'img': assert set(response.context_data.keys()) == set(('THEME', 'VERSION', 'uri', 'forms')) assert 'HTML' in response.context_data['forms'] <|code_end|> , continue by predicting the next line. Consider current file imports: import os import simplejson as json import cio import cio.conf from django.core.files import File from django.test import Client from django.utils.http import urlquote from cio.backends import storage from cio.backends.exceptions import NodeDoesNotExist, PersistenceError from cio.plugins import plugins from cio.utils.uri import URI from djedi.plugins.form import BaseEditorForm from djedi.tests.base import ClientTest, DjediTest, UserMixin from djedi.utils.encoding import smart_unicode from ..compat import reverse from djedi.plugins.img import DataForm and context: # Path: djedi/plugins/form.py # class BaseEditorForm(forms.Form): # def __init__(self, *args, **kwargs): # super(BaseEditorForm, self).__init__(*args, **kwargs) # # for field in list(self.fields.keys()): # self.fields[field].widget.__class__ = get_custom_render_widget( # self.fields[field].widget.__class__ # ) # # Path: djedi/tests/base.py # class ClientTest(DjediTest, UserMixin, AssertionMixin): # # def setUp(self): # super(ClientTest, self).setUp() # master = self.create_djedi_master() # client = Client(enforce_csrf_checks=True) # client.login(username=master.username, password='test') # self.client = client # # class DjediTest(TransactionTestCase): # # def setUp(self): # from cio.environment import env # from cio.backends import cache # from cio.pipeline import pipeline # from cio.plugins import plugins # # env.reset() # cache.clear() # pipeline.clear() # plugins.load() # # def tearDown(self): # shutil.rmtree(settings.MEDIA_ROOT, ignore_errors=True) # # @contextmanager # def settings(self, *args, **kwargs): # with super(DjediTest, self).settings(*args, **kwargs): # with cio_settings(): # configure() # yield # # class UserMixin(object): # # def create_djedi_master(self): # user = User.objects.create_superuser('master', 'master@djedi.io', 'test') # return user # # def create_djedi_apprentice(self): # user = User.objects.create_user('apprentice', email='apprentice@djedi.io', password='test') # group, _ = Group.objects.get_or_create(name='Djedi') # user.is_staff = True # user.groups.add(group) # user.save() # return user # # Path: djedi/utils/encoding.py # # Path: djedi/compat.py # def patterns(*urls): # def parse_bits(parser, bits, params, varargs, varkw, defaults, # takes_context, name): # def generic_tag_compiler(parser, token, params, varargs, varkw, defaults, # name, takes_context, node_class): # def __init__(self, *args, **kwargs): # def get_cache(name): # def getargspec(func): # class TemplateResponse(BaseTemplateResponse): which might include code, classes, or functions. Output only the next line.
assert isinstance(response.context_data['forms']['HTML'], BaseEditorForm)
Given the following code snippet before the placeholder: <|code_start|> del node['meta'] return node class PermissionTest(DjediTest, UserMixin): def setUp(self): super(PermissionTest, self).setUp() self.master = self.create_djedi_master() self.apprentice = self.create_djedi_apprentice() def test_permissions(self): client = Client() url = reverse('admin:djedi:api', args=['i18n://sv-se@page/title']) response = client.get(url) self.assertEqual(response.status_code, 403) logged_in = client.login(username=self.master.username, password='test') self.assertTrue(logged_in) response = client.get(url) self.assertEqual(response.status_code, 404) client.logout() logged_in = client.login(username=self.apprentice.username, password='test') self.assertTrue(logged_in) response = client.get(url) self.assertEqual(response.status_code, 404) <|code_end|> , predict the next line using imports from the current file: import os import simplejson as json import cio import cio.conf from django.core.files import File from django.test import Client from django.utils.http import urlquote from cio.backends import storage from cio.backends.exceptions import NodeDoesNotExist, PersistenceError from cio.plugins import plugins from cio.utils.uri import URI from djedi.plugins.form import BaseEditorForm from djedi.tests.base import ClientTest, DjediTest, UserMixin from djedi.utils.encoding import smart_unicode from ..compat import reverse from djedi.plugins.img import DataForm and context including class names, function names, and sometimes code from other files: # Path: djedi/plugins/form.py # class BaseEditorForm(forms.Form): # def __init__(self, *args, **kwargs): # super(BaseEditorForm, self).__init__(*args, **kwargs) # # for field in list(self.fields.keys()): # self.fields[field].widget.__class__ = get_custom_render_widget( # self.fields[field].widget.__class__ # ) # # Path: djedi/tests/base.py # class ClientTest(DjediTest, UserMixin, AssertionMixin): # # def setUp(self): # super(ClientTest, self).setUp() # master = self.create_djedi_master() # client = Client(enforce_csrf_checks=True) # client.login(username=master.username, password='test') # self.client = client # # class DjediTest(TransactionTestCase): # # def setUp(self): # from cio.environment import env # from cio.backends import cache # from cio.pipeline import pipeline # from cio.plugins import plugins # # env.reset() # cache.clear() # pipeline.clear() # plugins.load() # # def tearDown(self): # shutil.rmtree(settings.MEDIA_ROOT, ignore_errors=True) # # @contextmanager # def settings(self, *args, **kwargs): # with super(DjediTest, self).settings(*args, **kwargs): # with cio_settings(): # configure() # yield # # class UserMixin(object): # # def create_djedi_master(self): # user = User.objects.create_superuser('master', 'master@djedi.io', 'test') # return user # # def create_djedi_apprentice(self): # user = User.objects.create_user('apprentice', email='apprentice@djedi.io', password='test') # group, _ = Group.objects.get_or_create(name='Djedi') # user.is_staff = True # user.groups.add(group) # user.save() # return user # # Path: djedi/utils/encoding.py # # Path: djedi/compat.py # def patterns(*urls): # def parse_bits(parser, bits, params, varargs, varkw, defaults, # takes_context, name): # def generic_tag_compiler(parser, token, params, varargs, varkw, defaults, # name, takes_context, node_class): # def __init__(self, *args, **kwargs): # def get_cache(name): # def getargspec(func): # class TemplateResponse(BaseTemplateResponse): . Output only the next line.
class PrivateRestTest(ClientTest):
Using the snippet: <|code_start|> def json_node(response, simple=True): node = json.loads(response.content) if simple and 'meta' in node: del node['meta'] return node <|code_end|> , determine the next line of code. You have imports: import os import simplejson as json import cio import cio.conf from django.core.files import File from django.test import Client from django.utils.http import urlquote from cio.backends import storage from cio.backends.exceptions import NodeDoesNotExist, PersistenceError from cio.plugins import plugins from cio.utils.uri import URI from djedi.plugins.form import BaseEditorForm from djedi.tests.base import ClientTest, DjediTest, UserMixin from djedi.utils.encoding import smart_unicode from ..compat import reverse from djedi.plugins.img import DataForm and context (class names, function names, or code) available: # Path: djedi/plugins/form.py # class BaseEditorForm(forms.Form): # def __init__(self, *args, **kwargs): # super(BaseEditorForm, self).__init__(*args, **kwargs) # # for field in list(self.fields.keys()): # self.fields[field].widget.__class__ = get_custom_render_widget( # self.fields[field].widget.__class__ # ) # # Path: djedi/tests/base.py # class ClientTest(DjediTest, UserMixin, AssertionMixin): # # def setUp(self): # super(ClientTest, self).setUp() # master = self.create_djedi_master() # client = Client(enforce_csrf_checks=True) # client.login(username=master.username, password='test') # self.client = client # # class DjediTest(TransactionTestCase): # # def setUp(self): # from cio.environment import env # from cio.backends import cache # from cio.pipeline import pipeline # from cio.plugins import plugins # # env.reset() # cache.clear() # pipeline.clear() # plugins.load() # # def tearDown(self): # shutil.rmtree(settings.MEDIA_ROOT, ignore_errors=True) # # @contextmanager # def settings(self, *args, **kwargs): # with super(DjediTest, self).settings(*args, **kwargs): # with cio_settings(): # configure() # yield # # class UserMixin(object): # # def create_djedi_master(self): # user = User.objects.create_superuser('master', 'master@djedi.io', 'test') # return user # # def create_djedi_apprentice(self): # user = User.objects.create_user('apprentice', email='apprentice@djedi.io', password='test') # group, _ = Group.objects.get_or_create(name='Djedi') # user.is_staff = True # user.groups.add(group) # user.save() # return user # # Path: djedi/utils/encoding.py # # Path: djedi/compat.py # def patterns(*urls): # def parse_bits(parser, bits, params, varargs, varkw, defaults, # takes_context, name): # def generic_tag_compiler(parser, token, params, varargs, varkw, defaults, # name, takes_context, node_class): # def __init__(self, *args, **kwargs): # def get_cache(name): # def getargspec(func): # class TemplateResponse(BaseTemplateResponse): . Output only the next line.
class PermissionTest(DjediTest, UserMixin):
Predict the next line for this snippet: <|code_start|> def json_node(response, simple=True): node = json.loads(response.content) if simple and 'meta' in node: del node['meta'] return node <|code_end|> with the help of current file imports: import os import simplejson as json import cio import cio.conf from django.core.files import File from django.test import Client from django.utils.http import urlquote from cio.backends import storage from cio.backends.exceptions import NodeDoesNotExist, PersistenceError from cio.plugins import plugins from cio.utils.uri import URI from djedi.plugins.form import BaseEditorForm from djedi.tests.base import ClientTest, DjediTest, UserMixin from djedi.utils.encoding import smart_unicode from ..compat import reverse from djedi.plugins.img import DataForm and context from other files: # Path: djedi/plugins/form.py # class BaseEditorForm(forms.Form): # def __init__(self, *args, **kwargs): # super(BaseEditorForm, self).__init__(*args, **kwargs) # # for field in list(self.fields.keys()): # self.fields[field].widget.__class__ = get_custom_render_widget( # self.fields[field].widget.__class__ # ) # # Path: djedi/tests/base.py # class ClientTest(DjediTest, UserMixin, AssertionMixin): # # def setUp(self): # super(ClientTest, self).setUp() # master = self.create_djedi_master() # client = Client(enforce_csrf_checks=True) # client.login(username=master.username, password='test') # self.client = client # # class DjediTest(TransactionTestCase): # # def setUp(self): # from cio.environment import env # from cio.backends import cache # from cio.pipeline import pipeline # from cio.plugins import plugins # # env.reset() # cache.clear() # pipeline.clear() # plugins.load() # # def tearDown(self): # shutil.rmtree(settings.MEDIA_ROOT, ignore_errors=True) # # @contextmanager # def settings(self, *args, **kwargs): # with super(DjediTest, self).settings(*args, **kwargs): # with cio_settings(): # configure() # yield # # class UserMixin(object): # # def create_djedi_master(self): # user = User.objects.create_superuser('master', 'master@djedi.io', 'test') # return user # # def create_djedi_apprentice(self): # user = User.objects.create_user('apprentice', email='apprentice@djedi.io', password='test') # group, _ = Group.objects.get_or_create(name='Djedi') # user.is_staff = True # user.groups.add(group) # user.save() # return user # # Path: djedi/utils/encoding.py # # Path: djedi/compat.py # def patterns(*urls): # def parse_bits(parser, bits, params, varargs, varkw, defaults, # takes_context, name): # def generic_tag_compiler(parser, token, params, varargs, varkw, defaults, # name, takes_context, node_class): # def __init__(self, *args, **kwargs): # def get_cache(name): # def getargspec(func): # class TemplateResponse(BaseTemplateResponse): , which may contain function names, class names, or code. Output only the next line.
class PermissionTest(DjediTest, UserMixin):
Predict the next line after this snippet: <|code_start|> self.assertEqual(response.status_code, 200) node = json_node(response, simple=False) meta = node.pop('meta') content = u'# Djedi' if cio.PY26 else u'<h1>Djedi</h1>' self.assertDictEqual(node, {'uri': 'i18n://sv-se@page/title.md#draft', 'content': content}) self.assertEqual(meta['author'], u'master') self.assertEqual(meta['message'], u'lundberg') node = cio.get(uri, lazy=False) self.assertIsNone(node.content) cio.publish(uri) node = cio.get(uri, lazy=False) self.assertEqual(node.uri, 'i18n://sv-se@page/title.md#1') self.assertRenderedMarkdown(node.content, u'# Djedi') response = self.post('api', node.uri, {'data': u'# Djedi', 'meta[message]': u'Lundberg'}) node = json_node(response, simple=False) self.assertEqual(node['meta']['message'], u'Lundberg') with self.assertRaises(PersistenceError): storage.backend._create(URI(node['uri']), None) def test_delete(self): response = self.delete('api', 'i18n://sv-se@page/title') self.assertEqual(response.status_code, 404) node = cio.set('i18n://sv-se@page/title.md', u'# Djedi') response = self.delete('api', node.uri) self.assertEqual(response.status_code, 200) <|code_end|> using the current file's imports: import os import simplejson as json import cio import cio.conf from django.core.files import File from django.test import Client from django.utils.http import urlquote from cio.backends import storage from cio.backends.exceptions import NodeDoesNotExist, PersistenceError from cio.plugins import plugins from cio.utils.uri import URI from djedi.plugins.form import BaseEditorForm from djedi.tests.base import ClientTest, DjediTest, UserMixin from djedi.utils.encoding import smart_unicode from ..compat import reverse from djedi.plugins.img import DataForm and any relevant context from other files: # Path: djedi/plugins/form.py # class BaseEditorForm(forms.Form): # def __init__(self, *args, **kwargs): # super(BaseEditorForm, self).__init__(*args, **kwargs) # # for field in list(self.fields.keys()): # self.fields[field].widget.__class__ = get_custom_render_widget( # self.fields[field].widget.__class__ # ) # # Path: djedi/tests/base.py # class ClientTest(DjediTest, UserMixin, AssertionMixin): # # def setUp(self): # super(ClientTest, self).setUp() # master = self.create_djedi_master() # client = Client(enforce_csrf_checks=True) # client.login(username=master.username, password='test') # self.client = client # # class DjediTest(TransactionTestCase): # # def setUp(self): # from cio.environment import env # from cio.backends import cache # from cio.pipeline import pipeline # from cio.plugins import plugins # # env.reset() # cache.clear() # pipeline.clear() # plugins.load() # # def tearDown(self): # shutil.rmtree(settings.MEDIA_ROOT, ignore_errors=True) # # @contextmanager # def settings(self, *args, **kwargs): # with super(DjediTest, self).settings(*args, **kwargs): # with cio_settings(): # configure() # yield # # class UserMixin(object): # # def create_djedi_master(self): # user = User.objects.create_superuser('master', 'master@djedi.io', 'test') # return user # # def create_djedi_apprentice(self): # user = User.objects.create_user('apprentice', email='apprentice@djedi.io', password='test') # group, _ = Group.objects.get_or_create(name='Djedi') # user.is_staff = True # user.groups.add(group) # user.save() # return user # # Path: djedi/utils/encoding.py # # Path: djedi/compat.py # def patterns(*urls): # def parse_bits(parser, bits, params, varargs, varkw, defaults, # takes_context, name): # def generic_tag_compiler(parser, token, params, varargs, varkw, defaults, # name, takes_context, node_class): # def __init__(self, *args, **kwargs): # def get_cache(name): # def getargspec(func): # class TemplateResponse(BaseTemplateResponse): . Output only the next line.
self.assertEqual(smart_unicode(response.content), u'')
Next line prediction: <|code_start|> def json_node(response, simple=True): node = json.loads(response.content) if simple and 'meta' in node: del node['meta'] return node class PermissionTest(DjediTest, UserMixin): def setUp(self): super(PermissionTest, self).setUp() self.master = self.create_djedi_master() self.apprentice = self.create_djedi_apprentice() def test_permissions(self): client = Client() <|code_end|> . Use current file imports: (import os import simplejson as json import cio import cio.conf from django.core.files import File from django.test import Client from django.utils.http import urlquote from cio.backends import storage from cio.backends.exceptions import NodeDoesNotExist, PersistenceError from cio.plugins import plugins from cio.utils.uri import URI from djedi.plugins.form import BaseEditorForm from djedi.tests.base import ClientTest, DjediTest, UserMixin from djedi.utils.encoding import smart_unicode from ..compat import reverse from djedi.plugins.img import DataForm) and context including class names, function names, or small code snippets from other files: # Path: djedi/plugins/form.py # class BaseEditorForm(forms.Form): # def __init__(self, *args, **kwargs): # super(BaseEditorForm, self).__init__(*args, **kwargs) # # for field in list(self.fields.keys()): # self.fields[field].widget.__class__ = get_custom_render_widget( # self.fields[field].widget.__class__ # ) # # Path: djedi/tests/base.py # class ClientTest(DjediTest, UserMixin, AssertionMixin): # # def setUp(self): # super(ClientTest, self).setUp() # master = self.create_djedi_master() # client = Client(enforce_csrf_checks=True) # client.login(username=master.username, password='test') # self.client = client # # class DjediTest(TransactionTestCase): # # def setUp(self): # from cio.environment import env # from cio.backends import cache # from cio.pipeline import pipeline # from cio.plugins import plugins # # env.reset() # cache.clear() # pipeline.clear() # plugins.load() # # def tearDown(self): # shutil.rmtree(settings.MEDIA_ROOT, ignore_errors=True) # # @contextmanager # def settings(self, *args, **kwargs): # with super(DjediTest, self).settings(*args, **kwargs): # with cio_settings(): # configure() # yield # # class UserMixin(object): # # def create_djedi_master(self): # user = User.objects.create_superuser('master', 'master@djedi.io', 'test') # return user # # def create_djedi_apprentice(self): # user = User.objects.create_user('apprentice', email='apprentice@djedi.io', password='test') # group, _ = Group.objects.get_or_create(name='Djedi') # user.is_staff = True # user.groups.add(group) # user.save() # return user # # Path: djedi/utils/encoding.py # # Path: djedi/compat.py # def patterns(*urls): # def parse_bits(parser, bits, params, varargs, varkw, defaults, # takes_context, name): # def generic_tag_compiler(parser, token, params, varargs, varkw, defaults, # name, takes_context, node_class): # def __init__(self, *args, **kwargs): # def get_cache(name): # def getargspec(func): # class TemplateResponse(BaseTemplateResponse): . Output only the next line.
url = reverse('admin:djedi:api', args=['i18n://sv-se@page/title'])
Continue the code snippet: <|code_start|> app_name = 'djedi' if django.VERSION < (2, 0): urlpatterns = patterns( <|code_end|> . Use current file imports: import django from .compat import include, patterns, url from django.urls import path and context (classes, functions, or code) from other files: # Path: djedi/compat.py # def patterns(*urls): # def parse_bits(parser, bits, params, varargs, varkw, defaults, # takes_context, name): # def generic_tag_compiler(parser, token, params, varargs, varkw, defaults, # name, takes_context, node_class): # def __init__(self, *args, **kwargs): # def get_cache(name): # def getargspec(func): # class TemplateResponse(BaseTemplateResponse): . Output only the next line.
url(r'^', include('djedi.admin.urls', namespace='djedi')),
Based on the snippet: <|code_start|> app_name = 'djedi' if django.VERSION < (2, 0): urlpatterns = patterns( <|code_end|> , predict the immediate next line with the help of imports: import django from .compat import include, patterns, url from django.urls import path and context (classes, functions, sometimes code) from other files: # Path: djedi/compat.py # def patterns(*urls): # def parse_bits(parser, bits, params, varargs, varkw, defaults, # takes_context, name): # def generic_tag_compiler(parser, token, params, varargs, varkw, defaults, # name, takes_context, node_class): # def __init__(self, *args, **kwargs): # def get_cache(name): # def getargspec(func): # class TemplateResponse(BaseTemplateResponse): . Output only the next line.
url(r'^', include('djedi.admin.urls', namespace='djedi')),
Here is a snippet: <|code_start|> class DataForm(BaseEditorForm): data__id = forms.CharField( label="ID", max_length=255, required=False, widget=forms.TextInput(attrs={"class": "form-control"}), ) data__alt = forms.CharField( label="Alt text", max_length=255, required=False, widget=forms.TextInput(attrs={"class": "form-control"}), ) data__class = forms.CharField( label="Class", max_length=255, required=False, widget=forms.TextInput(attrs={"class": "form-control"}), ) <|code_end|> . Write the next line using the current file imports: import json import six from django.utils.html import escape from django.core.files.uploadedfile import InMemoryUploadedFile from django import forms from hashlib import sha1 from os import path from .form import FormsBasePlugin, BaseEditorForm from PIL import Image from django.core.files.storage import default_storage as file_storage and context from other files: # Path: djedi/plugins/form.py # class FormsBasePlugin(DjediPlugin): # ext = None # # @property # def forms(self): # return {} # # def get_editor_context(self, **context): # context.update( # {"forms": { # tab: form() # for tab, form in self.forms.items() # }} # ) # # return context # # def save(self, data, dumps=True): # data = self.collect_forms_data(data) # return json.dumps(data) if dumps else data # # def collect_forms_data(self, data): # return { # deprefix(field): data.get(deprefix(field)) # for tab, form in self.forms.items() # for field in form.base_fields.keys() # } # # class BaseEditorForm(forms.Form): # def __init__(self, *args, **kwargs): # super(BaseEditorForm, self).__init__(*args, **kwargs) # # for field in list(self.fields.keys()): # self.fields[field].widget.__class__ = get_custom_render_widget( # self.fields[field].widget.__class__ # ) , which may include functions, classes, or code. Output only the next line.
class ImagePluginBase(FormsBasePlugin):
Given the following code snippet before the placeholder: <|code_start|> def test_parse_spanish_date_datetime(self): start_date = datetime.datetime(2016, 12, 3, 13, 50) # Monday result = parse_spanish_date('03-Dic-16 13:50') self.assertTrue(result, start_date) class TestSpanishDate(TestCase): def test_to_string(self): start_date = datetime.date(2016, 12, 3) str_date = spanish_date_util.to_string(start_date) self.assertEqual('03-Dic-16', str_date) def test_to_string_datetime(self): start_date = datetime.datetime(2016, 12, 3, 16, 15) str_date = spanish_date_util.to_string(start_date) self.assertEqual('03-Dic-16 16:15', str_date) def test_parse(self): start_date = datetime.datetime(2016, 12, 3, 13, 50) result = spanish_date_util.parse('03-Dic-16 13:50') self.assertTrue(result, start_date) def test_parse_date(self): start_date = datetime.date(2016, 12, 3) o_date = spanish_date_util.parse('03-Dic-16') self.assertEqual(o_date, start_date) class TemporyFolderTest(TestCase): def test_temporary_folder_write_list(self): <|code_end|> , predict the next line using imports from the current file: import datetime import logging import os import pytz from unittest import mock from django.test import TestCase, SimpleTestCase from django.test import override_settings from django_test_tools.file_utils import TemporaryFolder, hash_file from django_test_tools.utils import Timer, add_date_to_filename, daterange, parse_spanish_date, spanish_date_util, \ create_output_filename_with_date, dict_compare, convert_to_snake_case, datetime_to_local_time and context including class names, function names, and sometimes code from other files: # Path: django_test_tools/file_utils.py # class TemporaryFolder: # def __init__(self, base_name, delete_on_exit=True): # self.new_path = create_dated(base_name) # self.delete_on_exit = delete_on_exit # # def __enter__(self): # os.mkdir(self.new_path) # self.saved_path = os.getcwd() # os.chdir(self.new_path) # # return self # # def __exit__(self, exc_type, exc_val, exc_tb): # os.chdir(self.saved_path) # if self.delete_on_exit: # shutil.rmtree(self.new_path) # # def write(self, filename, content): # with open(filename, 'w', encoding='utf-8') as file: # if isinstance(content, str): # file.writelines(content) # elif isinstance(content, list): # for line in content: # file.write(line) # file.write('\n') # else: # file.writelines(str(content)) # return os.path.join(self.new_path, filename) # # def hash_file(filename, algorithm='sha1', block_size=BLOCKSIZE): # """ # Creates a unique hash for a file. # # :param filename: String with the full path to the file # :param algorithm: String Algorithm to create the hash # :param block_size: int for the size of the block while reading the file # :return: string the hash for the file # """ # try: # hasher = getattr(hashlib, algorithm)() # except AttributeError: # raise ValueError('{} is not a valid hashing algorithm'.format(algorithm)) # # with open(filename, 'rb') as afile: # buf = afile.read(block_size) # while len(buf) > 0: # hasher.update(buf) # buf = afile.read(block_size) # return hasher.hexdigest() # # Path: django_test_tools/utils.py # def versiontuple(v): # def dict_compare(d1, d2): # def convert_to_snake_case(camel_case): # def create_output_filename_with_date(filename): # def add_date_to_filename(filename, **kwargs): # def deprecated(func): # def new_func(*args, **kwargs): # def daterange(start_date, end_date): # def weekdays(start_date, end_date): # def __init__(self, newPath): # def __enter__(self): # def __exit__(self, etype, value, traceback): # def force_date_to_datetime(unconverted_date, tzinfo=pytz.UTC): # def __init__(self): # def start(self): # def stop(self): # def reset(self): # def get_elapsed_time(self): # def get_elapsed_time_str(self): # def running(self): # def __enter__(self): # def __exit__(self, *args): # def load_json_file(filename): # def datetime_to_local_time(date_time): # def __init__(self): # def _get_date_parts(self, match, input_lang='es'): # def parse(self, str_date): # def to_string(self, m_date): # def parse_spanish_date(str_date): # class cd: # class Timer: # class SpanishDate(object): . Output only the next line.
with TemporaryFolder('my_temp_list', delete_on_exit=True) as folder:
Next line prediction: <|code_start|> self.assertTrue(result, start_date) class TestSpanishDate(TestCase): def test_to_string(self): start_date = datetime.date(2016, 12, 3) str_date = spanish_date_util.to_string(start_date) self.assertEqual('03-Dic-16', str_date) def test_to_string_datetime(self): start_date = datetime.datetime(2016, 12, 3, 16, 15) str_date = spanish_date_util.to_string(start_date) self.assertEqual('03-Dic-16 16:15', str_date) def test_parse(self): start_date = datetime.datetime(2016, 12, 3, 13, 50) result = spanish_date_util.parse('03-Dic-16 13:50') self.assertTrue(result, start_date) def test_parse_date(self): start_date = datetime.date(2016, 12, 3) o_date = spanish_date_util.parse('03-Dic-16') self.assertEqual(o_date, start_date) class TemporyFolderTest(TestCase): def test_temporary_folder_write_list(self): with TemporaryFolder('my_temp_list', delete_on_exit=True) as folder: self.assertTrue(os.path.exists(folder.new_path)) filename = folder.write('m.txt', ['kilo', 'boma']) <|code_end|> . Use current file imports: (import datetime import logging import os import pytz from unittest import mock from django.test import TestCase, SimpleTestCase from django.test import override_settings from django_test_tools.file_utils import TemporaryFolder, hash_file from django_test_tools.utils import Timer, add_date_to_filename, daterange, parse_spanish_date, spanish_date_util, \ create_output_filename_with_date, dict_compare, convert_to_snake_case, datetime_to_local_time) and context including class names, function names, or small code snippets from other files: # Path: django_test_tools/file_utils.py # class TemporaryFolder: # def __init__(self, base_name, delete_on_exit=True): # self.new_path = create_dated(base_name) # self.delete_on_exit = delete_on_exit # # def __enter__(self): # os.mkdir(self.new_path) # self.saved_path = os.getcwd() # os.chdir(self.new_path) # # return self # # def __exit__(self, exc_type, exc_val, exc_tb): # os.chdir(self.saved_path) # if self.delete_on_exit: # shutil.rmtree(self.new_path) # # def write(self, filename, content): # with open(filename, 'w', encoding='utf-8') as file: # if isinstance(content, str): # file.writelines(content) # elif isinstance(content, list): # for line in content: # file.write(line) # file.write('\n') # else: # file.writelines(str(content)) # return os.path.join(self.new_path, filename) # # def hash_file(filename, algorithm='sha1', block_size=BLOCKSIZE): # """ # Creates a unique hash for a file. # # :param filename: String with the full path to the file # :param algorithm: String Algorithm to create the hash # :param block_size: int for the size of the block while reading the file # :return: string the hash for the file # """ # try: # hasher = getattr(hashlib, algorithm)() # except AttributeError: # raise ValueError('{} is not a valid hashing algorithm'.format(algorithm)) # # with open(filename, 'rb') as afile: # buf = afile.read(block_size) # while len(buf) > 0: # hasher.update(buf) # buf = afile.read(block_size) # return hasher.hexdigest() # # Path: django_test_tools/utils.py # def versiontuple(v): # def dict_compare(d1, d2): # def convert_to_snake_case(camel_case): # def create_output_filename_with_date(filename): # def add_date_to_filename(filename, **kwargs): # def deprecated(func): # def new_func(*args, **kwargs): # def daterange(start_date, end_date): # def weekdays(start_date, end_date): # def __init__(self, newPath): # def __enter__(self): # def __exit__(self, etype, value, traceback): # def force_date_to_datetime(unconverted_date, tzinfo=pytz.UTC): # def __init__(self): # def start(self): # def stop(self): # def reset(self): # def get_elapsed_time(self): # def get_elapsed_time_str(self): # def running(self): # def __enter__(self): # def __exit__(self, *args): # def load_json_file(filename): # def datetime_to_local_time(date_time): # def __init__(self): # def _get_date_parts(self, match, input_lang='es'): # def parse(self, str_date): # def to_string(self, m_date): # def parse_spanish_date(str_date): # class cd: # class Timer: # class SpanishDate(object): . Output only the next line.
digest = hash_file(filename)
Predict the next line for this snippet: <|code_start|> self.assertEqual(2, len(same)) def test_dict_compare_removed(self): dict1 = {'name': 'Luis', 'colors': ['red', 'blue', 'black']} dict2 = {'name': 'Luis', 'colors': ['red', 'blue', 'black'], 'type': 'human'} added, removed, modified, same = dict_compare(dict1, dict2) self.assertEqual(0, len(added)) self.assertEqual({'type'}, removed) self.assertEqual(0, len(modified)) self.assertEqual({'colors', 'name'}, same) added, removed, modified, same = dict_compare(dict2, dict1) self.assertEqual({'type'}, added) self.assertEqual(0, len(removed)) self.assertEqual(0, len(modified)) self.assertEqual({'colors', 'name'}, same) dict1 = {'name': 'Luis', 'colors': ['red', 'blue']} added, removed, modified, same = dict_compare(dict2, dict1) self.assertEqual({'type'}, added) self.assertEqual(0, len(removed)) self.assertEqual({'colors': (['red', 'blue', 'black'], ['red', 'blue'])}, modified) self.assertEqual({'name'}, same) class TestTimer(TestCase): def test_get_elapsed_time_str(self): clock = MockPerfCounter() with mock.patch('time.perf_counter', clock.perf_counter): # clock.increment(3600.0) <|code_end|> with the help of current file imports: import datetime import logging import os import pytz from unittest import mock from django.test import TestCase, SimpleTestCase from django.test import override_settings from django_test_tools.file_utils import TemporaryFolder, hash_file from django_test_tools.utils import Timer, add_date_to_filename, daterange, parse_spanish_date, spanish_date_util, \ create_output_filename_with_date, dict_compare, convert_to_snake_case, datetime_to_local_time and context from other files: # Path: django_test_tools/file_utils.py # class TemporaryFolder: # def __init__(self, base_name, delete_on_exit=True): # self.new_path = create_dated(base_name) # self.delete_on_exit = delete_on_exit # # def __enter__(self): # os.mkdir(self.new_path) # self.saved_path = os.getcwd() # os.chdir(self.new_path) # # return self # # def __exit__(self, exc_type, exc_val, exc_tb): # os.chdir(self.saved_path) # if self.delete_on_exit: # shutil.rmtree(self.new_path) # # def write(self, filename, content): # with open(filename, 'w', encoding='utf-8') as file: # if isinstance(content, str): # file.writelines(content) # elif isinstance(content, list): # for line in content: # file.write(line) # file.write('\n') # else: # file.writelines(str(content)) # return os.path.join(self.new_path, filename) # # def hash_file(filename, algorithm='sha1', block_size=BLOCKSIZE): # """ # Creates a unique hash for a file. # # :param filename: String with the full path to the file # :param algorithm: String Algorithm to create the hash # :param block_size: int for the size of the block while reading the file # :return: string the hash for the file # """ # try: # hasher = getattr(hashlib, algorithm)() # except AttributeError: # raise ValueError('{} is not a valid hashing algorithm'.format(algorithm)) # # with open(filename, 'rb') as afile: # buf = afile.read(block_size) # while len(buf) > 0: # hasher.update(buf) # buf = afile.read(block_size) # return hasher.hexdigest() # # Path: django_test_tools/utils.py # def versiontuple(v): # def dict_compare(d1, d2): # def convert_to_snake_case(camel_case): # def create_output_filename_with_date(filename): # def add_date_to_filename(filename, **kwargs): # def deprecated(func): # def new_func(*args, **kwargs): # def daterange(start_date, end_date): # def weekdays(start_date, end_date): # def __init__(self, newPath): # def __enter__(self): # def __exit__(self, etype, value, traceback): # def force_date_to_datetime(unconverted_date, tzinfo=pytz.UTC): # def __init__(self): # def start(self): # def stop(self): # def reset(self): # def get_elapsed_time(self): # def get_elapsed_time_str(self): # def running(self): # def __enter__(self): # def __exit__(self, *args): # def load_json_file(filename): # def datetime_to_local_time(date_time): # def __init__(self): # def _get_date_parts(self, match, input_lang='es'): # def parse(self, str_date): # def to_string(self, m_date): # def parse_spanish_date(str_date): # class cd: # class Timer: # class SpanishDate(object): , which may contain function names, class names, or code. Output only the next line.
stopwatch = Timer()
Here is a snippet: <|code_start|> class TestTimer(TestCase): def test_get_elapsed_time_str(self): clock = MockPerfCounter() with mock.patch('time.perf_counter', clock.perf_counter): # clock.increment(3600.0) stopwatch = Timer() stopwatch.start() clock.increment(120.5) stopwatch.stop() self.assertEqual('0 h 2 m 0.50 s', stopwatch.get_elapsed_time_str()) def test_get_elapsed_time_str_with(self): clock = MockPerfCounter() with mock.patch('time.perf_counter', clock.perf_counter): # clock.increment(3600.0) with Timer() as stopwatch: clock.increment(360.25) self.assertEqual('0 h 6 m 0.25 s', stopwatch.get_elapsed_time_str()) class TestAddDateToFilename(TestCase): def setUp(self): self.mock_datetime = pytz.timezone('America/Panama').localize( datetime.datetime.strptime('2016-07-07 16:40:39', '%Y-%m-%d %H:%M:%S')) @mock.patch('django.utils.timezone.now') def test_add_date_to_filename_suffix_path(self, mock_now): mock_now.return_value = self.mock_datetime filename = r'c:\kilo\poli\namos.txt' <|code_end|> . Write the next line using the current file imports: import datetime import logging import os import pytz from unittest import mock from django.test import TestCase, SimpleTestCase from django.test import override_settings from django_test_tools.file_utils import TemporaryFolder, hash_file from django_test_tools.utils import Timer, add_date_to_filename, daterange, parse_spanish_date, spanish_date_util, \ create_output_filename_with_date, dict_compare, convert_to_snake_case, datetime_to_local_time and context from other files: # Path: django_test_tools/file_utils.py # class TemporaryFolder: # def __init__(self, base_name, delete_on_exit=True): # self.new_path = create_dated(base_name) # self.delete_on_exit = delete_on_exit # # def __enter__(self): # os.mkdir(self.new_path) # self.saved_path = os.getcwd() # os.chdir(self.new_path) # # return self # # def __exit__(self, exc_type, exc_val, exc_tb): # os.chdir(self.saved_path) # if self.delete_on_exit: # shutil.rmtree(self.new_path) # # def write(self, filename, content): # with open(filename, 'w', encoding='utf-8') as file: # if isinstance(content, str): # file.writelines(content) # elif isinstance(content, list): # for line in content: # file.write(line) # file.write('\n') # else: # file.writelines(str(content)) # return os.path.join(self.new_path, filename) # # def hash_file(filename, algorithm='sha1', block_size=BLOCKSIZE): # """ # Creates a unique hash for a file. # # :param filename: String with the full path to the file # :param algorithm: String Algorithm to create the hash # :param block_size: int for the size of the block while reading the file # :return: string the hash for the file # """ # try: # hasher = getattr(hashlib, algorithm)() # except AttributeError: # raise ValueError('{} is not a valid hashing algorithm'.format(algorithm)) # # with open(filename, 'rb') as afile: # buf = afile.read(block_size) # while len(buf) > 0: # hasher.update(buf) # buf = afile.read(block_size) # return hasher.hexdigest() # # Path: django_test_tools/utils.py # def versiontuple(v): # def dict_compare(d1, d2): # def convert_to_snake_case(camel_case): # def create_output_filename_with_date(filename): # def add_date_to_filename(filename, **kwargs): # def deprecated(func): # def new_func(*args, **kwargs): # def daterange(start_date, end_date): # def weekdays(start_date, end_date): # def __init__(self, newPath): # def __enter__(self): # def __exit__(self, etype, value, traceback): # def force_date_to_datetime(unconverted_date, tzinfo=pytz.UTC): # def __init__(self): # def start(self): # def stop(self): # def reset(self): # def get_elapsed_time(self): # def get_elapsed_time_str(self): # def running(self): # def __enter__(self): # def __exit__(self, *args): # def load_json_file(filename): # def datetime_to_local_time(date_time): # def __init__(self): # def _get_date_parts(self, match, input_lang='es'): # def parse(self, str_date): # def to_string(self, m_date): # def parse_spanish_date(str_date): # class cd: # class Timer: # class SpanishDate(object): , which may include functions, classes, or code. Output only the next line.
new_filename = add_date_to_filename(filename)
Here is a snippet: <|code_start|> mock_now.return_value = self.mock_datetime filename = r'c:\kilo\poli\namos.txt' new_filename = add_date_to_filename(filename, date_position='prefix') self.assertEquals(r'c:\kilo\poli\20160707_1640_namos.txt', new_filename) filename = r'/my/linux/path/namos.txt' new_filename = add_date_to_filename(filename, date_position='prefix') self.assertEquals(r'/my/linux/path/20160707_1640_namos.txt', new_filename) @mock.patch('django.utils.timezone.now') def test_add_date_to_filename_suffix_filename(self, mock_now): mock_now.return_value = self.mock_datetime filename = r'namos.txt' new_filename = add_date_to_filename(filename) self.assertEqual('namos_20160707_1640.txt', new_filename) @override_settings(TEST_OUTPUT_PATH=None) def test_create_output_filename_with_date_error(self): try: create_output_filename_with_date('kilo.txt') self.fail('Should have thrown value error') except ValueError as e: msg = 'You need a the variable TEST_OUTPUT_PATH in settings.' \ ' It should point to a folderfor temporary data to be written and reviewed.' self.assertEqual(msg, str(e)) def test_daterange(self): start_date = datetime.date(2015, 9, 1) end_date = datetime.date(2015, 9, 30) work_days = 0 <|code_end|> . Write the next line using the current file imports: import datetime import logging import os import pytz from unittest import mock from django.test import TestCase, SimpleTestCase from django.test import override_settings from django_test_tools.file_utils import TemporaryFolder, hash_file from django_test_tools.utils import Timer, add_date_to_filename, daterange, parse_spanish_date, spanish_date_util, \ create_output_filename_with_date, dict_compare, convert_to_snake_case, datetime_to_local_time and context from other files: # Path: django_test_tools/file_utils.py # class TemporaryFolder: # def __init__(self, base_name, delete_on_exit=True): # self.new_path = create_dated(base_name) # self.delete_on_exit = delete_on_exit # # def __enter__(self): # os.mkdir(self.new_path) # self.saved_path = os.getcwd() # os.chdir(self.new_path) # # return self # # def __exit__(self, exc_type, exc_val, exc_tb): # os.chdir(self.saved_path) # if self.delete_on_exit: # shutil.rmtree(self.new_path) # # def write(self, filename, content): # with open(filename, 'w', encoding='utf-8') as file: # if isinstance(content, str): # file.writelines(content) # elif isinstance(content, list): # for line in content: # file.write(line) # file.write('\n') # else: # file.writelines(str(content)) # return os.path.join(self.new_path, filename) # # def hash_file(filename, algorithm='sha1', block_size=BLOCKSIZE): # """ # Creates a unique hash for a file. # # :param filename: String with the full path to the file # :param algorithm: String Algorithm to create the hash # :param block_size: int for the size of the block while reading the file # :return: string the hash for the file # """ # try: # hasher = getattr(hashlib, algorithm)() # except AttributeError: # raise ValueError('{} is not a valid hashing algorithm'.format(algorithm)) # # with open(filename, 'rb') as afile: # buf = afile.read(block_size) # while len(buf) > 0: # hasher.update(buf) # buf = afile.read(block_size) # return hasher.hexdigest() # # Path: django_test_tools/utils.py # def versiontuple(v): # def dict_compare(d1, d2): # def convert_to_snake_case(camel_case): # def create_output_filename_with_date(filename): # def add_date_to_filename(filename, **kwargs): # def deprecated(func): # def new_func(*args, **kwargs): # def daterange(start_date, end_date): # def weekdays(start_date, end_date): # def __init__(self, newPath): # def __enter__(self): # def __exit__(self, etype, value, traceback): # def force_date_to_datetime(unconverted_date, tzinfo=pytz.UTC): # def __init__(self): # def start(self): # def stop(self): # def reset(self): # def get_elapsed_time(self): # def get_elapsed_time_str(self): # def running(self): # def __enter__(self): # def __exit__(self, *args): # def load_json_file(filename): # def datetime_to_local_time(date_time): # def __init__(self): # def _get_date_parts(self, match, input_lang='es'): # def parse(self, str_date): # def to_string(self, m_date): # def parse_spanish_date(str_date): # class cd: # class Timer: # class SpanishDate(object): , which may include functions, classes, or code. Output only the next line.
for dt in daterange(start_date, end_date):
Continue the code snippet: <|code_start|> end_date = datetime.date(2015, 9, 30) work_days = 0 for dt in daterange(start_date, end_date): work_days += 1 # logger.debug('Date: %s' % dt.strftime('%m-%d %a')) # self.assertFalse(dt.weekday() not in set([5, 6])) self.assertEqual(22, work_days) def test_daterange_week(self): start_date = datetime.date(2016, 10, 3) # Monday end_date = datetime.date(2016, 10, 7) # Friday work_days = 0 for dt in daterange(start_date, end_date): work_days += 1 self.assertEqual(5, work_days) def test_daterange_week_2(self): start_date = datetime.date(2016, 10, 3) # Monday end_date = datetime.date(2016, 10, 7) # Friday days = list(daterange(start_date, end_date)) self.assertEqual(5, len(days)) def test_daterange_one_day(self): start_date = datetime.date(2016, 10, 3) # Monday end_date = start_date days = list(daterange(start_date, end_date)) self.assertEqual(1, len(days)) def test_parse_spanish_date(self): start_date = datetime.date(2016, 12, 3) # Monday <|code_end|> . Use current file imports: import datetime import logging import os import pytz from unittest import mock from django.test import TestCase, SimpleTestCase from django.test import override_settings from django_test_tools.file_utils import TemporaryFolder, hash_file from django_test_tools.utils import Timer, add_date_to_filename, daterange, parse_spanish_date, spanish_date_util, \ create_output_filename_with_date, dict_compare, convert_to_snake_case, datetime_to_local_time and context (classes, functions, or code) from other files: # Path: django_test_tools/file_utils.py # class TemporaryFolder: # def __init__(self, base_name, delete_on_exit=True): # self.new_path = create_dated(base_name) # self.delete_on_exit = delete_on_exit # # def __enter__(self): # os.mkdir(self.new_path) # self.saved_path = os.getcwd() # os.chdir(self.new_path) # # return self # # def __exit__(self, exc_type, exc_val, exc_tb): # os.chdir(self.saved_path) # if self.delete_on_exit: # shutil.rmtree(self.new_path) # # def write(self, filename, content): # with open(filename, 'w', encoding='utf-8') as file: # if isinstance(content, str): # file.writelines(content) # elif isinstance(content, list): # for line in content: # file.write(line) # file.write('\n') # else: # file.writelines(str(content)) # return os.path.join(self.new_path, filename) # # def hash_file(filename, algorithm='sha1', block_size=BLOCKSIZE): # """ # Creates a unique hash for a file. # # :param filename: String with the full path to the file # :param algorithm: String Algorithm to create the hash # :param block_size: int for the size of the block while reading the file # :return: string the hash for the file # """ # try: # hasher = getattr(hashlib, algorithm)() # except AttributeError: # raise ValueError('{} is not a valid hashing algorithm'.format(algorithm)) # # with open(filename, 'rb') as afile: # buf = afile.read(block_size) # while len(buf) > 0: # hasher.update(buf) # buf = afile.read(block_size) # return hasher.hexdigest() # # Path: django_test_tools/utils.py # def versiontuple(v): # def dict_compare(d1, d2): # def convert_to_snake_case(camel_case): # def create_output_filename_with_date(filename): # def add_date_to_filename(filename, **kwargs): # def deprecated(func): # def new_func(*args, **kwargs): # def daterange(start_date, end_date): # def weekdays(start_date, end_date): # def __init__(self, newPath): # def __enter__(self): # def __exit__(self, etype, value, traceback): # def force_date_to_datetime(unconverted_date, tzinfo=pytz.UTC): # def __init__(self): # def start(self): # def stop(self): # def reset(self): # def get_elapsed_time(self): # def get_elapsed_time_str(self): # def running(self): # def __enter__(self): # def __exit__(self, *args): # def load_json_file(filename): # def datetime_to_local_time(date_time): # def __init__(self): # def _get_date_parts(self, match, input_lang='es'): # def parse(self, str_date): # def to_string(self, m_date): # def parse_spanish_date(str_date): # class cd: # class Timer: # class SpanishDate(object): . Output only the next line.
result = parse_spanish_date('03-Dic-16')
Predict the next line after this snippet: <|code_start|> for dt in daterange(start_date, end_date): work_days += 1 self.assertEqual(5, work_days) def test_daterange_week_2(self): start_date = datetime.date(2016, 10, 3) # Monday end_date = datetime.date(2016, 10, 7) # Friday days = list(daterange(start_date, end_date)) self.assertEqual(5, len(days)) def test_daterange_one_day(self): start_date = datetime.date(2016, 10, 3) # Monday end_date = start_date days = list(daterange(start_date, end_date)) self.assertEqual(1, len(days)) def test_parse_spanish_date(self): start_date = datetime.date(2016, 12, 3) # Monday result = parse_spanish_date('03-Dic-16') self.assertTrue(result, start_date) def test_parse_spanish_date_datetime(self): start_date = datetime.datetime(2016, 12, 3, 13, 50) # Monday result = parse_spanish_date('03-Dic-16 13:50') self.assertTrue(result, start_date) class TestSpanishDate(TestCase): def test_to_string(self): start_date = datetime.date(2016, 12, 3) <|code_end|> using the current file's imports: import datetime import logging import os import pytz from unittest import mock from django.test import TestCase, SimpleTestCase from django.test import override_settings from django_test_tools.file_utils import TemporaryFolder, hash_file from django_test_tools.utils import Timer, add_date_to_filename, daterange, parse_spanish_date, spanish_date_util, \ create_output_filename_with_date, dict_compare, convert_to_snake_case, datetime_to_local_time and any relevant context from other files: # Path: django_test_tools/file_utils.py # class TemporaryFolder: # def __init__(self, base_name, delete_on_exit=True): # self.new_path = create_dated(base_name) # self.delete_on_exit = delete_on_exit # # def __enter__(self): # os.mkdir(self.new_path) # self.saved_path = os.getcwd() # os.chdir(self.new_path) # # return self # # def __exit__(self, exc_type, exc_val, exc_tb): # os.chdir(self.saved_path) # if self.delete_on_exit: # shutil.rmtree(self.new_path) # # def write(self, filename, content): # with open(filename, 'w', encoding='utf-8') as file: # if isinstance(content, str): # file.writelines(content) # elif isinstance(content, list): # for line in content: # file.write(line) # file.write('\n') # else: # file.writelines(str(content)) # return os.path.join(self.new_path, filename) # # def hash_file(filename, algorithm='sha1', block_size=BLOCKSIZE): # """ # Creates a unique hash for a file. # # :param filename: String with the full path to the file # :param algorithm: String Algorithm to create the hash # :param block_size: int for the size of the block while reading the file # :return: string the hash for the file # """ # try: # hasher = getattr(hashlib, algorithm)() # except AttributeError: # raise ValueError('{} is not a valid hashing algorithm'.format(algorithm)) # # with open(filename, 'rb') as afile: # buf = afile.read(block_size) # while len(buf) > 0: # hasher.update(buf) # buf = afile.read(block_size) # return hasher.hexdigest() # # Path: django_test_tools/utils.py # def versiontuple(v): # def dict_compare(d1, d2): # def convert_to_snake_case(camel_case): # def create_output_filename_with_date(filename): # def add_date_to_filename(filename, **kwargs): # def deprecated(func): # def new_func(*args, **kwargs): # def daterange(start_date, end_date): # def weekdays(start_date, end_date): # def __init__(self, newPath): # def __enter__(self): # def __exit__(self, etype, value, traceback): # def force_date_to_datetime(unconverted_date, tzinfo=pytz.UTC): # def __init__(self): # def start(self): # def stop(self): # def reset(self): # def get_elapsed_time(self): # def get_elapsed_time_str(self): # def running(self): # def __enter__(self): # def __exit__(self, *args): # def load_json_file(filename): # def datetime_to_local_time(date_time): # def __init__(self): # def _get_date_parts(self, match, input_lang='es'): # def parse(self, str_date): # def to_string(self, m_date): # def parse_spanish_date(str_date): # class cd: # class Timer: # class SpanishDate(object): . Output only the next line.
str_date = spanish_date_util.to_string(start_date)
Continue the code snippet: <|code_start|> filename = r'c:\kilo\poli\namos.txt' new_filename = add_date_to_filename(filename, date_position='prefix') self.assertEquals(r'c:\kilo\poli\20160707_164039_namos.txt', new_filename) filename = r'/my/linux/path/namos.nemo.txt' new_filename = add_date_to_filename(filename) self.assertEquals(r'/my/linux/path/namos.nemo_20160707_164039.txt', new_filename) @mock.patch('django.utils.timezone.now') def test_add_date_to_filename_preffix_path(self, mock_now): mock_now.return_value = self.mock_datetime filename = r'c:\kilo\poli\namos.txt' new_filename = add_date_to_filename(filename, date_position='prefix') self.assertEquals(r'c:\kilo\poli\20160707_1640_namos.txt', new_filename) filename = r'/my/linux/path/namos.txt' new_filename = add_date_to_filename(filename, date_position='prefix') self.assertEquals(r'/my/linux/path/20160707_1640_namos.txt', new_filename) @mock.patch('django.utils.timezone.now') def test_add_date_to_filename_suffix_filename(self, mock_now): mock_now.return_value = self.mock_datetime filename = r'namos.txt' new_filename = add_date_to_filename(filename) self.assertEqual('namos_20160707_1640.txt', new_filename) @override_settings(TEST_OUTPUT_PATH=None) def test_create_output_filename_with_date_error(self): try: <|code_end|> . Use current file imports: import datetime import logging import os import pytz from unittest import mock from django.test import TestCase, SimpleTestCase from django.test import override_settings from django_test_tools.file_utils import TemporaryFolder, hash_file from django_test_tools.utils import Timer, add_date_to_filename, daterange, parse_spanish_date, spanish_date_util, \ create_output_filename_with_date, dict_compare, convert_to_snake_case, datetime_to_local_time and context (classes, functions, or code) from other files: # Path: django_test_tools/file_utils.py # class TemporaryFolder: # def __init__(self, base_name, delete_on_exit=True): # self.new_path = create_dated(base_name) # self.delete_on_exit = delete_on_exit # # def __enter__(self): # os.mkdir(self.new_path) # self.saved_path = os.getcwd() # os.chdir(self.new_path) # # return self # # def __exit__(self, exc_type, exc_val, exc_tb): # os.chdir(self.saved_path) # if self.delete_on_exit: # shutil.rmtree(self.new_path) # # def write(self, filename, content): # with open(filename, 'w', encoding='utf-8') as file: # if isinstance(content, str): # file.writelines(content) # elif isinstance(content, list): # for line in content: # file.write(line) # file.write('\n') # else: # file.writelines(str(content)) # return os.path.join(self.new_path, filename) # # def hash_file(filename, algorithm='sha1', block_size=BLOCKSIZE): # """ # Creates a unique hash for a file. # # :param filename: String with the full path to the file # :param algorithm: String Algorithm to create the hash # :param block_size: int for the size of the block while reading the file # :return: string the hash for the file # """ # try: # hasher = getattr(hashlib, algorithm)() # except AttributeError: # raise ValueError('{} is not a valid hashing algorithm'.format(algorithm)) # # with open(filename, 'rb') as afile: # buf = afile.read(block_size) # while len(buf) > 0: # hasher.update(buf) # buf = afile.read(block_size) # return hasher.hexdigest() # # Path: django_test_tools/utils.py # def versiontuple(v): # def dict_compare(d1, d2): # def convert_to_snake_case(camel_case): # def create_output_filename_with_date(filename): # def add_date_to_filename(filename, **kwargs): # def deprecated(func): # def new_func(*args, **kwargs): # def daterange(start_date, end_date): # def weekdays(start_date, end_date): # def __init__(self, newPath): # def __enter__(self): # def __exit__(self, etype, value, traceback): # def force_date_to_datetime(unconverted_date, tzinfo=pytz.UTC): # def __init__(self): # def start(self): # def stop(self): # def reset(self): # def get_elapsed_time(self): # def get_elapsed_time_str(self): # def running(self): # def __enter__(self): # def __exit__(self, *args): # def load_json_file(filename): # def datetime_to_local_time(date_time): # def __init__(self): # def _get_date_parts(self, match, input_lang='es'): # def parse(self, str_date): # def to_string(self, m_date): # def parse_spanish_date(str_date): # class cd: # class Timer: # class SpanishDate(object): . Output only the next line.
create_output_filename_with_date('kilo.txt')
Next line prediction: <|code_start|> logger = logging.getLogger(__name__) __author__ = 'lberrocal' class MockPerfCounter(object): def __init__(self): self.t = 0 def increment(self, n): self.t += n def perf_counter(self): return self.t class Testdict_compare(TestCase): def test_dict_compare(self): dict1 = {'name': 'Luis', 'colors': ['red', 'blue', 'black']} dict2 = {'name': 'Luis', 'colors': ['red', 'blue', 'black']} <|code_end|> . Use current file imports: (import datetime import logging import os import pytz from unittest import mock from django.test import TestCase, SimpleTestCase from django.test import override_settings from django_test_tools.file_utils import TemporaryFolder, hash_file from django_test_tools.utils import Timer, add_date_to_filename, daterange, parse_spanish_date, spanish_date_util, \ create_output_filename_with_date, dict_compare, convert_to_snake_case, datetime_to_local_time) and context including class names, function names, or small code snippets from other files: # Path: django_test_tools/file_utils.py # class TemporaryFolder: # def __init__(self, base_name, delete_on_exit=True): # self.new_path = create_dated(base_name) # self.delete_on_exit = delete_on_exit # # def __enter__(self): # os.mkdir(self.new_path) # self.saved_path = os.getcwd() # os.chdir(self.new_path) # # return self # # def __exit__(self, exc_type, exc_val, exc_tb): # os.chdir(self.saved_path) # if self.delete_on_exit: # shutil.rmtree(self.new_path) # # def write(self, filename, content): # with open(filename, 'w', encoding='utf-8') as file: # if isinstance(content, str): # file.writelines(content) # elif isinstance(content, list): # for line in content: # file.write(line) # file.write('\n') # else: # file.writelines(str(content)) # return os.path.join(self.new_path, filename) # # def hash_file(filename, algorithm='sha1', block_size=BLOCKSIZE): # """ # Creates a unique hash for a file. # # :param filename: String with the full path to the file # :param algorithm: String Algorithm to create the hash # :param block_size: int for the size of the block while reading the file # :return: string the hash for the file # """ # try: # hasher = getattr(hashlib, algorithm)() # except AttributeError: # raise ValueError('{} is not a valid hashing algorithm'.format(algorithm)) # # with open(filename, 'rb') as afile: # buf = afile.read(block_size) # while len(buf) > 0: # hasher.update(buf) # buf = afile.read(block_size) # return hasher.hexdigest() # # Path: django_test_tools/utils.py # def versiontuple(v): # def dict_compare(d1, d2): # def convert_to_snake_case(camel_case): # def create_output_filename_with_date(filename): # def add_date_to_filename(filename, **kwargs): # def deprecated(func): # def new_func(*args, **kwargs): # def daterange(start_date, end_date): # def weekdays(start_date, end_date): # def __init__(self, newPath): # def __enter__(self): # def __exit__(self, etype, value, traceback): # def force_date_to_datetime(unconverted_date, tzinfo=pytz.UTC): # def __init__(self): # def start(self): # def stop(self): # def reset(self): # def get_elapsed_time(self): # def get_elapsed_time_str(self): # def running(self): # def __enter__(self): # def __exit__(self, *args): # def load_json_file(filename): # def datetime_to_local_time(date_time): # def __init__(self): # def _get_date_parts(self, match, input_lang='es'): # def parse(self, str_date): # def to_string(self, m_date): # def parse_spanish_date(str_date): # class cd: # class Timer: # class SpanishDate(object): . Output only the next line.
added, removed, modified, same = dict_compare(dict1, dict2)
Predict the next line after this snippet: <|code_start|>class TemporyFolderTest(TestCase): def test_temporary_folder_write_list(self): with TemporaryFolder('my_temp_list', delete_on_exit=True) as folder: self.assertTrue(os.path.exists(folder.new_path)) filename = folder.write('m.txt', ['kilo', 'boma']) digest = hash_file(filename) self.assertEqual('5585c5895705bb5fe8906a2fd93453af5ee643b5', digest) self.assertFalse(os.path.exists(folder.new_path)) def test_temporary_folder_write_str(self): with TemporaryFolder('my_temp_str') as folder: self.assertTrue(os.path.exists(folder.new_path)) filename = folder.write('m.txt', 'Hola') digest = hash_file(filename) self.assertEqual('4e46dc0969e6621f2d61d2228e3cd91b75cd9edc', digest) self.assertFalse(os.path.exists(folder.new_path)) def test_temporary_folder_write_other(self): with TemporaryFolder('my_temp_date') as folder: self.assertTrue(os.path.exists(folder.new_path)) filename = folder.write('m.txt', datetime.date(2016, 12, 3)) digest = hash_file(filename) self.assertEqual('2b7db434f52eb470e1a6dcdc39063536c075a4f0', digest) self.assertFalse(os.path.exists(folder.new_path)) class TestSnakeCase(SimpleTestCase): def test_convert_to_snake_case(self): camel_case = 'OperatingSystem' <|code_end|> using the current file's imports: import datetime import logging import os import pytz from unittest import mock from django.test import TestCase, SimpleTestCase from django.test import override_settings from django_test_tools.file_utils import TemporaryFolder, hash_file from django_test_tools.utils import Timer, add_date_to_filename, daterange, parse_spanish_date, spanish_date_util, \ create_output_filename_with_date, dict_compare, convert_to_snake_case, datetime_to_local_time and any relevant context from other files: # Path: django_test_tools/file_utils.py # class TemporaryFolder: # def __init__(self, base_name, delete_on_exit=True): # self.new_path = create_dated(base_name) # self.delete_on_exit = delete_on_exit # # def __enter__(self): # os.mkdir(self.new_path) # self.saved_path = os.getcwd() # os.chdir(self.new_path) # # return self # # def __exit__(self, exc_type, exc_val, exc_tb): # os.chdir(self.saved_path) # if self.delete_on_exit: # shutil.rmtree(self.new_path) # # def write(self, filename, content): # with open(filename, 'w', encoding='utf-8') as file: # if isinstance(content, str): # file.writelines(content) # elif isinstance(content, list): # for line in content: # file.write(line) # file.write('\n') # else: # file.writelines(str(content)) # return os.path.join(self.new_path, filename) # # def hash_file(filename, algorithm='sha1', block_size=BLOCKSIZE): # """ # Creates a unique hash for a file. # # :param filename: String with the full path to the file # :param algorithm: String Algorithm to create the hash # :param block_size: int for the size of the block while reading the file # :return: string the hash for the file # """ # try: # hasher = getattr(hashlib, algorithm)() # except AttributeError: # raise ValueError('{} is not a valid hashing algorithm'.format(algorithm)) # # with open(filename, 'rb') as afile: # buf = afile.read(block_size) # while len(buf) > 0: # hasher.update(buf) # buf = afile.read(block_size) # return hasher.hexdigest() # # Path: django_test_tools/utils.py # def versiontuple(v): # def dict_compare(d1, d2): # def convert_to_snake_case(camel_case): # def create_output_filename_with_date(filename): # def add_date_to_filename(filename, **kwargs): # def deprecated(func): # def new_func(*args, **kwargs): # def daterange(start_date, end_date): # def weekdays(start_date, end_date): # def __init__(self, newPath): # def __enter__(self): # def __exit__(self, etype, value, traceback): # def force_date_to_datetime(unconverted_date, tzinfo=pytz.UTC): # def __init__(self): # def start(self): # def stop(self): # def reset(self): # def get_elapsed_time(self): # def get_elapsed_time_str(self): # def running(self): # def __enter__(self): # def __exit__(self, *args): # def load_json_file(filename): # def datetime_to_local_time(date_time): # def __init__(self): # def _get_date_parts(self, match, input_lang='es'): # def parse(self, str_date): # def to_string(self, m_date): # def parse_spanish_date(str_date): # class cd: # class Timer: # class SpanishDate(object): . Output only the next line.
snake_case = convert_to_snake_case(camel_case)
Using the snippet: <|code_start|> def test_temporary_folder_write_other(self): with TemporaryFolder('my_temp_date') as folder: self.assertTrue(os.path.exists(folder.new_path)) filename = folder.write('m.txt', datetime.date(2016, 12, 3)) digest = hash_file(filename) self.assertEqual('2b7db434f52eb470e1a6dcdc39063536c075a4f0', digest) self.assertFalse(os.path.exists(folder.new_path)) class TestSnakeCase(SimpleTestCase): def test_convert_to_snake_case(self): camel_case = 'OperatingSystem' snake_case = convert_to_snake_case(camel_case) self.assertEqual(snake_case, 'operating_system') def test_convert_to_snake_case_long(self): camel_case = 'OperatingSystemLongName' snake_case = convert_to_snake_case(camel_case) self.assertEqual(snake_case, 'operating_system_long_name') class TestDatetimeToLocalTime(SimpleTestCase): def test_datetime_to_local_time_datetime(self): input_date_format = '%Y-%m-%d %H:%M:%S %z' output_date_format = '%Y-%m-%d %H:%M:%S' date_value = '2018-09-23 09:37:50 -0500' datetime_object = datetime.datetime.strptime(date_value, input_date_format) <|code_end|> , determine the next line of code. You have imports: import datetime import logging import os import pytz from unittest import mock from django.test import TestCase, SimpleTestCase from django.test import override_settings from django_test_tools.file_utils import TemporaryFolder, hash_file from django_test_tools.utils import Timer, add_date_to_filename, daterange, parse_spanish_date, spanish_date_util, \ create_output_filename_with_date, dict_compare, convert_to_snake_case, datetime_to_local_time and context (class names, function names, or code) available: # Path: django_test_tools/file_utils.py # class TemporaryFolder: # def __init__(self, base_name, delete_on_exit=True): # self.new_path = create_dated(base_name) # self.delete_on_exit = delete_on_exit # # def __enter__(self): # os.mkdir(self.new_path) # self.saved_path = os.getcwd() # os.chdir(self.new_path) # # return self # # def __exit__(self, exc_type, exc_val, exc_tb): # os.chdir(self.saved_path) # if self.delete_on_exit: # shutil.rmtree(self.new_path) # # def write(self, filename, content): # with open(filename, 'w', encoding='utf-8') as file: # if isinstance(content, str): # file.writelines(content) # elif isinstance(content, list): # for line in content: # file.write(line) # file.write('\n') # else: # file.writelines(str(content)) # return os.path.join(self.new_path, filename) # # def hash_file(filename, algorithm='sha1', block_size=BLOCKSIZE): # """ # Creates a unique hash for a file. # # :param filename: String with the full path to the file # :param algorithm: String Algorithm to create the hash # :param block_size: int for the size of the block while reading the file # :return: string the hash for the file # """ # try: # hasher = getattr(hashlib, algorithm)() # except AttributeError: # raise ValueError('{} is not a valid hashing algorithm'.format(algorithm)) # # with open(filename, 'rb') as afile: # buf = afile.read(block_size) # while len(buf) > 0: # hasher.update(buf) # buf = afile.read(block_size) # return hasher.hexdigest() # # Path: django_test_tools/utils.py # def versiontuple(v): # def dict_compare(d1, d2): # def convert_to_snake_case(camel_case): # def create_output_filename_with_date(filename): # def add_date_to_filename(filename, **kwargs): # def deprecated(func): # def new_func(*args, **kwargs): # def daterange(start_date, end_date): # def weekdays(start_date, end_date): # def __init__(self, newPath): # def __enter__(self): # def __exit__(self, etype, value, traceback): # def force_date_to_datetime(unconverted_date, tzinfo=pytz.UTC): # def __init__(self): # def start(self): # def stop(self): # def reset(self): # def get_elapsed_time(self): # def get_elapsed_time_str(self): # def running(self): # def __enter__(self): # def __exit__(self, *args): # def load_json_file(filename): # def datetime_to_local_time(date_time): # def __init__(self): # def _get_date_parts(self, match, input_lang='es'): # def parse(self, str_date): # def to_string(self, m_date): # def parse_spanish_date(str_date): # class cd: # class Timer: # class SpanishDate(object): . Output only the next line.
datetime_object_with_timezone = datetime_to_local_time(datetime_object)
Based on the snippet: <|code_start|> faker = FakerFactory.create() class OperatingSystemFactory(DjangoModelFactory): class Meta: <|code_end|> , predict the immediate next line with the help of imports: import string from random import randint from pytz import timezone from django.conf import settings from factory import Iterator from factory import LazyAttribute from factory import SubFactory from factory import lazy_attribute from factory.django import DjangoModelFactory, FileField from factory.fuzzy import FuzzyText, FuzzyInteger from faker import Factory as FakerFactory from example.servers.models import OperatingSystem, Server and context (classes, functions, sometimes code) from other files: # Path: example/servers/models.py # class OperatingSystem(models.Model): # name = models.CharField(max_length=20) # version = models.CharField(max_length=5) # licenses_available = models.IntegerField() # cost = models.DecimalField(decimal_places=2, max_digits=7) # # class Meta: # unique_together = ('name', 'version') # # class Server(models.Model): # PRODUCTION = 'PROD' # DEVELOPMENT = 'DEV' # USE_CHOICES = ((PRODUCTION, 'Prod'), # (DEVELOPMENT, 'Dev')) # name = models.CharField(max_length=20, unique=True) # notes = models.TextField() # virtual = models.BooleanField() # ip_address = models.GenericIPAddressField() # created = models.DateTimeField() # online_date = models.DateField() # operating_system = models.ForeignKey(OperatingSystem, related_name='servers', on_delete=models.CASCADE) # server_id = models.CharField(max_length=6) # use = models.CharField(max_length=4, choices=USE_CHOICES, default=DEVELOPMENT) # comments = models.TextField(null=True, blank=True) . Output only the next line.
model = OperatingSystem
Given the code snippet: <|code_start|> faker = FakerFactory.create() class OperatingSystemFactory(DjangoModelFactory): class Meta: model = OperatingSystem name = LazyAttribute(lambda x: faker.text(max_nb_chars=20)) version = LazyAttribute(lambda x: faker.text(max_nb_chars=5)) licenses_available = LazyAttribute(lambda o: randint(1, 100)) cost = LazyAttribute(lambda x: faker.pydecimal(left_digits=5, right_digits=2, positive=True)) class ServerFactory(DjangoModelFactory): class Meta: <|code_end|> , generate the next line using the imports in this file: import string from random import randint from pytz import timezone from django.conf import settings from factory import Iterator from factory import LazyAttribute from factory import SubFactory from factory import lazy_attribute from factory.django import DjangoModelFactory, FileField from factory.fuzzy import FuzzyText, FuzzyInteger from faker import Factory as FakerFactory from example.servers.models import OperatingSystem, Server and context (functions, classes, or occasionally code) from other files: # Path: example/servers/models.py # class OperatingSystem(models.Model): # name = models.CharField(max_length=20) # version = models.CharField(max_length=5) # licenses_available = models.IntegerField() # cost = models.DecimalField(decimal_places=2, max_digits=7) # # class Meta: # unique_together = ('name', 'version') # # class Server(models.Model): # PRODUCTION = 'PROD' # DEVELOPMENT = 'DEV' # USE_CHOICES = ((PRODUCTION, 'Prod'), # (DEVELOPMENT, 'Dev')) # name = models.CharField(max_length=20, unique=True) # notes = models.TextField() # virtual = models.BooleanField() # ip_address = models.GenericIPAddressField() # created = models.DateTimeField() # online_date = models.DateField() # operating_system = models.ForeignKey(OperatingSystem, related_name='servers', on_delete=models.CASCADE) # server_id = models.CharField(max_length=6) # use = models.CharField(max_length=4, choices=USE_CHOICES, default=DEVELOPMENT) # comments = models.TextField(null=True, blank=True) . Output only the next line.
model = Server
Here is a snippet: <|code_start|> # ) # parser.add_argument("-a", "--assign", # action='store_true', # dest="assign", # help="Create unit assignments", # ) # # parser.add_argument("--office", # dest="office", # help="Organizational unit short name", # default=None, # ) # parser.add_argument("--start-date", # dest="start_date", # help="Start date for the assignment", # default=None, # ) # parser.add_argument("--fiscal-year", # dest="fiscal_year", # help="Fiscal year for assignments", # default=None, # ) # parser.add_argument("-u", "--username", # dest="usernames", # help="LDAP usernames for employees", # nargs='+', # ) def handle(self, *args, **options): app_name = options.get('app_name', None) <|code_end|> . Write the next line using the current file imports: from django.core.management import BaseCommand from ...app_manager import DjangoAppManager from ...generators.model_test_gen import AppModelsTestCaseGenerator and context from other files: # Path: django_test_tools/app_manager.py # class DjangoAppManager(object): # def __init__(self): # self.installed_apps = dict(self.get_installed_apps()) # # def get_app(self, app_name): # return self.installed_apps.get(app_name) # # def get_installed_apps(self): # for app_config in apps.get_app_configs(): # yield app_config.name, app_config # # def get_model(self, app_name, model_name): # app = self.get_app(app_name) # for model in app.get_models(): # if model_name == model.__name__: # return model # return None # # def get_project_apps(self, project_name): # project_apps = dict() # for app_name, app_config in self.installed_apps.items(): # app_project = app_name.split('.')[0] # if app_project == project_name: # project_apps[app_name] = app_config # return project_apps # # def get_app_data(self, app_name): # """ # Read application data converts into a dictionary # # :param app_name: Application name # :return: Dictionary with application data # """ # app = self.get_app(app_name) # app_dict = dict() # app_dict['app_name'] = app.name # app_dict['models'] = dict() # for key, model in app.models.items(): # app_dict['models'][key] = dict() # app_dict['models'][key]['model_name'] = model.__name__ # app_dict['models'][key]['original_attrs'] = model._meta.original_attrs # app_dict['models'][key]['fields'] = list() # for field in model._meta.fields: # self._convert_field_to_dict(field, app_dict['models'][key]['fields']) # # return app_dict # # def _convert_field_to_dict(self, field, field_list): # field_dict = dict() # field_dict['field_name'] = field.name # field_dict['type'] = type(field).__name__ # field_dict['unique'] = field.unique # field_dict['primary_key'] = field.primary_key # field_dict['editable'] = field.editable # if hasattr(field, 'choices') and field.choices is not None: # field_dict['choices_type'] = type(field.choices).__name__ # if field_dict['choices_type'] == 'tuple': # field_dict['choices'] = field.choices # if hasattr(field, 'max_length') and field.max_length is not None: # field_dict['max_length'] = field.max_length # if hasattr(field, 'max_digits') and field.max_digits is not None: # field_dict['max_digits'] = field.max_digits # if hasattr(field, 'decimal_places') and field.decimal_places is not None: # field_dict['decimal_places'] = field.decimal_places # if hasattr(field, 'remote_field') and field.remote_field is not None: # field_dict['remote_field'] = field.remote_field.model.__name__ # field_list.append(field_dict) # return field_dict # # Path: django_test_tools/generators/model_test_gen.py # class AppModelsTestCaseGenerator(object): # def __init__(self, app): # self.app = app # # def _generate(self): # app_content = list() # for model in self.app.get_models(): # model_test_case = ModelTestCaseGenerator(model) # app_content.append(model_test_case) # return app_content # # def _get_imports(self): # imports_to_print = list(set(PRINT_IMPORTS)) # imports_to_print.sort(reverse=True) # return '\n'.join(imports_to_print) # # def __str__(self): # printable = list() # printable.append(self._get_imports()) # for model_test_cases in self._generate(): # printable.append(str(model_test_cases)) # # return '\n'.join(printable) , which may include functions, classes, or code. Output only the next line.
app_manager = DjangoAppManager()
Continue the code snippet: <|code_start|> # dest="assign", # help="Create unit assignments", # ) # # parser.add_argument("--office", # dest="office", # help="Organizational unit short name", # default=None, # ) # parser.add_argument("--start-date", # dest="start_date", # help="Start date for the assignment", # default=None, # ) # parser.add_argument("--fiscal-year", # dest="fiscal_year", # help="Fiscal year for assignments", # default=None, # ) # parser.add_argument("-u", "--username", # dest="usernames", # help="LDAP usernames for employees", # nargs='+', # ) def handle(self, *args, **options): app_name = options.get('app_name', None) app_manager = DjangoAppManager() app = app_manager.get_app(app_name) if app: <|code_end|> . Use current file imports: from django.core.management import BaseCommand from ...app_manager import DjangoAppManager from ...generators.model_test_gen import AppModelsTestCaseGenerator and context (classes, functions, or code) from other files: # Path: django_test_tools/app_manager.py # class DjangoAppManager(object): # def __init__(self): # self.installed_apps = dict(self.get_installed_apps()) # # def get_app(self, app_name): # return self.installed_apps.get(app_name) # # def get_installed_apps(self): # for app_config in apps.get_app_configs(): # yield app_config.name, app_config # # def get_model(self, app_name, model_name): # app = self.get_app(app_name) # for model in app.get_models(): # if model_name == model.__name__: # return model # return None # # def get_project_apps(self, project_name): # project_apps = dict() # for app_name, app_config in self.installed_apps.items(): # app_project = app_name.split('.')[0] # if app_project == project_name: # project_apps[app_name] = app_config # return project_apps # # def get_app_data(self, app_name): # """ # Read application data converts into a dictionary # # :param app_name: Application name # :return: Dictionary with application data # """ # app = self.get_app(app_name) # app_dict = dict() # app_dict['app_name'] = app.name # app_dict['models'] = dict() # for key, model in app.models.items(): # app_dict['models'][key] = dict() # app_dict['models'][key]['model_name'] = model.__name__ # app_dict['models'][key]['original_attrs'] = model._meta.original_attrs # app_dict['models'][key]['fields'] = list() # for field in model._meta.fields: # self._convert_field_to_dict(field, app_dict['models'][key]['fields']) # # return app_dict # # def _convert_field_to_dict(self, field, field_list): # field_dict = dict() # field_dict['field_name'] = field.name # field_dict['type'] = type(field).__name__ # field_dict['unique'] = field.unique # field_dict['primary_key'] = field.primary_key # field_dict['editable'] = field.editable # if hasattr(field, 'choices') and field.choices is not None: # field_dict['choices_type'] = type(field.choices).__name__ # if field_dict['choices_type'] == 'tuple': # field_dict['choices'] = field.choices # if hasattr(field, 'max_length') and field.max_length is not None: # field_dict['max_length'] = field.max_length # if hasattr(field, 'max_digits') and field.max_digits is not None: # field_dict['max_digits'] = field.max_digits # if hasattr(field, 'decimal_places') and field.decimal_places is not None: # field_dict['decimal_places'] = field.decimal_places # if hasattr(field, 'remote_field') and field.remote_field is not None: # field_dict['remote_field'] = field.remote_field.model.__name__ # field_list.append(field_dict) # return field_dict # # Path: django_test_tools/generators/model_test_gen.py # class AppModelsTestCaseGenerator(object): # def __init__(self, app): # self.app = app # # def _generate(self): # app_content = list() # for model in self.app.get_models(): # model_test_case = ModelTestCaseGenerator(model) # app_content.append(model_test_case) # return app_content # # def _get_imports(self): # imports_to_print = list(set(PRINT_IMPORTS)) # imports_to_print.sort(reverse=True) # return '\n'.join(imports_to_print) # # def __str__(self): # printable = list() # printable.append(self._get_imports()) # for model_test_cases in self._generate(): # printable.append(str(model_test_cases)) # # return '\n'.join(printable) . Output only the next line.
app_model_tests = AppModelsTestCaseGenerator(app)
Predict the next line after this snippet: <|code_start|> def get_results(self, content=None): if content is None: content = self.content content.seek(0) lines = content.readlines() results = list() for line in lines: results.append(line.strip('\n')) return results def get_errors(self): return self.get_results(self.error_content) class TestOutputMixin(object): clean_output = True def clean_output_folder(self, dated_filename): if self.clean_output: os.remove(dated_filename) # noinspection PyUnresolvedReferences self.assertFalse(os.path.exists(dated_filename)) def get_excel_content(self, filename, sheet_name=None): """ Reads the content of an excel file and returns the content a as list of row lists. :param filename: string full path to the filename :param sheet_name: string. Name of the sheet to read if None will read the active sheet :return: a list containing a list of values for every row. """ <|code_end|> using the current file's imports: import csv import json import os from io import StringIO from django.conf import settings from django.urls import reverse from rest_framework.test import APIClient from .excel import ExcelAdapter from .exceptions import DjangoTestToolsException and any relevant context from other files: # Path: django_test_tools/excel.py # class ExcelAdapter(object): # # @classmethod # def convert_to_list(cls, filename, sheet_name=None, has_header=True): # """ # Reads an Excel file and converts every row into a dictionary. All values are converted to strings. # Assumes first row contains the name of the attributes. # # :param filename: <str> Excel filename # :param sheet_name: <str> Name of the sheet # :return: <list> A list of dictionaries. # """ # data = list() # wb = load_workbook(filename=filename, data_only=True) # if sheet_name is None: # sheet = wb.active # else: # sheet = wb[sheet_name] # row_num = 1 # for row in sheet.rows: # row_data = list() # if row_num == 1 and has_header: # row_num += 1 # continue # for column in range(0, len(row)): # row_data.append(row[column].value) # data.append(row_data) # row_num += 1 # return data # # @classmethod # def convert_to_dict(cls, filename, sheet_name=None): # """ # Reads an Excel file and converts every row into a dictionary. All values are converted to strings. # Assumes first row contains the name of the attributes. # # :param filename: <str> Excel filename # :param sheet_name: <str> Name of the sheet # :return: <list> A list of dictionaries. # """ # data = list() # wb = load_workbook(filename=filename, data_only=True) # if sheet_name is None: # sheet = wb.active # else: # sheet = wb[sheet_name] # row_num = 1 # attributes = list() # for row in sheet.rows: # row_data = dict() # if row_num == 1: # row_num += 1 # for column in range(0, len(row)): # attributes.append(row[column].value) # continue # for column in range(0, len(row)): # row_data[attributes[column]] = str(row[column].value) # data.append(row_data) # row_num += 1 # return data # # Path: django_test_tools/exceptions.py # class DjangoTestToolsException(Exception): # pass . Output only the next line.
adapter = ExcelAdapter()
Given snippet: <|code_start|> def get_fixture_fullpath(self, fixture_filename): """ Get full patch for the fixture file :param fixture_filename: <str> name of the fixture file :return: <str> full path to fixture file """ self._sanity_check() if self.app_name is None: fixture_file = settings.APPS_DIR.path('tests', 'fixtures', fixture_filename).root else: fixture_file = settings.APPS_DIR.path(self.app_name, 'tests', 'fixtures', fixture_filename).root return fixture_file def get_fixture_json(self, fixture_filename): """ Reads a file and returns the json content. :param fixture_filename: <str> filename :return: <dict> With the file content """ fixture_file = self.get_fixture_fullpath(fixture_filename) with open(fixture_file, 'r') as f: json_data = json.load(f) return json_data def _sanity_check(self): if self.app_name is None and self.strict: <|code_end|> , continue by predicting the next line. Consider current file imports: import csv import json import os from io import StringIO from django.conf import settings from django.urls import reverse from rest_framework.test import APIClient from .excel import ExcelAdapter from .exceptions import DjangoTestToolsException and context: # Path: django_test_tools/excel.py # class ExcelAdapter(object): # # @classmethod # def convert_to_list(cls, filename, sheet_name=None, has_header=True): # """ # Reads an Excel file and converts every row into a dictionary. All values are converted to strings. # Assumes first row contains the name of the attributes. # # :param filename: <str> Excel filename # :param sheet_name: <str> Name of the sheet # :return: <list> A list of dictionaries. # """ # data = list() # wb = load_workbook(filename=filename, data_only=True) # if sheet_name is None: # sheet = wb.active # else: # sheet = wb[sheet_name] # row_num = 1 # for row in sheet.rows: # row_data = list() # if row_num == 1 and has_header: # row_num += 1 # continue # for column in range(0, len(row)): # row_data.append(row[column].value) # data.append(row_data) # row_num += 1 # return data # # @classmethod # def convert_to_dict(cls, filename, sheet_name=None): # """ # Reads an Excel file and converts every row into a dictionary. All values are converted to strings. # Assumes first row contains the name of the attributes. # # :param filename: <str> Excel filename # :param sheet_name: <str> Name of the sheet # :return: <list> A list of dictionaries. # """ # data = list() # wb = load_workbook(filename=filename, data_only=True) # if sheet_name is None: # sheet = wb.active # else: # sheet = wb[sheet_name] # row_num = 1 # attributes = list() # for row in sheet.rows: # row_data = dict() # if row_num == 1: # row_num += 1 # for column in range(0, len(row)): # attributes.append(row[column].value) # continue # for column in range(0, len(row)): # row_data[attributes[column]] = str(row[column].value) # data.append(row_data) # row_num += 1 # return data # # Path: django_test_tools/exceptions.py # class DjangoTestToolsException(Exception): # pass which might include code, classes, or functions. Output only the next line.
raise DjangoTestToolsException('app_name not defined')
Predict the next line for this snippet: <|code_start|> class UrlGenerator(object): def __init__(self, model_name): self.model_name = model_name self.template = 'django_test_tools/urls.py.j2' def print_urls(self, filename): self._print(filename, 'urls') def print_paths(self, filename): self._print(filename, 'paths') def _print(self, filename, what_to_print): data = dict() data['model_name'] = self.model_name data['print_{}'.format(what_to_print)] = True rendered = render_to_string(self.template, data) with open(filename, 'w', encoding='utf-8') as url_file: url_file.write(rendered) class SerializerTestGenerator(object): def __init__(self): self.env = Environment( loader=PackageLoader('django_test_tools', 'templates'), autoescape=select_autoescape(['html', 'j2']) ) <|code_end|> with the help of current file imports: from django.template.loader import render_to_string from jinja2 import Environment, PackageLoader, select_autoescape from ..templatetags.dtt_filters import to_snake_case and context from other files: # Path: django_test_tools/templatetags/dtt_filters.py # @register.filter(name='to_snake_case') # def to_snake_case(name): # s1 = first_cap_re.sub(r'\1_\2', name) # return all_cap_re.sub(r'\1_\2', s1).lower() , which may contain function names, class names, or code. Output only the next line.
self.env.filters['to_snake_case'] = to_snake_case
Using the snippet: <|code_start|> class Command(BaseCommand): """ $ python manage.py generate_serializers_test my_application.app.api.serializers.MyObjectSerializer -f output/m.py """ def add_arguments(self, parser): parser.add_argument('serializer_class') parser.add_argument("-f", "--filename", dest="filename", help="Output filename", ) def handle(self, *args, **options): parts = options.get('serializer_class').split('.') serializer_class_name = parts[-1] module_name = '.'.join(parts[0:-1]) filename = options.get('filename') <|code_end|> , determine the next line of code. You have imports: import importlib from django.core.management import BaseCommand from ...generators.crud_generator import SerializerTestGenerator and context (class names, function names, or code) available: # Path: django_test_tools/generators/crud_generator.py # class SerializerTestGenerator(object): # # def __init__(self): # self.env = Environment( # loader=PackageLoader('django_test_tools', 'templates'), # autoescape=select_autoescape(['html', 'j2']) # ) # self.env.filters['to_snake_case'] = to_snake_case # # self.template_name = 'django_test_tools/test_serializers.py.j2' # self.template = self.env.get_template(self.template_name) # # def print(self, serializer_info, filename): # rendered = self.template.render(serializer_info) # with open(filename, 'w', encoding='utf-8') as file: # file.write(rendered) . Output only the next line.
generator = SerializerTestGenerator()
Given the code snippet: <|code_start|> class FactoryBoyGenerator(object): """ Currently supporting: - BooleanField - CharField - CountryField: from https://github.com/SmileyChris/django-countries - DateField: - DateTimeField - DecimalField - ForeignKey - GenericIPAddressField - IntegerField - MoneyField: from https://github.com/django-money/django-money - TextField The following fields are ignored by default 'AutoField', 'AutoCreatedField', 'AutoLastModifiedField' """ def __init__(self, **kwargs): <|code_end|> , generate the next line using the imports in this file: from django.utils import timezone from django_test_tools import __version__ as current_version from ..app_manager import DjangoAppManager and context (functions, classes, or occasionally code) from other files: # Path: django_test_tools/app_manager.py # class DjangoAppManager(object): # def __init__(self): # self.installed_apps = dict(self.get_installed_apps()) # # def get_app(self, app_name): # return self.installed_apps.get(app_name) # # def get_installed_apps(self): # for app_config in apps.get_app_configs(): # yield app_config.name, app_config # # def get_model(self, app_name, model_name): # app = self.get_app(app_name) # for model in app.get_models(): # if model_name == model.__name__: # return model # return None # # def get_project_apps(self, project_name): # project_apps = dict() # for app_name, app_config in self.installed_apps.items(): # app_project = app_name.split('.')[0] # if app_project == project_name: # project_apps[app_name] = app_config # return project_apps # # def get_app_data(self, app_name): # """ # Read application data converts into a dictionary # # :param app_name: Application name # :return: Dictionary with application data # """ # app = self.get_app(app_name) # app_dict = dict() # app_dict['app_name'] = app.name # app_dict['models'] = dict() # for key, model in app.models.items(): # app_dict['models'][key] = dict() # app_dict['models'][key]['model_name'] = model.__name__ # app_dict['models'][key]['original_attrs'] = model._meta.original_attrs # app_dict['models'][key]['fields'] = list() # for field in model._meta.fields: # self._convert_field_to_dict(field, app_dict['models'][key]['fields']) # # return app_dict # # def _convert_field_to_dict(self, field, field_list): # field_dict = dict() # field_dict['field_name'] = field.name # field_dict['type'] = type(field).__name__ # field_dict['unique'] = field.unique # field_dict['primary_key'] = field.primary_key # field_dict['editable'] = field.editable # if hasattr(field, 'choices') and field.choices is not None: # field_dict['choices_type'] = type(field.choices).__name__ # if field_dict['choices_type'] == 'tuple': # field_dict['choices'] = field.choices # if hasattr(field, 'max_length') and field.max_length is not None: # field_dict['max_length'] = field.max_length # if hasattr(field, 'max_digits') and field.max_digits is not None: # field_dict['max_digits'] = field.max_digits # if hasattr(field, 'decimal_places') and field.decimal_places is not None: # field_dict['decimal_places'] = field.decimal_places # if hasattr(field, 'remote_field') and field.remote_field is not None: # field_dict['remote_field'] = field.remote_field.model.__name__ # field_list.append(field_dict) # return field_dict . Output only the next line.
self.app_manager = DjangoAppManager()
Using the snippet: <|code_start|> self.assertIsNotNone(operatingsystem.cost) # def test_(self): # operatingsystem = OperatingSystemFactory.create() # servers = ServerFactory.create_batch(5, operating_system=operatingsystem) # from django.conf import settings # from django.db import connection, reset_queries # # try: # settings.DEBUG = True # #servers = operatingsystem.servers.all() # for s in servers: # k = s.operating_system.name # self.assertEquals(len(connection.queries), 1000000) # finally: # settings.DEBUG = False # reset_queries() class TestCaseServer(TestCase): def test_create(self): """ Test the creation of a Server model using a factory """ server = ServerFactory.create() <|code_end|> , determine the next line of code. You have imports: from example.servers.models import Server from ..factories import ServerFactory from django.forms.models import model_to_dict from django.test import TestCase from django.conf import settings from example.servers.models import OperatingSystem from ..factories import OperatingSystemFactory from django.db import IntegrityError and context (class names, function names, or code) available: # Path: example/servers/models.py # class Server(models.Model): # PRODUCTION = 'PROD' # DEVELOPMENT = 'DEV' # USE_CHOICES = ((PRODUCTION, 'Prod'), # (DEVELOPMENT, 'Dev')) # name = models.CharField(max_length=20, unique=True) # notes = models.TextField() # virtual = models.BooleanField() # ip_address = models.GenericIPAddressField() # created = models.DateTimeField() # online_date = models.DateField() # operating_system = models.ForeignKey(OperatingSystem, related_name='servers', on_delete=models.CASCADE) # server_id = models.CharField(max_length=6) # use = models.CharField(max_length=4, choices=USE_CHOICES, default=DEVELOPMENT) # comments = models.TextField(null=True, blank=True) # # Path: example/servers/tests/factories.py # class ServerFactory(DjangoModelFactory): # class Meta: # model = Server # # name = LazyAttribute(lambda x: faker.text(max_nb_chars=20)) # notes = LazyAttribute(lambda x: faker.paragraph(nb_sentences=3, variable_nb_sentences=True)) # virtual = Iterator([True, False]) # ip_address = LazyAttribute(lambda o: faker.ipv4(network=False)) # created = LazyAttribute(lambda x: faker.date_time_between(start_date="-1y", end_date="now", # tzinfo=timezone(settings.TIME_ZONE))) # online_date = LazyAttribute(lambda x: faker.date_time_between(start_date="-1y", end_date="now", # tzinfo=timezone(settings.TIME_ZONE))) # operating_system = SubFactory(OperatingSystemFactory) # server_id = LazyAttribute(lambda x: FuzzyText(length=6, chars=string.digits).fuzz()) # use = Iterator(Server.USE_CHOICES, getter=lambda x: x[0]) # comments = LazyAttribute(lambda x: faker.paragraph(nb_sentences=3, variable_nb_sentences=True)) # # Path: example/servers/models.py # class OperatingSystem(models.Model): # name = models.CharField(max_length=20) # version = models.CharField(max_length=5) # licenses_available = models.IntegerField() # cost = models.DecimalField(decimal_places=2, max_digits=7) # # class Meta: # unique_together = ('name', 'version') # # Path: example/servers/tests/factories.py # class OperatingSystemFactory(DjangoModelFactory): # class Meta: # model = OperatingSystem # # name = LazyAttribute(lambda x: faker.text(max_nb_chars=20)) # version = LazyAttribute(lambda x: faker.text(max_nb_chars=5)) # licenses_available = LazyAttribute(lambda o: randint(1, 100)) # cost = LazyAttribute(lambda x: faker.pydecimal(left_digits=5, right_digits=2, positive=True)) . Output only the next line.
self.assertEqual(1, Server.objects.count())
Based on the snippet: <|code_start|> self.assertIsNotNone(operatingsystem.licenses_available) self.assertIsNotNone(operatingsystem.cost) # def test_(self): # operatingsystem = OperatingSystemFactory.create() # servers = ServerFactory.create_batch(5, operating_system=operatingsystem) # from django.conf import settings # from django.db import connection, reset_queries # # try: # settings.DEBUG = True # #servers = operatingsystem.servers.all() # for s in servers: # k = s.operating_system.name # self.assertEquals(len(connection.queries), 1000000) # finally: # settings.DEBUG = False # reset_queries() class TestCaseServer(TestCase): def test_create(self): """ Test the creation of a Server model using a factory """ <|code_end|> , predict the immediate next line with the help of imports: from example.servers.models import Server from ..factories import ServerFactory from django.forms.models import model_to_dict from django.test import TestCase from django.conf import settings from example.servers.models import OperatingSystem from ..factories import OperatingSystemFactory from django.db import IntegrityError and context (classes, functions, sometimes code) from other files: # Path: example/servers/models.py # class Server(models.Model): # PRODUCTION = 'PROD' # DEVELOPMENT = 'DEV' # USE_CHOICES = ((PRODUCTION, 'Prod'), # (DEVELOPMENT, 'Dev')) # name = models.CharField(max_length=20, unique=True) # notes = models.TextField() # virtual = models.BooleanField() # ip_address = models.GenericIPAddressField() # created = models.DateTimeField() # online_date = models.DateField() # operating_system = models.ForeignKey(OperatingSystem, related_name='servers', on_delete=models.CASCADE) # server_id = models.CharField(max_length=6) # use = models.CharField(max_length=4, choices=USE_CHOICES, default=DEVELOPMENT) # comments = models.TextField(null=True, blank=True) # # Path: example/servers/tests/factories.py # class ServerFactory(DjangoModelFactory): # class Meta: # model = Server # # name = LazyAttribute(lambda x: faker.text(max_nb_chars=20)) # notes = LazyAttribute(lambda x: faker.paragraph(nb_sentences=3, variable_nb_sentences=True)) # virtual = Iterator([True, False]) # ip_address = LazyAttribute(lambda o: faker.ipv4(network=False)) # created = LazyAttribute(lambda x: faker.date_time_between(start_date="-1y", end_date="now", # tzinfo=timezone(settings.TIME_ZONE))) # online_date = LazyAttribute(lambda x: faker.date_time_between(start_date="-1y", end_date="now", # tzinfo=timezone(settings.TIME_ZONE))) # operating_system = SubFactory(OperatingSystemFactory) # server_id = LazyAttribute(lambda x: FuzzyText(length=6, chars=string.digits).fuzz()) # use = Iterator(Server.USE_CHOICES, getter=lambda x: x[0]) # comments = LazyAttribute(lambda x: faker.paragraph(nb_sentences=3, variable_nb_sentences=True)) # # Path: example/servers/models.py # class OperatingSystem(models.Model): # name = models.CharField(max_length=20) # version = models.CharField(max_length=5) # licenses_available = models.IntegerField() # cost = models.DecimalField(decimal_places=2, max_digits=7) # # class Meta: # unique_together = ('name', 'version') # # Path: example/servers/tests/factories.py # class OperatingSystemFactory(DjangoModelFactory): # class Meta: # model = OperatingSystem # # name = LazyAttribute(lambda x: faker.text(max_nb_chars=20)) # version = LazyAttribute(lambda x: faker.text(max_nb_chars=5)) # licenses_available = LazyAttribute(lambda o: randint(1, 100)) # cost = LazyAttribute(lambda x: faker.pydecimal(left_digits=5, right_digits=2, positive=True)) . Output only the next line.
server = ServerFactory.create()
Predict the next line for this snippet: <|code_start|> class TestCaseOperatingSystem(TestCase): def test_create(self): """ Test the creation of a OperatingSystem model using a factory """ operatingsystem = OperatingSystemFactory.create() <|code_end|> with the help of current file imports: from example.servers.models import Server from ..factories import ServerFactory from django.forms.models import model_to_dict from django.test import TestCase from django.conf import settings from example.servers.models import OperatingSystem from ..factories import OperatingSystemFactory from django.db import IntegrityError and context from other files: # Path: example/servers/models.py # class Server(models.Model): # PRODUCTION = 'PROD' # DEVELOPMENT = 'DEV' # USE_CHOICES = ((PRODUCTION, 'Prod'), # (DEVELOPMENT, 'Dev')) # name = models.CharField(max_length=20, unique=True) # notes = models.TextField() # virtual = models.BooleanField() # ip_address = models.GenericIPAddressField() # created = models.DateTimeField() # online_date = models.DateField() # operating_system = models.ForeignKey(OperatingSystem, related_name='servers', on_delete=models.CASCADE) # server_id = models.CharField(max_length=6) # use = models.CharField(max_length=4, choices=USE_CHOICES, default=DEVELOPMENT) # comments = models.TextField(null=True, blank=True) # # Path: example/servers/tests/factories.py # class ServerFactory(DjangoModelFactory): # class Meta: # model = Server # # name = LazyAttribute(lambda x: faker.text(max_nb_chars=20)) # notes = LazyAttribute(lambda x: faker.paragraph(nb_sentences=3, variable_nb_sentences=True)) # virtual = Iterator([True, False]) # ip_address = LazyAttribute(lambda o: faker.ipv4(network=False)) # created = LazyAttribute(lambda x: faker.date_time_between(start_date="-1y", end_date="now", # tzinfo=timezone(settings.TIME_ZONE))) # online_date = LazyAttribute(lambda x: faker.date_time_between(start_date="-1y", end_date="now", # tzinfo=timezone(settings.TIME_ZONE))) # operating_system = SubFactory(OperatingSystemFactory) # server_id = LazyAttribute(lambda x: FuzzyText(length=6, chars=string.digits).fuzz()) # use = Iterator(Server.USE_CHOICES, getter=lambda x: x[0]) # comments = LazyAttribute(lambda x: faker.paragraph(nb_sentences=3, variable_nb_sentences=True)) # # Path: example/servers/models.py # class OperatingSystem(models.Model): # name = models.CharField(max_length=20) # version = models.CharField(max_length=5) # licenses_available = models.IntegerField() # cost = models.DecimalField(decimal_places=2, max_digits=7) # # class Meta: # unique_together = ('name', 'version') # # Path: example/servers/tests/factories.py # class OperatingSystemFactory(DjangoModelFactory): # class Meta: # model = OperatingSystem # # name = LazyAttribute(lambda x: faker.text(max_nb_chars=20)) # version = LazyAttribute(lambda x: faker.text(max_nb_chars=5)) # licenses_available = LazyAttribute(lambda o: randint(1, 100)) # cost = LazyAttribute(lambda x: faker.pydecimal(left_digits=5, right_digits=2, positive=True)) , which may contain function names, class names, or code. Output only the next line.
self.assertEqual(1, OperatingSystem.objects.count())
Continue the code snippet: <|code_start|> class TestCaseOperatingSystem(TestCase): def test_create(self): """ Test the creation of a OperatingSystem model using a factory """ <|code_end|> . Use current file imports: from example.servers.models import Server from ..factories import ServerFactory from django.forms.models import model_to_dict from django.test import TestCase from django.conf import settings from example.servers.models import OperatingSystem from ..factories import OperatingSystemFactory from django.db import IntegrityError and context (classes, functions, or code) from other files: # Path: example/servers/models.py # class Server(models.Model): # PRODUCTION = 'PROD' # DEVELOPMENT = 'DEV' # USE_CHOICES = ((PRODUCTION, 'Prod'), # (DEVELOPMENT, 'Dev')) # name = models.CharField(max_length=20, unique=True) # notes = models.TextField() # virtual = models.BooleanField() # ip_address = models.GenericIPAddressField() # created = models.DateTimeField() # online_date = models.DateField() # operating_system = models.ForeignKey(OperatingSystem, related_name='servers', on_delete=models.CASCADE) # server_id = models.CharField(max_length=6) # use = models.CharField(max_length=4, choices=USE_CHOICES, default=DEVELOPMENT) # comments = models.TextField(null=True, blank=True) # # Path: example/servers/tests/factories.py # class ServerFactory(DjangoModelFactory): # class Meta: # model = Server # # name = LazyAttribute(lambda x: faker.text(max_nb_chars=20)) # notes = LazyAttribute(lambda x: faker.paragraph(nb_sentences=3, variable_nb_sentences=True)) # virtual = Iterator([True, False]) # ip_address = LazyAttribute(lambda o: faker.ipv4(network=False)) # created = LazyAttribute(lambda x: faker.date_time_between(start_date="-1y", end_date="now", # tzinfo=timezone(settings.TIME_ZONE))) # online_date = LazyAttribute(lambda x: faker.date_time_between(start_date="-1y", end_date="now", # tzinfo=timezone(settings.TIME_ZONE))) # operating_system = SubFactory(OperatingSystemFactory) # server_id = LazyAttribute(lambda x: FuzzyText(length=6, chars=string.digits).fuzz()) # use = Iterator(Server.USE_CHOICES, getter=lambda x: x[0]) # comments = LazyAttribute(lambda x: faker.paragraph(nb_sentences=3, variable_nb_sentences=True)) # # Path: example/servers/models.py # class OperatingSystem(models.Model): # name = models.CharField(max_length=20) # version = models.CharField(max_length=5) # licenses_available = models.IntegerField() # cost = models.DecimalField(decimal_places=2, max_digits=7) # # class Meta: # unique_together = ('name', 'version') # # Path: example/servers/tests/factories.py # class OperatingSystemFactory(DjangoModelFactory): # class Meta: # model = OperatingSystem # # name = LazyAttribute(lambda x: faker.text(max_nb_chars=20)) # version = LazyAttribute(lambda x: faker.text(max_nb_chars=5)) # licenses_available = LazyAttribute(lambda o: randint(1, 100)) # cost = LazyAttribute(lambda x: faker.pydecimal(left_digits=5, right_digits=2, positive=True)) . Output only the next line.
operatingsystem = OperatingSystemFactory.create()
Based on the snippet: <|code_start|> else: file.writelines(str(content)) return os.path.join(self.new_path, filename) def compare_file_content(*args, **kwargs): errors = list() file1 = args[0] file2 = args[1] excluded_lines = kwargs.get('excluded_lines', []) encoding = kwargs.get('encoding', 'utf-8') raise_exception = kwargs.get('raise_exception', True) eol = kwargs.get('eol', '\n') def get_lines(filename): with open(filename, 'r', encoding=encoding, newline=eol) as file: lines = file.readlines() return lines lines1 = get_lines(file1) lines2 = get_lines(file2) for i in range(len(lines1)): if i not in excluded_lines: if lines1[i] != lines2[i]: msg = 'On line {} expected "{}" got "{}"'.format(i, lines1[i].replace(eol, ''), lines2[i].replace(eol, '')) errors.append(msg) if raise_exception: <|code_end|> , predict the immediate next line with the help of imports: import hashlib import json import os import pickle import shutil from datetime import date, datetime from django.conf import settings from django.utils import timezone from django_test_tools.exceptions import DjangoTestToolsException and context (classes, functions, sometimes code) from other files: # Path: django_test_tools/exceptions.py # class DjangoTestToolsException(Exception): # pass . Output only the next line.
raise DjangoTestToolsException(msg)
Given the code snippet: <|code_start|> """ Converts a CamelCase name to snake case. ..code-block:: python camel_case = 'OperatingSystemLongName' snake_case = convert_to_snake_case(camel_case) self.assertEqual(snake_case, 'operating_system_long_name') :param camel_case: string. Camel case name :return: string. Snake case name """ s1 = first_cap_re.sub(r'\1_\2', camel_case) return all_cap_re.sub(r'\1_\2', s1).lower() @deprecated('Should use django_test_tools.file_utils.create_dated() function') def create_output_filename_with_date(filename): """ Based on the filename will create a full path filename incluidn the date and time in '%Y%m%d_%H%M' format. The path to the filename will be set in the TEST_OUTPUT_PATH settings variable. :param filename: base filename. my_excel_data.xlsx for example :return: string, full path to file with date and time in the TEST_OUTPUT_PATH folder """ if getattr(settings, 'TEST_OUTPUT_PATH', None) is None: msg = 'You need a the variable TEST_OUTPUT_PATH in settings. It should point to a folder' \ 'for temporary data to be written and reviewed.' raise ValueError(msg) if not os.path.exists(settings.TEST_OUTPUT_PATH): os.makedirs(settings.TEST_OUTPUT_PATH) <|code_end|> , generate the next line using the imports in this file: import functools import json import os import re import time import warnings import pytz from datetime import datetime, date, timedelta from django.conf import settings from django.utils import timezone from openpyxl.compat import deprecated from .file_utils import add_date and context (functions, classes, or occasionally code) from other files: # Path: django_test_tools/file_utils.py # def add_date(filename, **kwargs): # """ # Adds to a filename the current date and time in '%Y%m%d_%H%M' format. # For a filename /my/path/myexcel.xlsx the function would return /my/path/myexcel_20170101_1305.xlsx. # If the file already exists the function will add seconds to the date to attempt to get a unique name. # # The function will detect if another file exists with the same name if it exist it will append seconds to the # filename. For example if file /my/path/myexcel_20170101_1305.xlsx alread exist thte function will return # /my/path/myexcel_20170101_130521.xlsx. # # :param filename: string with fullpath to file or just the filename # :param kwargs: dictionary. date_position: suffix or preffix, extension: string to replace extension # :return: string with full path string including the date and time # """ # current_datetime = timezone.localtime(timezone.now()).strftime('%Y%m%d_%H%M%S') # new_filename_data = dict() # suffix_template = '{path}{separator}{filename_with_out_extension}_{datetime}.{extension}' # prefix_template = '{path}{separator}{datetime}_{filename_with_out_extension}.{extension}' # if '/' in filename and '\\' in filename: # raise ValueError('Filename %s contains both / and \\ separators' % filename) # if '\\' in filename: # path_parts = filename.split('\\') # file = path_parts[-1] # path = '\\'.join(path_parts[:-1]) # separator = '\\' # elif '/' in filename: # path_parts = filename.split('/') # file = path_parts[-1] # path = '/'.join(path_parts[:-1]) # separator = '/' # else: # file = filename # path = '' # separator = '' # # new_filename_data['path'] = path # parts = file.split('.') # if kwargs.get('extension', None) is not None: # new_filename_data['extension'] = kwargs['extension'] # else: # if len(parts) > 1: # new_filename_data['extension'] = parts[-1] # else: # new_filename_data['extension'] = '' # # new_filename_data['separator'] = separator # if new_filename_data['extension'] == '': # new_filename_data['filename_with_out_extension'] = parts[0] # else: # new_filename_data['filename_with_out_extension'] = '.'.join(parts[:-1]) # new_filename_data['datetime'] = current_datetime[:-2] # Seconds are stripped # # date_position = kwargs.get('date_position', 'suffix') # if date_position == 'suffix': # new_filename = suffix_template.format(**new_filename_data) # if os.path.exists(new_filename): # new_filename_data['datetime'] = current_datetime # new_filename = suffix_template.format(**new_filename_data) # if new_filename_data['extension'] == '': # new_filename = new_filename[:-1] # else: # new_filename = prefix_template.format(**new_filename_data) # if os.path.exists(new_filename): # new_filename_data['datetime'] = current_datetime # new_filename = prefix_template.format(**new_filename_data) # if new_filename_data['extension'] == '': # new_filename = new_filename[:-1] # # return new_filename . Output only the next line.
return add_date(os.path.join(settings.TEST_OUTPUT_PATH, filename))
Next line prediction: <|code_start|> ) # parser.add_argument("-a", "--assign", # action='store_true', # dest="assign", # help="Create unit assignments", # ) # # parser.add_argument("--office", # dest="office", # help="Organizational unit short name", # default=None, # ) # parser.add_argument("--start-date", # dest="start_date", # help="Start date for the assignment", # default=None, # ) # parser.add_argument("--fiscal-year", # dest="fiscal_year", # help="Fiscal year for assignments", # default=None, # ) # parser.add_argument("-u", "--username", # dest="usernames", # help="LDAP usernames for employees", # nargs='+', # ) def handle(self, *args, **options): app_name = options.get('app_name', None) <|code_end|> . Use current file imports: (import json from django.core.management import BaseCommand from ...app_manager import DjangoAppManager) and context including class names, function names, or small code snippets from other files: # Path: django_test_tools/app_manager.py # class DjangoAppManager(object): # def __init__(self): # self.installed_apps = dict(self.get_installed_apps()) # # def get_app(self, app_name): # return self.installed_apps.get(app_name) # # def get_installed_apps(self): # for app_config in apps.get_app_configs(): # yield app_config.name, app_config # # def get_model(self, app_name, model_name): # app = self.get_app(app_name) # for model in app.get_models(): # if model_name == model.__name__: # return model # return None # # def get_project_apps(self, project_name): # project_apps = dict() # for app_name, app_config in self.installed_apps.items(): # app_project = app_name.split('.')[0] # if app_project == project_name: # project_apps[app_name] = app_config # return project_apps # # def get_app_data(self, app_name): # """ # Read application data converts into a dictionary # # :param app_name: Application name # :return: Dictionary with application data # """ # app = self.get_app(app_name) # app_dict = dict() # app_dict['app_name'] = app.name # app_dict['models'] = dict() # for key, model in app.models.items(): # app_dict['models'][key] = dict() # app_dict['models'][key]['model_name'] = model.__name__ # app_dict['models'][key]['original_attrs'] = model._meta.original_attrs # app_dict['models'][key]['fields'] = list() # for field in model._meta.fields: # self._convert_field_to_dict(field, app_dict['models'][key]['fields']) # # return app_dict # # def _convert_field_to_dict(self, field, field_list): # field_dict = dict() # field_dict['field_name'] = field.name # field_dict['type'] = type(field).__name__ # field_dict['unique'] = field.unique # field_dict['primary_key'] = field.primary_key # field_dict['editable'] = field.editable # if hasattr(field, 'choices') and field.choices is not None: # field_dict['choices_type'] = type(field.choices).__name__ # if field_dict['choices_type'] == 'tuple': # field_dict['choices'] = field.choices # if hasattr(field, 'max_length') and field.max_length is not None: # field_dict['max_length'] = field.max_length # if hasattr(field, 'max_digits') and field.max_digits is not None: # field_dict['max_digits'] = field.max_digits # if hasattr(field, 'decimal_places') and field.decimal_places is not None: # field_dict['decimal_places'] = field.decimal_places # if hasattr(field, 'remote_field') and field.remote_field is not None: # field_dict['remote_field'] = field.remote_field.model.__name__ # field_list.append(field_dict) # return field_dict . Output only the next line.
app_manager = DjangoAppManager()
Given the code snippet: <|code_start|> # ) # parser.add_argument("-a", "--assign", # action='store_true', # dest="assign", # help="Create unit assignments", # ) # # parser.add_argument("--office", # dest="office", # help="Organizational unit short name", # default=None, # ) # parser.add_argument("--start-date", # dest="start_date", # help="Start date for the assignment", # default=None, # ) # parser.add_argument("--fiscal-year", # dest="fiscal_year", # help="Fiscal year for assignments", # default=None, # ) # parser.add_argument("-u", "--username", # dest="usernames", # help="LDAP usernames for employees", # nargs='+', # ) def handle(self, *args, **options): if not options.get('output_file'): <|code_end|> , generate the next line using the imports in this file: import os from django.core.management import BaseCommand from ...file_utils import add_date from ...flake8.parsers import Flake8Parser, RadonParser and context (functions, classes, or occasionally code) from other files: # Path: django_test_tools/file_utils.py # def add_date(filename, **kwargs): # """ # Adds to a filename the current date and time in '%Y%m%d_%H%M' format. # For a filename /my/path/myexcel.xlsx the function would return /my/path/myexcel_20170101_1305.xlsx. # If the file already exists the function will add seconds to the date to attempt to get a unique name. # # The function will detect if another file exists with the same name if it exist it will append seconds to the # filename. For example if file /my/path/myexcel_20170101_1305.xlsx alread exist thte function will return # /my/path/myexcel_20170101_130521.xlsx. # # :param filename: string with fullpath to file or just the filename # :param kwargs: dictionary. date_position: suffix or preffix, extension: string to replace extension # :return: string with full path string including the date and time # """ # current_datetime = timezone.localtime(timezone.now()).strftime('%Y%m%d_%H%M%S') # new_filename_data = dict() # suffix_template = '{path}{separator}{filename_with_out_extension}_{datetime}.{extension}' # prefix_template = '{path}{separator}{datetime}_{filename_with_out_extension}.{extension}' # if '/' in filename and '\\' in filename: # raise ValueError('Filename %s contains both / and \\ separators' % filename) # if '\\' in filename: # path_parts = filename.split('\\') # file = path_parts[-1] # path = '\\'.join(path_parts[:-1]) # separator = '\\' # elif '/' in filename: # path_parts = filename.split('/') # file = path_parts[-1] # path = '/'.join(path_parts[:-1]) # separator = '/' # else: # file = filename # path = '' # separator = '' # # new_filename_data['path'] = path # parts = file.split('.') # if kwargs.get('extension', None) is not None: # new_filename_data['extension'] = kwargs['extension'] # else: # if len(parts) > 1: # new_filename_data['extension'] = parts[-1] # else: # new_filename_data['extension'] = '' # # new_filename_data['separator'] = separator # if new_filename_data['extension'] == '': # new_filename_data['filename_with_out_extension'] = parts[0] # else: # new_filename_data['filename_with_out_extension'] = '.'.join(parts[:-1]) # new_filename_data['datetime'] = current_datetime[:-2] # Seconds are stripped # # date_position = kwargs.get('date_position', 'suffix') # if date_position == 'suffix': # new_filename = suffix_template.format(**new_filename_data) # if os.path.exists(new_filename): # new_filename_data['datetime'] = current_datetime # new_filename = suffix_template.format(**new_filename_data) # if new_filename_data['extension'] == '': # new_filename = new_filename[:-1] # else: # new_filename = prefix_template.format(**new_filename_data) # if os.path.exists(new_filename): # new_filename_data['datetime'] = current_datetime # new_filename = prefix_template.format(**new_filename_data) # if new_filename_data['extension'] == '': # new_filename = new_filename[:-1] # # return new_filename . Output only the next line.
output_filename = add_date(options.get('input_file'))
Continue the code snippet: <|code_start|> class TestCommonRegExp(SimpleTestCase): def test_match_regexp(self): str_data = '10:45' <|code_end|> . Use current file imports: from django.test import SimpleTestCase from django_test_tools.re.regexp import CommonRegExp and context (classes, functions, or code) from other files: # Path: django_test_tools/re/regexp.py # class CommonRegExp(object): # """ # This class is a utility for commonly used regular expressions. # # .. code-block:: python # # str_data = '10:45' # common_regexp = CommonRegExp() # regular_expression, key = common_regexp.match_regexp(str_data) # self.assertEqual(regular_expression, '([0-1][0-9]|2[0-4]):([0-5][0-9])') # self.assertEqual(key, 'time_military') # # if the strict keyword is used the class will add ^ at the begining and a $ at the end if the already are not present. # # """ # # def __init__(self,**kwargs): # self.strict = kwargs.get('strict', False) # self.regular_expressions = dict() # self.regular_expressions['time_military'] = { # 'pattern': r'([0-1][0-9]|2[0-4]):([0-5][0-9])' # } # self.regular_expressions['integer'] = { # 'pattern': r'^(\d+)$' # } # self.regular_expressions['decimal'] = { # 'pattern': r'(\d+\.\d+)' # } # self.regular_expressions['url'] = { # 'pattern': r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+' # } # if kwargs.get('reg_exps'): # self.regular_expressions.update(kwargs.get('reg_exps')) # # self.regular_expressions_compiled = dict() # for key, reg_exp in self.regular_expressions.items(): # #self.regular_expressions_compiled[key] = re.compile(reg_exp['pattern']) # self.regular_expressions_compiled[key] = self._compile_regular_expression(self.regular_expressions[key]) # # def match_regexp(self, value): # for key, regexp in self.regular_expressions_compiled.items(): # match = regexp.match(value) # if match: # return regexp.pattern, key # # return None, None # # def add_regular_expression(self, name, pattern, **kwargs): # regexp_dict = dict() # regexp_dict['pattern'] = pattern # if kwargs.get('strict') is not None: # regexp_dict['strict'] = kwargs.get('strict') # self.regular_expressions_compiled[name] = self._compile_regular_expression(regexp_dict) # # def _compile_regular_expression(self, regexp_dict): # if (self.strict or regexp_dict.get('strict')) and not regexp_dict['pattern'].startswith('^'): # regexp_dict['pattern'] = '^{}'.format(regexp_dict['pattern']) # # if (self.strict or regexp_dict.get('strict')) and not regexp_dict['pattern'].endswith('$'): # regexp_dict['pattern'] = '{}$'.format(regexp_dict['pattern']) # return re.compile(regexp_dict['pattern']) . Output only the next line.
common_regexp = CommonRegExp()
Given the code snippet: <|code_start|> writer = AssertionWriter(**kwargs) return writer.write_assert_list(dictionary_list, variable_name, filename=kwargs.get('filename')) @deprecated('Use assert_utils.write_assertions instead') def write_assert_list(filename, dictionary_list, variable_name): """ Function to generate assertions for a dictionary or list content. :param filename: :param dictionary_list: :param variable_name: :return: """ writer = AssertionWriter() return writer.write_assert_list(dictionary_list, variable_name, filename=filename) class AssertionWriter(object): """ This class generates assertions using Django practice of putting actual value first and then expected value. """ def __init__(self, **kwargs): self.excluded_variable_names = ['created', 'modified'] if kwargs.get('excluded_keys') is not None: for key in kwargs.get('excluded_keys'): self.excluded_variable_names.append(key) self.use_regexp_assertion = kwargs.get('use_regexp_assertion', False) if self.use_regexp_assertion: <|code_end|> , generate the next line using the imports in this file: import collections from datetime import datetime, date from decimal import Decimal from openpyxl.compat import deprecated from .re.regexp import CommonRegExp from .utils import create_output_filename_with_date and context (functions, classes, or occasionally code) from other files: # Path: django_test_tools/re/regexp.py # class CommonRegExp(object): # """ # This class is a utility for commonly used regular expressions. # # .. code-block:: python # # str_data = '10:45' # common_regexp = CommonRegExp() # regular_expression, key = common_regexp.match_regexp(str_data) # self.assertEqual(regular_expression, '([0-1][0-9]|2[0-4]):([0-5][0-9])') # self.assertEqual(key, 'time_military') # # if the strict keyword is used the class will add ^ at the begining and a $ at the end if the already are not present. # # """ # # def __init__(self,**kwargs): # self.strict = kwargs.get('strict', False) # self.regular_expressions = dict() # self.regular_expressions['time_military'] = { # 'pattern': r'([0-1][0-9]|2[0-4]):([0-5][0-9])' # } # self.regular_expressions['integer'] = { # 'pattern': r'^(\d+)$' # } # self.regular_expressions['decimal'] = { # 'pattern': r'(\d+\.\d+)' # } # self.regular_expressions['url'] = { # 'pattern': r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+' # } # if kwargs.get('reg_exps'): # self.regular_expressions.update(kwargs.get('reg_exps')) # # self.regular_expressions_compiled = dict() # for key, reg_exp in self.regular_expressions.items(): # #self.regular_expressions_compiled[key] = re.compile(reg_exp['pattern']) # self.regular_expressions_compiled[key] = self._compile_regular_expression(self.regular_expressions[key]) # # def match_regexp(self, value): # for key, regexp in self.regular_expressions_compiled.items(): # match = regexp.match(value) # if match: # return regexp.pattern, key # # return None, None # # def add_regular_expression(self, name, pattern, **kwargs): # regexp_dict = dict() # regexp_dict['pattern'] = pattern # if kwargs.get('strict') is not None: # regexp_dict['strict'] = kwargs.get('strict') # self.regular_expressions_compiled[name] = self._compile_regular_expression(regexp_dict) # # def _compile_regular_expression(self, regexp_dict): # if (self.strict or regexp_dict.get('strict')) and not regexp_dict['pattern'].startswith('^'): # regexp_dict['pattern'] = '^{}'.format(regexp_dict['pattern']) # # if (self.strict or regexp_dict.get('strict')) and not regexp_dict['pattern'].endswith('$'): # regexp_dict['pattern'] = '{}$'.format(regexp_dict['pattern']) # return re.compile(regexp_dict['pattern']) # # Path: django_test_tools/utils.py # @deprecated('Should use django_test_tools.file_utils.create_dated() function') # def create_output_filename_with_date(filename): # """ # Based on the filename will create a full path filename incluidn the date and time in '%Y%m%d_%H%M' format. # The path to the filename will be set in the TEST_OUTPUT_PATH settings variable. # # :param filename: base filename. my_excel_data.xlsx for example # :return: string, full path to file with date and time in the TEST_OUTPUT_PATH folder # """ # if getattr(settings, 'TEST_OUTPUT_PATH', None) is None: # msg = 'You need a the variable TEST_OUTPUT_PATH in settings. It should point to a folder' \ # 'for temporary data to be written and reviewed.' # raise ValueError(msg) # if not os.path.exists(settings.TEST_OUTPUT_PATH): # os.makedirs(settings.TEST_OUTPUT_PATH) # return add_date(os.path.join(settings.TEST_OUTPUT_PATH, filename)) . Output only the next line.
self.common_regexp = CommonRegExp(strict=True)
Given the code snippet: <|code_start|> class AssertionWriter(object): """ This class generates assertions using Django practice of putting actual value first and then expected value. """ def __init__(self, **kwargs): self.excluded_variable_names = ['created', 'modified'] if kwargs.get('excluded_keys') is not None: for key in kwargs.get('excluded_keys'): self.excluded_variable_names.append(key) self.use_regexp_assertion = kwargs.get('use_regexp_assertion', False) if self.use_regexp_assertion: self.common_regexp = CommonRegExp(strict=True) self.check_for_type_only = kwargs.get('type_only', False) def add_regular_expression(self, name, pattern, **kwargs): self.common_regexp.add_regular_expression(name, pattern, **kwargs) def write_assert_list(self, dictionary_list, variable_name, **kwargs): """ Function to generate assertions for a dictionary or list content. :param kwargs: :param dictionary_list: :param variable_name: :return: """ if kwargs.get('filename') is None: <|code_end|> , generate the next line using the imports in this file: import collections from datetime import datetime, date from decimal import Decimal from openpyxl.compat import deprecated from .re.regexp import CommonRegExp from .utils import create_output_filename_with_date and context (functions, classes, or occasionally code) from other files: # Path: django_test_tools/re/regexp.py # class CommonRegExp(object): # """ # This class is a utility for commonly used regular expressions. # # .. code-block:: python # # str_data = '10:45' # common_regexp = CommonRegExp() # regular_expression, key = common_regexp.match_regexp(str_data) # self.assertEqual(regular_expression, '([0-1][0-9]|2[0-4]):([0-5][0-9])') # self.assertEqual(key, 'time_military') # # if the strict keyword is used the class will add ^ at the begining and a $ at the end if the already are not present. # # """ # # def __init__(self,**kwargs): # self.strict = kwargs.get('strict', False) # self.regular_expressions = dict() # self.regular_expressions['time_military'] = { # 'pattern': r'([0-1][0-9]|2[0-4]):([0-5][0-9])' # } # self.regular_expressions['integer'] = { # 'pattern': r'^(\d+)$' # } # self.regular_expressions['decimal'] = { # 'pattern': r'(\d+\.\d+)' # } # self.regular_expressions['url'] = { # 'pattern': r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+' # } # if kwargs.get('reg_exps'): # self.regular_expressions.update(kwargs.get('reg_exps')) # # self.regular_expressions_compiled = dict() # for key, reg_exp in self.regular_expressions.items(): # #self.regular_expressions_compiled[key] = re.compile(reg_exp['pattern']) # self.regular_expressions_compiled[key] = self._compile_regular_expression(self.regular_expressions[key]) # # def match_regexp(self, value): # for key, regexp in self.regular_expressions_compiled.items(): # match = regexp.match(value) # if match: # return regexp.pattern, key # # return None, None # # def add_regular_expression(self, name, pattern, **kwargs): # regexp_dict = dict() # regexp_dict['pattern'] = pattern # if kwargs.get('strict') is not None: # regexp_dict['strict'] = kwargs.get('strict') # self.regular_expressions_compiled[name] = self._compile_regular_expression(regexp_dict) # # def _compile_regular_expression(self, regexp_dict): # if (self.strict or regexp_dict.get('strict')) and not regexp_dict['pattern'].startswith('^'): # regexp_dict['pattern'] = '^{}'.format(regexp_dict['pattern']) # # if (self.strict or regexp_dict.get('strict')) and not regexp_dict['pattern'].endswith('$'): # regexp_dict['pattern'] = '{}$'.format(regexp_dict['pattern']) # return re.compile(regexp_dict['pattern']) # # Path: django_test_tools/utils.py # @deprecated('Should use django_test_tools.file_utils.create_dated() function') # def create_output_filename_with_date(filename): # """ # Based on the filename will create a full path filename incluidn the date and time in '%Y%m%d_%H%M' format. # The path to the filename will be set in the TEST_OUTPUT_PATH settings variable. # # :param filename: base filename. my_excel_data.xlsx for example # :return: string, full path to file with date and time in the TEST_OUTPUT_PATH folder # """ # if getattr(settings, 'TEST_OUTPUT_PATH', None) is None: # msg = 'You need a the variable TEST_OUTPUT_PATH in settings. It should point to a folder' \ # 'for temporary data to be written and reviewed.' # raise ValueError(msg) # if not os.path.exists(settings.TEST_OUTPUT_PATH): # os.makedirs(settings.TEST_OUTPUT_PATH) # return add_date(os.path.join(settings.TEST_OUTPUT_PATH, filename)) . Output only the next line.
filename = create_output_filename_with_date('{}.py'.format(variable_name))
Continue the code snippet: <|code_start|> \"\"\" {1} = {0}Factory.create() """ PRINT_TEST_ATTRIBUTE_UNIQUE = """ def test_{2}_is_unique(self): \"\"\" Tests attribute {2} of model {0} to see if the unique constraint works. This test should break if the unique attribute is changed. \"\"\" {1} = {0}Factory.create() {1}_02 = {0}Factory.create() {1}_02.{2} = {1}.{2} try: {1}_02.save() self.fail('Test should have raised and integrity error') except IntegrityError as e: self.assertEqual(str(e), '') #FIXME This test is incomplete """ # noinspection PyProtectedMember,PyProtectedMember class ModelTestCaseGenerator(object): def __init__(self, model): self.model = model def _generate(self): model_test_case_content = list() model_test_case_content.append({'print': PRINT_TEST_CLASS, 'args': [self.model.__name__, <|code_end|> . Use current file imports: from ..utils import convert_to_snake_case and context (classes, functions, or code) from other files: # Path: django_test_tools/utils.py # def convert_to_snake_case(camel_case): # """ # Converts a CamelCase name to snake case. # ..code-block:: python # # camel_case = 'OperatingSystemLongName' # snake_case = convert_to_snake_case(camel_case) # self.assertEqual(snake_case, 'operating_system_long_name') # # :param camel_case: string. Camel case name # :return: string. Snake case name # """ # s1 = first_cap_re.sub(r'\1_\2', camel_case) # return all_cap_re.sub(r'\1_\2', s1).lower() . Output only the next line.
convert_to_snake_case(self.model.__name__)]})
Based on the snippet: <|code_start|> # help="List data", # ) parser.add_argument("--format", dest="format", help="Git format", default=None, ) parser.add_argument('-f', "--filename", dest="filename", help="Output filename", default=None, ) # parser.add_argument("-u", "--username", # dest="usernames", # help="LDAP usernames for employees", # nargs='+', # ) def handle(self, *args, **options): headers = ['Hash', 'Email', 'Date', 'Description'] if options.get('format') is None: git_format = '%h|%ae|%ai|%s' else: git_format = options.get('format') if options.get('filename') is None: filepath = os.path.join(settings.TEST_OUTPUT_PATH, 'git_report.xlsx') <|code_end|> , predict the immediate next line with the help of imports: import pytz import os import subprocess import logging from datetime import datetime from django.conf import settings from django.core.management import BaseCommand from openpyxl import Workbook from ...file_utils import add_date from ...utils import datetime_to_local_time and context (classes, functions, sometimes code) from other files: # Path: django_test_tools/file_utils.py # def add_date(filename, **kwargs): # """ # Adds to a filename the current date and time in '%Y%m%d_%H%M' format. # For a filename /my/path/myexcel.xlsx the function would return /my/path/myexcel_20170101_1305.xlsx. # If the file already exists the function will add seconds to the date to attempt to get a unique name. # # The function will detect if another file exists with the same name if it exist it will append seconds to the # filename. For example if file /my/path/myexcel_20170101_1305.xlsx alread exist thte function will return # /my/path/myexcel_20170101_130521.xlsx. # # :param filename: string with fullpath to file or just the filename # :param kwargs: dictionary. date_position: suffix or preffix, extension: string to replace extension # :return: string with full path string including the date and time # """ # current_datetime = timezone.localtime(timezone.now()).strftime('%Y%m%d_%H%M%S') # new_filename_data = dict() # suffix_template = '{path}{separator}{filename_with_out_extension}_{datetime}.{extension}' # prefix_template = '{path}{separator}{datetime}_{filename_with_out_extension}.{extension}' # if '/' in filename and '\\' in filename: # raise ValueError('Filename %s contains both / and \\ separators' % filename) # if '\\' in filename: # path_parts = filename.split('\\') # file = path_parts[-1] # path = '\\'.join(path_parts[:-1]) # separator = '\\' # elif '/' in filename: # path_parts = filename.split('/') # file = path_parts[-1] # path = '/'.join(path_parts[:-1]) # separator = '/' # else: # file = filename # path = '' # separator = '' # # new_filename_data['path'] = path # parts = file.split('.') # if kwargs.get('extension', None) is not None: # new_filename_data['extension'] = kwargs['extension'] # else: # if len(parts) > 1: # new_filename_data['extension'] = parts[-1] # else: # new_filename_data['extension'] = '' # # new_filename_data['separator'] = separator # if new_filename_data['extension'] == '': # new_filename_data['filename_with_out_extension'] = parts[0] # else: # new_filename_data['filename_with_out_extension'] = '.'.join(parts[:-1]) # new_filename_data['datetime'] = current_datetime[:-2] # Seconds are stripped # # date_position = kwargs.get('date_position', 'suffix') # if date_position == 'suffix': # new_filename = suffix_template.format(**new_filename_data) # if os.path.exists(new_filename): # new_filename_data['datetime'] = current_datetime # new_filename = suffix_template.format(**new_filename_data) # if new_filename_data['extension'] == '': # new_filename = new_filename[:-1] # else: # new_filename = prefix_template.format(**new_filename_data) # if os.path.exists(new_filename): # new_filename_data['datetime'] = current_datetime # new_filename = prefix_template.format(**new_filename_data) # if new_filename_data['extension'] == '': # new_filename = new_filename[:-1] # # return new_filename # # Path: django_test_tools/utils.py # def datetime_to_local_time(date_time): # """ # Converts a naive date to a time zoned date based in hte setting.TIME_ZONE variable. If the date has already a time zone # it will localize the date. # :param date_time: <date> or <datetime> to be localized # :return: localized non naive datetime # """ # if isinstance(date_time, date) and not isinstance(date_time, datetime): # date_time = datetime.combine(date_time, datetime.min.time()) # # is_naive = date_time.tzinfo is None or date_time.tzinfo.utcoffset(date_time) is None # time_zone = pytz.timezone(settings.TIME_ZONE) # if is_naive: # return time_zone.localize(date_time) # else: # return date_time.astimezone(time_zone) . Output only the next line.
filename = add_date(filepath)