Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*- """ Copyright (C) 2017 IBM Corporation Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Contributors: * Roberto Oliveira <rdutra@br.ibm.com> """ <|code_end|> with the help of current file imports: import ma.checkers.checker_file_utils as utils from ma.checkers.checker import Checker from ma.xml_loader.builtins_loader import BuiltinLoader and context from other files: # Path: ma/checkers/checker.py # class Checker(object): # """ Abstract class Checker """ # __metaclass__ = abc.ABCMeta # # def check_node(self, node): # """ Check node from AST and return if it is a migration issue """ # return False # # def check_include(self, include_name): # """ Check include from AST and return if it is a migration issue """ # return False # # def check_file(self, file_name): # """ Check issues into file and return a list of lists, containing the # problem name and line number """ # return [] # # def get_solution(self, problem): # """ Get solution for the problem using the node from AST or the raw # node from file """ # return "" # # @abc.abstractmethod # def get_pattern_hint(self): # """Return the pattern that should be used to get the # problematics files""" # raise NotImplementedError('users must define __get_pattern_hint__ to\ # use this base class') # # @abc.abstractmethod # def get_problem_msg(self): # """Return the problem message of the checker""" # raise NotImplementedError('users must define __get_problem_msg__ to \ # use this base class') # # @abc.abstractmethod # def get_problem_type(self): # """Return the problem type of the checker""" # raise NotImplementedError('users must define __get_problem_type__ to \ # use this base class') # # Path: ma/xml_loader/builtins_loader.py # class BuiltinLoader(object): # """ Class to load builtins from xml file """ # # def __init__(self): # self.builtins = [] # self.__load_builtins(BUILTINS_FILE) # self._builtins_names = [] # self.__load_builtins_names() # self._builtins_headers = [] # self.__load_builtins_headers() # # @property # def builtins_names(self): # """ Builtins names (functions and data types) """ # return self._builtins_names # # @property # def builtins_headers(self): # """ Builtins headers """ # return self._builtins_headers # # def is_builtin(self, name): # """ Check if the given name is a builtin """ # if name in self.builtins: # return True # # def __load_builtins_names(self): # """ Load builtins name (do not include headers) """ # for builtin in self.builtins: # if isinstance(builtin, Type) or isinstance(builtin, Function): # self._builtins_names.append(builtin.name) # # def __load_builtins_headers(self): # """ Load builtins headers """ # for builtin in self.builtins: # if isinstance(builtin, Include): # self._builtins_headers.append(builtin.name) # # def __load_builtins(self, file_name): # """ Load all builtins elements """ # tree = elemTree.parse(file_name) # root = tree.getroot() # self.__load_includes(root) # self.__load_types(root) # self.__load_functions(root) # # def __load_includes(self, root): # """ Load includes elements """ # for incl in root.iter('include'): # name = incl.attrib['name'] # replacer = incl.text # include = Include(name, replacer) # self.builtins.append(include) # # def __load_types(self, root): # """ Load types elements """ # for dtype in root.iter('type'): # name = dtype.attrib['name'] # replacer = dtype.text # data_type = Type(name, replacer) # self.builtins.append(data_type) # # def __load_functions(self, root): # """ Load functions elements """ # for func in root.iter('function'): # name = func.attrib['name'] # try: # finput = func.find(".//in").text # except AttributeError: # finput = "" # try: # foutput = func.find(".//out").text # except AttributeError: # foutput = "" # # code_list = [] # for cfunc in func.iter('code'): # endian = cfunc.attrib['endian'] # nlines = cfunc.attrib['nlines'] # replacer = cfunc.text # code = Function.Code(endian, nlines, replacer) # code_list.append(code) # function = Function(name, finput, foutput, code_list) # self.builtins.append(function) , which may contain function names, class names, or code. Output only the next line.
class BuiltinChecker(Checker):
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- """ Copyright (C) 2017 IBM Corporation Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Contributors: * Roberto Oliveira <rdutra@br.ibm.com> """ class BuiltinChecker(Checker): """ Checker for x86-specific built-ins """ def __init__(self): self.problem_type = "x86-specific compiler built-in" self.problem_msg = "x86 built-ins not supported in Power" <|code_end|> , generate the next line using the imports in this file: import ma.checkers.checker_file_utils as utils from ma.checkers.checker import Checker from ma.xml_loader.builtins_loader import BuiltinLoader and context (functions, classes, or occasionally code) from other files: # Path: ma/checkers/checker.py # class Checker(object): # """ Abstract class Checker """ # __metaclass__ = abc.ABCMeta # # def check_node(self, node): # """ Check node from AST and return if it is a migration issue """ # return False # # def check_include(self, include_name): # """ Check include from AST and return if it is a migration issue """ # return False # # def check_file(self, file_name): # """ Check issues into file and return a list of lists, containing the # problem name and line number """ # return [] # # def get_solution(self, problem): # """ Get solution for the problem using the node from AST or the raw # node from file """ # return "" # # @abc.abstractmethod # def get_pattern_hint(self): # """Return the pattern that should be used to get the # problematics files""" # raise NotImplementedError('users must define __get_pattern_hint__ to\ # use this base class') # # @abc.abstractmethod # def get_problem_msg(self): # """Return the problem message of the checker""" # raise NotImplementedError('users must define __get_problem_msg__ to \ # use this base class') # # @abc.abstractmethod # def get_problem_type(self): # """Return the problem type of the checker""" # raise NotImplementedError('users must define __get_problem_type__ to \ # use this base class') # # Path: ma/xml_loader/builtins_loader.py # class BuiltinLoader(object): # """ Class to load builtins from xml file """ # # def __init__(self): # self.builtins = [] # self.__load_builtins(BUILTINS_FILE) # self._builtins_names = [] # self.__load_builtins_names() # self._builtins_headers = [] # self.__load_builtins_headers() # # @property # def builtins_names(self): # """ Builtins names (functions and data types) """ # return self._builtins_names # # @property # def builtins_headers(self): # """ Builtins headers """ # return self._builtins_headers # # def is_builtin(self, name): # """ Check if the given name is a builtin """ # if name in self.builtins: # return True # # def __load_builtins_names(self): # """ Load builtins name (do not include headers) """ # for builtin in self.builtins: # if isinstance(builtin, Type) or isinstance(builtin, Function): # self._builtins_names.append(builtin.name) # # def __load_builtins_headers(self): # """ Load builtins headers """ # for builtin in self.builtins: # if isinstance(builtin, Include): # self._builtins_headers.append(builtin.name) # # def __load_builtins(self, file_name): # """ Load all builtins elements """ # tree = elemTree.parse(file_name) # root = tree.getroot() # self.__load_includes(root) # self.__load_types(root) # self.__load_functions(root) # # def __load_includes(self, root): # """ Load includes elements """ # for incl in root.iter('include'): # name = incl.attrib['name'] # replacer = incl.text # include = Include(name, replacer) # self.builtins.append(include) # # def __load_types(self, root): # """ Load types elements """ # for dtype in root.iter('type'): # name = dtype.attrib['name'] # replacer = dtype.text # data_type = Type(name, replacer) # self.builtins.append(data_type) # # def __load_functions(self, root): # """ Load functions elements """ # for func in root.iter('function'): # name = func.attrib['name'] # try: # finput = func.find(".//in").text # except AttributeError: # finput = "" # try: # foutput = func.find(".//out").text # except AttributeError: # foutput = "" # # code_list = [] # for cfunc in func.iter('code'): # endian = cfunc.attrib['endian'] # nlines = cfunc.attrib['nlines'] # replacer = cfunc.text # code = Function.Code(endian, nlines, replacer) # code_list.append(code) # function = Function(name, finput, foutput, code_list) # self.builtins.append(function) . Output only the next line.
self.loader = BuiltinLoader()
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*- """ Copyright (C) 2017 IBM Corporation Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Contributors: * Roberto Oliveira <rdutra@br.ibm.com> * Rafael Peria de Sene <rpsene@br.ibm.com> """ class CheckersBase(object): """ Base class to use checkers test """ def __init__(self): <|code_end|> using the current file's imports: from ma.problem_reporter import ProblemReporter from ma import controller and any relevant context from other files: # Path: ma/problem_reporter.py # class ProblemReporter(object): # """ Class to handle with reported problems """ # problems = {} # # @classmethod # def report_include(cls, name, file_name, line, problem_type, problem_msg, # solution): # """ Report a problem in an include directive """ # if not cls.__should_report(file_name, line, file_name): # return # name = "include " + name # problem = Problem(name, file_name, line, problem_msg, solution) # cls.__report_problem(problem, problem_type) # # @classmethod # def report_node(cls, node, current_file, problem_type, problem_msg, # solution): # """ Report a problem in a node """ # node_loc = node.location # node_file = node_loc.file # node_line = node_loc.line # if not cls.__should_report(node_file, node_line, current_file): # return # # name = core.get_raw_node(node) # problem = Problem(name, node_file, node_line, problem_msg, solution) # cls.__report_problem(problem, problem_type) # # @classmethod # def report_file(cls, file_name, num_line, name, problem_type, problem_msg, # solution): # """ Report a problem in a file """ # if not cls.__should_report(file_name, num_line, file_name): # return # problem = Problem(name, file_name, num_line, problem_msg, solution) # cls.__report_problem(problem, problem_type) # # @classmethod # def __report_problem(cls, problem, problem_type): # """ Add the reported problem in a dictionary """ # if cls.problems.get(problem_type, None) is not None: # cls.problems.get(problem_type).append(problem) # else: # problem_list = [] # problem_list.append(problem) # cls.problems[problem_type] = problem_list # # @classmethod # def print_problems(cls): # """ Print all reported problems """ # if not cls.problems: # print("\nNo migration reports found.") # return # # tab = " " # cls.__print_logo() # for problem_type, problems in cls.problems.items(): # problems_dict = {} # # Group problems by file # for problem in problems: # name = problem.file_name # problems_dict[name] = problems_dict.get(name, []) + [problem] # # print("Problem type: " + problem_type) # print("Problem description: " + problems[0].problem_msg) # for file_name, problems in problems_dict.items(): # print(tab + "File: " + file_name) # for problem in problems: # print((tab * 2) + "Line: " + str(problem.line)) # print((tab * 2) + "Problem: " + str(problem.name)) # if problem.solution: # print((tab * 2) + "Solution: " + problem.solution) # print("") # print("") # # @classmethod # def get_problems(cls): # """ Get all reported problems """ # return cls.problems # # @classmethod # def clear_problems(cls): # """ Clear reported problems """ # cls.problems.clear() # # @classmethod # def __should_report(cls, node_file, node_line, current_file): # """ Check if should report the node """ # # Location is not known # if not node_file: # return False # # Node is not in the current file # if str(node_file) != current_file: # return False # # Node is inside a blocked line # if node_line in ReportBlocker.blocked_lines: # return False # return True # # @classmethod # def __print_logo(cls): # """ Print the report logo """ # title = "Migration Report" # border = "=" * len(title) # print("") # print(border) # print(title) # print(border) # # Path: ma/controller.py # def run(argv): # def _include_paths(): # def _run_checker(checker, argv): # def _load_checkers(checkers): # def __current_wip(checker, files): . Output only the next line.
self.reporter = ProblemReporter()
Based on the snippet: <|code_start|> Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Contributors: * Roberto Oliveira <rdutra@br.ibm.com> * Rafael Peria de Sene <rpsene@br.ibm.com> """ class CheckersBase(object): """ Base class to use checkers test """ def __init__(self): self.reporter = ProblemReporter() def run(self, checker, path): """ Run MA checker. The checker is the one that will be activated and the path is the folder with the files used in the test """ self.reporter.clear_problems() <|code_end|> , predict the immediate next line with the help of imports: from ma.problem_reporter import ProblemReporter from ma import controller and context (classes, functions, sometimes code) from other files: # Path: ma/problem_reporter.py # class ProblemReporter(object): # """ Class to handle with reported problems """ # problems = {} # # @classmethod # def report_include(cls, name, file_name, line, problem_type, problem_msg, # solution): # """ Report a problem in an include directive """ # if not cls.__should_report(file_name, line, file_name): # return # name = "include " + name # problem = Problem(name, file_name, line, problem_msg, solution) # cls.__report_problem(problem, problem_type) # # @classmethod # def report_node(cls, node, current_file, problem_type, problem_msg, # solution): # """ Report a problem in a node """ # node_loc = node.location # node_file = node_loc.file # node_line = node_loc.line # if not cls.__should_report(node_file, node_line, current_file): # return # # name = core.get_raw_node(node) # problem = Problem(name, node_file, node_line, problem_msg, solution) # cls.__report_problem(problem, problem_type) # # @classmethod # def report_file(cls, file_name, num_line, name, problem_type, problem_msg, # solution): # """ Report a problem in a file """ # if not cls.__should_report(file_name, num_line, file_name): # return # problem = Problem(name, file_name, num_line, problem_msg, solution) # cls.__report_problem(problem, problem_type) # # @classmethod # def __report_problem(cls, problem, problem_type): # """ Add the reported problem in a dictionary """ # if cls.problems.get(problem_type, None) is not None: # cls.problems.get(problem_type).append(problem) # else: # problem_list = [] # problem_list.append(problem) # cls.problems[problem_type] = problem_list # # @classmethod # def print_problems(cls): # """ Print all reported problems """ # if not cls.problems: # print("\nNo migration reports found.") # return # # tab = " " # cls.__print_logo() # for problem_type, problems in cls.problems.items(): # problems_dict = {} # # Group problems by file # for problem in problems: # name = problem.file_name # problems_dict[name] = problems_dict.get(name, []) + [problem] # # print("Problem type: " + problem_type) # print("Problem description: " + problems[0].problem_msg) # for file_name, problems in problems_dict.items(): # print(tab + "File: " + file_name) # for problem in problems: # print((tab * 2) + "Line: " + str(problem.line)) # print((tab * 2) + "Problem: " + str(problem.name)) # if problem.solution: # print((tab * 2) + "Solution: " + problem.solution) # print("") # print("") # # @classmethod # def get_problems(cls): # """ Get all reported problems """ # return cls.problems # # @classmethod # def clear_problems(cls): # """ Clear reported problems """ # cls.problems.clear() # # @classmethod # def __should_report(cls, node_file, node_line, current_file): # """ Check if should report the node """ # # Location is not known # if not node_file: # return False # # Node is not in the current file # if str(node_file) != current_file: # return False # # Node is inside a blocked line # if node_line in ReportBlocker.blocked_lines: # return False # return True # # @classmethod # def __print_logo(cls): # """ Print the report logo """ # title = "Migration Report" # border = "=" * len(title) # print("") # print(border) # print(title) # print(border) # # Path: ma/controller.py # def run(argv): # def _include_paths(): # def _run_checker(checker, argv): # def _load_checkers(checkers): # def __current_wip(checker, files): . Output only the next line.
controller._run_checker(checker, False, path)
Next line prediction: <|code_start|># -*- coding: utf-8 -*- """ Copyright (C) 2017 IBM Corporation Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Contributors: * Diego Fernandez-Merjildo <merjildo@br.ibm.com> """ <|code_end|> . Use current file imports: (import ma.checkers.checker_file_utils as utils from ma.checkers.checker import Checker) and context including class names, function names, or small code snippets from other files: # Path: ma/checkers/checker.py # class Checker(object): # """ Abstract class Checker """ # __metaclass__ = abc.ABCMeta # # def check_node(self, node): # """ Check node from AST and return if it is a migration issue """ # return False # # def check_include(self, include_name): # """ Check include from AST and return if it is a migration issue """ # return False # # def check_file(self, file_name): # """ Check issues into file and return a list of lists, containing the # problem name and line number """ # return [] # # def get_solution(self, problem): # """ Get solution for the problem using the node from AST or the raw # node from file """ # return "" # # @abc.abstractmethod # def get_pattern_hint(self): # """Return the pattern that should be used to get the # problematics files""" # raise NotImplementedError('users must define __get_pattern_hint__ to\ # use this base class') # # @abc.abstractmethod # def get_problem_msg(self): # """Return the problem message of the checker""" # raise NotImplementedError('users must define __get_problem_msg__ to \ # use this base class') # # @abc.abstractmethod # def get_problem_type(self): # """Return the problem type of the checker""" # raise NotImplementedError('users must define __get_problem_type__ to \ # use this base class') . Output only the next line.
class ApiMpiChecker(Checker):
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- """ Copyright (C) 2017 IBM Corporation Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Contributors: * Daniel Kreling <dbkreling@br.ibm.com> """ <|code_end|> . Write the next line using the current file imports: import ma.checkers.checker_file_utils as utils from ma.checkers.checker import Checker and context from other files: # Path: ma/checkers/checker.py # class Checker(object): # """ Abstract class Checker """ # __metaclass__ = abc.ABCMeta # # def check_node(self, node): # """ Check node from AST and return if it is a migration issue """ # return False # # def check_include(self, include_name): # """ Check include from AST and return if it is a migration issue """ # return False # # def check_file(self, file_name): # """ Check issues into file and return a list of lists, containing the # problem name and line number """ # return [] # # def get_solution(self, problem): # """ Get solution for the problem using the node from AST or the raw # node from file """ # return "" # # @abc.abstractmethod # def get_pattern_hint(self): # """Return the pattern that should be used to get the # problematics files""" # raise NotImplementedError('users must define __get_pattern_hint__ to\ # use this base class') # # @abc.abstractmethod # def get_problem_msg(self): # """Return the problem message of the checker""" # raise NotImplementedError('users must define __get_problem_msg__ to \ # use this base class') # # @abc.abstractmethod # def get_problem_type(self): # """Return the problem type of the checker""" # raise NotImplementedError('users must define __get_problem_type__ to \ # use this base class') , which may include functions, classes, or code. Output only the next line.
class ApiDfpChecker(Checker):
Using the snippet: <|code_start|># -*- coding: utf-8 -*- """ Copyright (C) 2017 IBM Corporation Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Contributors: * Diego Fernandez-Merjildo <merjildo@br.ibm.com> """ <|code_end|> , determine the next line of code. You have imports: import re from ma.checkers.checker import Checker from ma import core and context (class names, function names, or code) available: # Path: ma/checkers/checker.py # class Checker(object): # """ Abstract class Checker """ # __metaclass__ = abc.ABCMeta # # def check_node(self, node): # """ Check node from AST and return if it is a migration issue """ # return False # # def check_include(self, include_name): # """ Check include from AST and return if it is a migration issue """ # return False # # def check_file(self, file_name): # """ Check issues into file and return a list of lists, containing the # problem name and line number """ # return [] # # def get_solution(self, problem): # """ Get solution for the problem using the node from AST or the raw # node from file """ # return "" # # @abc.abstractmethod # def get_pattern_hint(self): # """Return the pattern that should be used to get the # problematics files""" # raise NotImplementedError('users must define __get_pattern_hint__ to\ # use this base class') # # @abc.abstractmethod # def get_problem_msg(self): # """Return the problem message of the checker""" # raise NotImplementedError('users must define __get_problem_msg__ to \ # use this base class') # # @abc.abstractmethod # def get_problem_type(self): # """Return the problem type of the checker""" # raise NotImplementedError('users must define __get_problem_type__ to \ # use this base class') # # Path: ma/core.py # X86_PATTERNS = ["amd64", "AMD64", "[xX]86", "[xX]86_64", "[iI]386", "[iI]486", # "[iI]686"] # PPC_PATTERNS = ["PPC", "ppc", "power[pP][cC]", "POWER[pP][cC]"] # def get_supported_checkers(): # def get_supported_extensions(): # def execute(command): # def execute_stdout(command): # def cmdexists(command): # def get_timestamp(): # def get_files(location, hint=''): # def get_file_content(file_name, offset, length): # def get_raw_node(node): # def get_includes(file_path): # def get_ifdefs(file_path): # def get_ifdef_regex(arch, separator): . Output only the next line.
class PerformanceDegradationChecker(Checker):
Given the code snippet: <|code_start|> """ Copyright (C) 2017 IBM Corporation Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Contributors: * Diego Fernandez-Merjildo <merjildo@br.ibm.com> """ class PerformanceDegradationChecker(Checker): """ This checker finds preprocessor ifs with architecture optimizations and without an optimization for Linux on Power""" def __init__(self): super(PerformanceDegradationChecker, self).__init__() self.problem_type = "Performance degradation" self.problem_msg = "This preprocessor can contain code without Power optimization" <|code_end|> , generate the next line using the imports in this file: import re from ma.checkers.checker import Checker from ma import core and context (functions, classes, or occasionally code) from other files: # Path: ma/checkers/checker.py # class Checker(object): # """ Abstract class Checker """ # __metaclass__ = abc.ABCMeta # # def check_node(self, node): # """ Check node from AST and return if it is a migration issue """ # return False # # def check_include(self, include_name): # """ Check include from AST and return if it is a migration issue """ # return False # # def check_file(self, file_name): # """ Check issues into file and return a list of lists, containing the # problem name and line number """ # return [] # # def get_solution(self, problem): # """ Get solution for the problem using the node from AST or the raw # node from file """ # return "" # # @abc.abstractmethod # def get_pattern_hint(self): # """Return the pattern that should be used to get the # problematics files""" # raise NotImplementedError('users must define __get_pattern_hint__ to\ # use this base class') # # @abc.abstractmethod # def get_problem_msg(self): # """Return the problem message of the checker""" # raise NotImplementedError('users must define __get_problem_msg__ to \ # use this base class') # # @abc.abstractmethod # def get_problem_type(self): # """Return the problem type of the checker""" # raise NotImplementedError('users must define __get_problem_type__ to \ # use this base class') # # Path: ma/core.py # X86_PATTERNS = ["amd64", "AMD64", "[xX]86", "[xX]86_64", "[iI]386", "[iI]486", # "[iI]686"] # PPC_PATTERNS = ["PPC", "ppc", "power[pP][cC]", "POWER[pP][cC]"] # def get_supported_checkers(): # def get_supported_extensions(): # def execute(command): # def execute_stdout(command): # def cmdexists(command): # def get_timestamp(): # def get_files(location, hint=''): # def get_file_content(file_name, offset, length): # def get_raw_node(node): # def get_includes(file_path): # def get_ifdefs(file_path): # def get_ifdef_regex(arch, separator): . Output only the next line.
self.hint = core.get_ifdef_regex("x86", "\\|")
Next line prediction: <|code_start|># -*- coding: utf-8 -*- """ Copyright (C) 2017 IBM Corporation Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Contributors: * Daniel Kreling <dbkreling@br.ibm.com> """ <|code_end|> . Use current file imports: (from clang.cindex import CursorKind from ma.checkers.checker import Checker from ma.xml_loader.htm_loader import HtmLoader) and context including class names, function names, or small code snippets from other files: # Path: ma/checkers/checker.py # class Checker(object): # """ Abstract class Checker """ # __metaclass__ = abc.ABCMeta # # def check_node(self, node): # """ Check node from AST and return if it is a migration issue """ # return False # # def check_include(self, include_name): # """ Check include from AST and return if it is a migration issue """ # return False # # def check_file(self, file_name): # """ Check issues into file and return a list of lists, containing the # problem name and line number """ # return [] # # def get_solution(self, problem): # """ Get solution for the problem using the node from AST or the raw # node from file """ # return "" # # @abc.abstractmethod # def get_pattern_hint(self): # """Return the pattern that should be used to get the # problematics files""" # raise NotImplementedError('users must define __get_pattern_hint__ to\ # use this base class') # # @abc.abstractmethod # def get_problem_msg(self): # """Return the problem message of the checker""" # raise NotImplementedError('users must define __get_problem_msg__ to \ # use this base class') # # @abc.abstractmethod # def get_problem_type(self): # """Return the problem type of the checker""" # raise NotImplementedError('users must define __get_problem_type__ to \ # use this base class') # # Path: ma/xml_loader/htm_loader.py # class HtmLoader(object): # """ Load htm.xml information into a Python element""" # # def __init__(self): # self.htms = [] # self.htms_include = [] # self.__load_xml(HTM_FILE) # # def __load_xml(self, file_name): # """Load the contents of htm.xml into a Python element""" # tree = elemTree.parse(file_name) # self.root = tree.getroot() # for htm in self.root.iter('function'): # self.htms.append(htm.attrib) # for htm_header in self.root.iter('header'): # self.htms_include.append(htm_header.attrib) # # def get_functions(self): # """Populate a list of HTM names""" # for htm in self.root.findall('htmapi'): # if htm.get("type") == "function": # self.htms.append(htm.get('target')) # return self.htms # # def get_includes(self): # """Populate a list of HTM includes in the header""" # for htm in self.root.findall('htmapi'): # if htm.get('type') == 'header': # self.htms_include.append(htm.get('target')) # return self.htms_include # # def get_fixes(self): # '''Method to populate a list of htm fixes''' # suggestion_dict = {} # for sysc in self.root.findall('htmapi'): # if sysc.get("replacer"): # suggestion_dict[sysc.get("target")] = (sysc.get("replacer")) # return suggestion_dict . Output only the next line.
class HtmChecker(Checker):
Using the snippet: <|code_start|># -*- coding: utf-8 -*- """ Copyright (C) 2017 IBM Corporation Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Contributors: * Daniel Kreling <dbkreling@br.ibm.com> """ class HtmChecker(Checker): """ Checker for HTM calls. """ def __init__(self): self.problem_type = "Hardware Transactional Memory (HTM)" self.problem_msg = "x86 specific HTM calls are not supported in Power Systems" <|code_end|> , determine the next line of code. You have imports: from clang.cindex import CursorKind from ma.checkers.checker import Checker from ma.xml_loader.htm_loader import HtmLoader and context (class names, function names, or code) available: # Path: ma/checkers/checker.py # class Checker(object): # """ Abstract class Checker """ # __metaclass__ = abc.ABCMeta # # def check_node(self, node): # """ Check node from AST and return if it is a migration issue """ # return False # # def check_include(self, include_name): # """ Check include from AST and return if it is a migration issue """ # return False # # def check_file(self, file_name): # """ Check issues into file and return a list of lists, containing the # problem name and line number """ # return [] # # def get_solution(self, problem): # """ Get solution for the problem using the node from AST or the raw # node from file """ # return "" # # @abc.abstractmethod # def get_pattern_hint(self): # """Return the pattern that should be used to get the # problematics files""" # raise NotImplementedError('users must define __get_pattern_hint__ to\ # use this base class') # # @abc.abstractmethod # def get_problem_msg(self): # """Return the problem message of the checker""" # raise NotImplementedError('users must define __get_problem_msg__ to \ # use this base class') # # @abc.abstractmethod # def get_problem_type(self): # """Return the problem type of the checker""" # raise NotImplementedError('users must define __get_problem_type__ to \ # use this base class') # # Path: ma/xml_loader/htm_loader.py # class HtmLoader(object): # """ Load htm.xml information into a Python element""" # # def __init__(self): # self.htms = [] # self.htms_include = [] # self.__load_xml(HTM_FILE) # # def __load_xml(self, file_name): # """Load the contents of htm.xml into a Python element""" # tree = elemTree.parse(file_name) # self.root = tree.getroot() # for htm in self.root.iter('function'): # self.htms.append(htm.attrib) # for htm_header in self.root.iter('header'): # self.htms_include.append(htm_header.attrib) # # def get_functions(self): # """Populate a list of HTM names""" # for htm in self.root.findall('htmapi'): # if htm.get("type") == "function": # self.htms.append(htm.get('target')) # return self.htms # # def get_includes(self): # """Populate a list of HTM includes in the header""" # for htm in self.root.findall('htmapi'): # if htm.get('type') == 'header': # self.htms_include.append(htm.get('target')) # return self.htms_include # # def get_fixes(self): # '''Method to populate a list of htm fixes''' # suggestion_dict = {} # for sysc in self.root.findall('htmapi'): # if sysc.get("replacer"): # suggestion_dict[sysc.get("target")] = (sysc.get("replacer")) # return suggestion_dict . Output only the next line.
self.htm_functions = HtmLoader().get_functions()
Based on the snippet: <|code_start|># -*- coding: utf-8 -*- """ Copyright (C) 2017 IBM Corporation Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Contributors: * Roberto Oliveira <rdutra@br.ibm.com> * Rafael Peria de Sene <rpsene@br.ibm.com> * Diego Fernandez-Merjildo <merjildo@br.ibm.com> """ <|code_end|> , predict the immediate next line with the help of imports: from clang.cindex import CursorKind from ma.checkers.checker import Checker and context (classes, functions, sometimes code) from other files: # Path: ma/checkers/checker.py # class Checker(object): # """ Abstract class Checker """ # __metaclass__ = abc.ABCMeta # # def check_node(self, node): # """ Check node from AST and return if it is a migration issue """ # return False # # def check_include(self, include_name): # """ Check include from AST and return if it is a migration issue """ # return False # # def check_file(self, file_name): # """ Check issues into file and return a list of lists, containing the # problem name and line number """ # return [] # # def get_solution(self, problem): # """ Get solution for the problem using the node from AST or the raw # node from file """ # return "" # # @abc.abstractmethod # def get_pattern_hint(self): # """Return the pattern that should be used to get the # problematics files""" # raise NotImplementedError('users must define __get_pattern_hint__ to\ # use this base class') # # @abc.abstractmethod # def get_problem_msg(self): # """Return the problem message of the checker""" # raise NotImplementedError('users must define __get_problem_msg__ to \ # use this base class') # # @abc.abstractmethod # def get_problem_type(self): # """Return the problem type of the checker""" # raise NotImplementedError('users must define __get_problem_type__ to \ # use this base class') . Output only the next line.
class AsmChecker(Checker):
Next line prediction: <|code_start|>#! /usr/bin/env python # -*- coding: utf-8 -*- """ Copyright (C) 2017 IBM Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Contributors: * Diego Fernandez-Merjildo <merjildo@br.ibm.com> """ class QuickfixLoaderTest(unittest.TestCase): """ Test cases for the quickfix loader""" @unittest.skip def get_include_test(self): """This test aim to check correct include value return from get_include() method in QuickfixLoader class""" <|code_end|> . Use current file imports: (import unittest from ma.xml_loader.quickfix_loader import QuickfixLoader) and context including class names, function names, or small code snippets from other files: # Path: ma/xml_loader/quickfix_loader.py # class QuickfixLoader(object): # """Class to load Quickfix Loader for MA. # This class get information stored in XML file # into a python module""" # def __init__(self): # self.items = {} # self.load_xml(QUICKFIX_XML) # # def load_xml(self, file_name): # '''Method to load Quickfixes strings. # This method open XML file and load info inside a # dictionary data structure''' # # tree = elemTree.parse(file_name) # root = tree.getroot() # orig_item = None # # for item in root.iter(): # if item.tag == 'item': # orig_item = item.attrib # # if item.tag == 'replacer': # replacer = item.attrib # self.items[orig_item['target']] = [orig_item, replacer] # # def get_include(self, target): # '''Method to get include value for selected target''' # replacer = self.items[target][1] # return replacer['include'] # # def get_type(self, target): # '''Method to get type value for selected target''' # replacer = self.items[target][1] # return replacer['type'] # # def get_value(self, target): # '''Method to get type value for selected target''' # replacer = self.items[target][1] # return replacer['value'] # # def get_define(self, target): # '''Method to get define value for selected target''' # replacer = self.items[target][1] # return replacer['define'] . Output only the next line.
quickfix_loader = QuickfixLoader()
Based on the snippet: <|code_start|> Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Contributors: * Roberto Oliveira <rdutra@br.ibm.com> * Diego Fernandez-Merjildo <merjildo@br.ibm.com> """ LINE_DELIMITER = "$" def _get_lines(names, file_name): """ Get all lines that contain names and return it as a list """ grep_delimiter = "\\|" command = "grep -n '" for name in names: command += name + grep_delimiter command = command[:-len(grep_delimiter)] command += "' " + file_name + " | cut -f1 -d:" <|code_end|> , predict the immediate next line with the help of imports: import re from ma import core and context (classes, functions, sometimes code) from other files: # Path: ma/core.py # X86_PATTERNS = ["amd64", "AMD64", "[xX]86", "[xX]86_64", "[iI]386", "[iI]486", # "[iI]686"] # PPC_PATTERNS = ["PPC", "ppc", "power[pP][cC]", "POWER[pP][cC]"] # def get_supported_checkers(): # def get_supported_extensions(): # def execute(command): # def execute_stdout(command): # def cmdexists(command): # def get_timestamp(): # def get_files(location, hint=''): # def get_file_content(file_name, offset, length): # def get_raw_node(node): # def get_includes(file_path): # def get_ifdefs(file_path): # def get_ifdef_regex(arch, separator): . Output only the next line.
lines = core.execute_stdout(command)[1]
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- """ Copyright (C) 2017 IBM Corporation Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Contributors: * Diego Fernandez-Merjildo <merjildo@br.ibm.com> """ <|code_end|> , generate the next line using the imports in this file: import ma.checkers.checker_file_utils as utils from ma.checkers.checker import Checker and context (functions, classes, or occasionally code) from other files: # Path: ma/checkers/checker.py # class Checker(object): # """ Abstract class Checker """ # __metaclass__ = abc.ABCMeta # # def check_node(self, node): # """ Check node from AST and return if it is a migration issue """ # return False # # def check_include(self, include_name): # """ Check include from AST and return if it is a migration issue """ # return False # # def check_file(self, file_name): # """ Check issues into file and return a list of lists, containing the # problem name and line number """ # return [] # # def get_solution(self, problem): # """ Get solution for the problem using the node from AST or the raw # node from file """ # return "" # # @abc.abstractmethod # def get_pattern_hint(self): # """Return the pattern that should be used to get the # problematics files""" # raise NotImplementedError('users must define __get_pattern_hint__ to\ # use this base class') # # @abc.abstractmethod # def get_problem_msg(self): # """Return the problem message of the checker""" # raise NotImplementedError('users must define __get_problem_msg__ to \ # use this base class') # # @abc.abstractmethod # def get_problem_type(self): # """Return the problem type of the checker""" # raise NotImplementedError('users must define __get_problem_type__ to \ # use this base class') . Output only the next line.
class ApiMklChecker(Checker):
Using the snippet: <|code_start|># -*- coding: utf-8 -*- """ Copyright (C) 2017 IBM Corporation Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Contributors: * Daniel Kreling <dbkreling@br.ibm.com> * Roberto Oliveira <rdutra@br.ibm.com> * Rafael Peria de Sene <rpsene@br.ibm.com> * Diego Fernandez-Merjildo <merjildo@br.ibm.com> """ <|code_end|> , determine the next line of code. You have imports: from clang.cindex import CursorKind from clang.cindex import TypeKind from ma.checkers.checker import Checker and context (class names, function names, or code) available: # Path: ma/checkers/checker.py # class Checker(object): # """ Abstract class Checker """ # __metaclass__ = abc.ABCMeta # # def check_node(self, node): # """ Check node from AST and return if it is a migration issue """ # return False # # def check_include(self, include_name): # """ Check include from AST and return if it is a migration issue """ # return False # # def check_file(self, file_name): # """ Check issues into file and return a list of lists, containing the # problem name and line number """ # return [] # # def get_solution(self, problem): # """ Get solution for the problem using the node from AST or the raw # node from file """ # return "" # # @abc.abstractmethod # def get_pattern_hint(self): # """Return the pattern that should be used to get the # problematics files""" # raise NotImplementedError('users must define __get_pattern_hint__ to\ # use this base class') # # @abc.abstractmethod # def get_problem_msg(self): # """Return the problem message of the checker""" # raise NotImplementedError('users must define __get_problem_msg__ to \ # use this base class') # # @abc.abstractmethod # def get_problem_type(self): # """Return the problem type of the checker""" # raise NotImplementedError('users must define __get_problem_type__ to \ # use this base class') . Output only the next line.
class LongDoubleChecker(Checker):
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*- """ Copyright (C) 2017 IBM Corporation Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Contributors: * Daniel Kreling <dbkreling@br.ibm.com> """ <|code_end|> using the current file's imports: import ma.checkers.checker_file_utils as utils from ma.checkers.checker import Checker and any relevant context from other files: # Path: ma/checkers/checker.py # class Checker(object): # """ Abstract class Checker """ # __metaclass__ = abc.ABCMeta # # def check_node(self, node): # """ Check node from AST and return if it is a migration issue """ # return False # # def check_include(self, include_name): # """ Check include from AST and return if it is a migration issue """ # return False # # def check_file(self, file_name): # """ Check issues into file and return a list of lists, containing the # problem name and line number """ # return [] # # def get_solution(self, problem): # """ Get solution for the problem using the node from AST or the raw # node from file """ # return "" # # @abc.abstractmethod # def get_pattern_hint(self): # """Return the pattern that should be used to get the # problematics files""" # raise NotImplementedError('users must define __get_pattern_hint__ to\ # use this base class') # # @abc.abstractmethod # def get_problem_msg(self): # """Return the problem message of the checker""" # raise NotImplementedError('users must define __get_problem_msg__ to \ # use this base class') # # @abc.abstractmethod # def get_problem_type(self): # """Return the problem type of the checker""" # raise NotImplementedError('users must define __get_problem_type__ to \ # use this base class') . Output only the next line.
class ApiIppChecker(Checker):
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- """ Copyright (C) 2017 IBM Corporation Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Contributors: * Roberto Oliveira <rdutra@br.ibm.com> * Rafael Peria de Sene <rpsene@br.ibm.com> """ class Statistics(object): """ Class to deal with statistics """ def __init__(self, kind): self.kind = kind <|code_end|> , predict the next line using imports from the current file: from terminaltables import AsciiTable from .problem_reporter import ProblemReporter and context including class names, function names, and sometimes code from other files: # Path: ma/problem_reporter.py # class ProblemReporter(object): # """ Class to handle with reported problems """ # problems = {} # # @classmethod # def report_include(cls, name, file_name, line, problem_type, problem_msg, # solution): # """ Report a problem in an include directive """ # if not cls.__should_report(file_name, line, file_name): # return # name = "include " + name # problem = Problem(name, file_name, line, problem_msg, solution) # cls.__report_problem(problem, problem_type) # # @classmethod # def report_node(cls, node, current_file, problem_type, problem_msg, # solution): # """ Report a problem in a node """ # node_loc = node.location # node_file = node_loc.file # node_line = node_loc.line # if not cls.__should_report(node_file, node_line, current_file): # return # # name = core.get_raw_node(node) # problem = Problem(name, node_file, node_line, problem_msg, solution) # cls.__report_problem(problem, problem_type) # # @classmethod # def report_file(cls, file_name, num_line, name, problem_type, problem_msg, # solution): # """ Report a problem in a file """ # if not cls.__should_report(file_name, num_line, file_name): # return # problem = Problem(name, file_name, num_line, problem_msg, solution) # cls.__report_problem(problem, problem_type) # # @classmethod # def __report_problem(cls, problem, problem_type): # """ Add the reported problem in a dictionary """ # if cls.problems.get(problem_type, None) is not None: # cls.problems.get(problem_type).append(problem) # else: # problem_list = [] # problem_list.append(problem) # cls.problems[problem_type] = problem_list # # @classmethod # def print_problems(cls): # """ Print all reported problems """ # if not cls.problems: # print("\nNo migration reports found.") # return # # tab = " " # cls.__print_logo() # for problem_type, problems in cls.problems.items(): # problems_dict = {} # # Group problems by file # for problem in problems: # name = problem.file_name # problems_dict[name] = problems_dict.get(name, []) + [problem] # # print("Problem type: " + problem_type) # print("Problem description: " + problems[0].problem_msg) # for file_name, problems in problems_dict.items(): # print(tab + "File: " + file_name) # for problem in problems: # print((tab * 2) + "Line: " + str(problem.line)) # print((tab * 2) + "Problem: " + str(problem.name)) # if problem.solution: # print((tab * 2) + "Solution: " + problem.solution) # print("") # print("") # # @classmethod # def get_problems(cls): # """ Get all reported problems """ # return cls.problems # # @classmethod # def clear_problems(cls): # """ Clear reported problems """ # cls.problems.clear() # # @classmethod # def __should_report(cls, node_file, node_line, current_file): # """ Check if should report the node """ # # Location is not known # if not node_file: # return False # # Node is not in the current file # if str(node_file) != current_file: # return False # # Node is inside a blocked line # if node_line in ReportBlocker.blocked_lines: # return False # return True # # @classmethod # def __print_logo(cls): # """ Print the report logo """ # title = "Migration Report" # border = "=" * len(title) # print("") # print(border) # print(title) # print(border) . Output only the next line.
self.problems = ProblemReporter.get_problems()
Using the snippet: <|code_start|># -*- coding: utf-8 -*- """ Copyright (C) 2017 IBM Corporation Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Contributors: * Daniel Kreling <dbkreling@br.ibm.com> * Roberto Oliveira <rdutra@br.ibm.com> * Diego Fernandez-Merjildo <merjildo@br.ibm.com> * Rafael Peria de Sene <rpsene@br.ibm.com> """ <|code_end|> , determine the next line of code. You have imports: from clang.cindex import CursorKind from ma.checkers.checker import Checker from ma.xml_loader.syscalls_loader import SyscallsLoader and context (class names, function names, or code) available: # Path: ma/checkers/checker.py # class Checker(object): # """ Abstract class Checker """ # __metaclass__ = abc.ABCMeta # # def check_node(self, node): # """ Check node from AST and return if it is a migration issue """ # return False # # def check_include(self, include_name): # """ Check include from AST and return if it is a migration issue """ # return False # # def check_file(self, file_name): # """ Check issues into file and return a list of lists, containing the # problem name and line number """ # return [] # # def get_solution(self, problem): # """ Get solution for the problem using the node from AST or the raw # node from file """ # return "" # # @abc.abstractmethod # def get_pattern_hint(self): # """Return the pattern that should be used to get the # problematics files""" # raise NotImplementedError('users must define __get_pattern_hint__ to\ # use this base class') # # @abc.abstractmethod # def get_problem_msg(self): # """Return the problem message of the checker""" # raise NotImplementedError('users must define __get_problem_msg__ to \ # use this base class') # # @abc.abstractmethod # def get_problem_type(self): # """Return the problem type of the checker""" # raise NotImplementedError('users must define __get_problem_type__ to \ # use this base class') # # Path: ma/xml_loader/syscalls_loader.py # class SyscallsLoader(object): # ''' Load syscalls into a Python element ''' # # def __init__(self): # self.syscalls = [] # self.__load_xml(SYSCALLS_FILE) # # def __load_xml(self, file_name): # '''Function to load the contents of syscalls.xml''' # tree = elemTree.parse(file_name) # self.root = tree.getroot() # for sysc in self.root.iter('syscall'): # self.syscalls.append(sysc.attrib) # # def get_names(self): # '''Method to populate a list of syscall names ''' # for sysc in self.root.findall('syscall'): # self.syscalls.append(sysc.get("target")) # return self.syscalls # # def get_fixes(self): # '''Method to populate a list of syscall fixes''' # suggestion_dict = {} # for sysc in self.root.findall('syscall'): # if sysc.get("replacer"): # suggestion_dict[sysc.get("target")] = (sysc.get("replacer"), # sysc.get("includes")) # return suggestion_dict . Output only the next line.
class SyscallChecker(Checker):
Here is a snippet: <|code_start|>Copyright (C) 2017 IBM Corporation Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Contributors: * Daniel Kreling <dbkreling@br.ibm.com> * Roberto Oliveira <rdutra@br.ibm.com> * Diego Fernandez-Merjildo <merjildo@br.ibm.com> * Rafael Peria de Sene <rpsene@br.ibm.com> """ class SyscallChecker(Checker): """ Checker for syscall declarations """ def __init__(self): self.problem_type = "Syscall usage" self.problem_msg = "Syscall not available in Power architecture." self.hint = 'ch[s/g/l/f/v/o/m/]\|SYS_\|' + 'statat' <|code_end|> . Write the next line using the current file imports: from clang.cindex import CursorKind from ma.checkers.checker import Checker from ma.xml_loader.syscalls_loader import SyscallsLoader and context from other files: # Path: ma/checkers/checker.py # class Checker(object): # """ Abstract class Checker """ # __metaclass__ = abc.ABCMeta # # def check_node(self, node): # """ Check node from AST and return if it is a migration issue """ # return False # # def check_include(self, include_name): # """ Check include from AST and return if it is a migration issue """ # return False # # def check_file(self, file_name): # """ Check issues into file and return a list of lists, containing the # problem name and line number """ # return [] # # def get_solution(self, problem): # """ Get solution for the problem using the node from AST or the raw # node from file """ # return "" # # @abc.abstractmethod # def get_pattern_hint(self): # """Return the pattern that should be used to get the # problematics files""" # raise NotImplementedError('users must define __get_pattern_hint__ to\ # use this base class') # # @abc.abstractmethod # def get_problem_msg(self): # """Return the problem message of the checker""" # raise NotImplementedError('users must define __get_problem_msg__ to \ # use this base class') # # @abc.abstractmethod # def get_problem_type(self): # """Return the problem type of the checker""" # raise NotImplementedError('users must define __get_problem_type__ to \ # use this base class') # # Path: ma/xml_loader/syscalls_loader.py # class SyscallsLoader(object): # ''' Load syscalls into a Python element ''' # # def __init__(self): # self.syscalls = [] # self.__load_xml(SYSCALLS_FILE) # # def __load_xml(self, file_name): # '''Function to load the contents of syscalls.xml''' # tree = elemTree.parse(file_name) # self.root = tree.getroot() # for sysc in self.root.iter('syscall'): # self.syscalls.append(sysc.attrib) # # def get_names(self): # '''Method to populate a list of syscall names ''' # for sysc in self.root.findall('syscall'): # self.syscalls.append(sysc.get("target")) # return self.syscalls # # def get_fixes(self): # '''Method to populate a list of syscall fixes''' # suggestion_dict = {} # for sysc in self.root.findall('syscall'): # if sysc.get("replacer"): # suggestion_dict[sysc.get("target")] = (sysc.get("replacer"), # sysc.get("includes")) # return suggestion_dict , which may include functions, classes, or code. Output only the next line.
self.syscalls_names = SyscallsLoader().get_names()
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*- """ Copyright (C) 2017 IBM Corporation Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Contributors: * Roberto Oliveira <rdutra@br.ibm.com> * Diego Fernandez-Merjildo <merjildo@br.ibm.com> """ <|code_end|> using the current file's imports: import re import os from clang.cindex import CursorKind from clang.cindex import TypeKind from ma.checkers.checker import Checker from ma import core and any relevant context from other files: # Path: ma/checkers/checker.py # class Checker(object): # """ Abstract class Checker """ # __metaclass__ = abc.ABCMeta # # def check_node(self, node): # """ Check node from AST and return if it is a migration issue """ # return False # # def check_include(self, include_name): # """ Check include from AST and return if it is a migration issue """ # return False # # def check_file(self, file_name): # """ Check issues into file and return a list of lists, containing the # problem name and line number """ # return [] # # def get_solution(self, problem): # """ Get solution for the problem using the node from AST or the raw # node from file """ # return "" # # @abc.abstractmethod # def get_pattern_hint(self): # """Return the pattern that should be used to get the # problematics files""" # raise NotImplementedError('users must define __get_pattern_hint__ to\ # use this base class') # # @abc.abstractmethod # def get_problem_msg(self): # """Return the problem message of the checker""" # raise NotImplementedError('users must define __get_problem_msg__ to \ # use this base class') # # @abc.abstractmethod # def get_problem_type(self): # """Return the problem type of the checker""" # raise NotImplementedError('users must define __get_problem_type__ to \ # use this base class') # # Path: ma/core.py # X86_PATTERNS = ["amd64", "AMD64", "[xX]86", "[xX]86_64", "[iI]386", "[iI]486", # "[iI]686"] # PPC_PATTERNS = ["PPC", "ppc", "power[pP][cC]", "POWER[pP][cC]"] # def get_supported_checkers(): # def get_supported_extensions(): # def execute(command): # def execute_stdout(command): # def cmdexists(command): # def get_timestamp(): # def get_files(location, hint=''): # def get_file_content(file_name, offset, length): # def get_raw_node(node): # def get_includes(file_path): # def get_ifdefs(file_path): # def get_ifdef_regex(arch, separator): . Output only the next line.
class CharChecker(Checker):
Here is a snippet: <|code_start|> def get_pattern_hint(self): return self.hint def get_problem_msg(self): return self.problem_msg def get_problem_type(self): return self.problem_type def check_node(self, node): kind = node.kind if kind != CursorKind.BINARY_OPERATOR and kind != CursorKind.VAR_DECL: return False if self._is_dangerous_type(node) and self._has_children(node): last_children_node = list(node.get_children())[-1] return self._is_dangerous_assignment(last_children_node) def get_solution(self, node): kind = node.kind type_kind = node.type.kind info = "" if kind == CursorKind.BINARY_OPERATOR or type_kind == TypeKind.TYPEDEF: node = self._get_var_declaration(node, node) location = node.location line = location.line file_name = os.path.basename(str(location.file)) info = " (file: {0} | line: {1})".format(file_name, line) <|code_end|> . Write the next line using the current file imports: import re import os from clang.cindex import CursorKind from clang.cindex import TypeKind from ma.checkers.checker import Checker from ma import core and context from other files: # Path: ma/checkers/checker.py # class Checker(object): # """ Abstract class Checker """ # __metaclass__ = abc.ABCMeta # # def check_node(self, node): # """ Check node from AST and return if it is a migration issue """ # return False # # def check_include(self, include_name): # """ Check include from AST and return if it is a migration issue """ # return False # # def check_file(self, file_name): # """ Check issues into file and return a list of lists, containing the # problem name and line number """ # return [] # # def get_solution(self, problem): # """ Get solution for the problem using the node from AST or the raw # node from file """ # return "" # # @abc.abstractmethod # def get_pattern_hint(self): # """Return the pattern that should be used to get the # problematics files""" # raise NotImplementedError('users must define __get_pattern_hint__ to\ # use this base class') # # @abc.abstractmethod # def get_problem_msg(self): # """Return the problem message of the checker""" # raise NotImplementedError('users must define __get_problem_msg__ to \ # use this base class') # # @abc.abstractmethod # def get_problem_type(self): # """Return the problem type of the checker""" # raise NotImplementedError('users must define __get_problem_type__ to \ # use this base class') # # Path: ma/core.py # X86_PATTERNS = ["amd64", "AMD64", "[xX]86", "[xX]86_64", "[iI]386", "[iI]486", # "[iI]686"] # PPC_PATTERNS = ["PPC", "ppc", "power[pP][cC]", "POWER[pP][cC]"] # def get_supported_checkers(): # def get_supported_extensions(): # def execute(command): # def execute_stdout(command): # def cmdexists(command): # def get_timestamp(): # def get_files(location, hint=''): # def get_file_content(file_name, offset, length): # def get_raw_node(node): # def get_includes(file_path): # def get_ifdefs(file_path): # def get_ifdef_regex(arch, separator): , which may include functions, classes, or code. Output only the next line.
raw_node = core.get_raw_node(node)
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- """ Copyright (C) 2017 IBM Corporation Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Contributors: * Rafael Peria de Sene <rpsene@br.ibm.com> """ <|code_end|> , generate the next line using the imports in this file: from ma.checkers.checker import Checker import ma.checkers.checker_file_utils as utils and context (functions, classes, or occasionally code) from other files: # Path: ma/checkers/checker.py # class Checker(object): # """ Abstract class Checker """ # __metaclass__ = abc.ABCMeta # # def check_node(self, node): # """ Check node from AST and return if it is a migration issue """ # return False # # def check_include(self, include_name): # """ Check include from AST and return if it is a migration issue """ # return False # # def check_file(self, file_name): # """ Check issues into file and return a list of lists, containing the # problem name and line number """ # return [] # # def get_solution(self, problem): # """ Get solution for the problem using the node from AST or the raw # node from file """ # return "" # # @abc.abstractmethod # def get_pattern_hint(self): # """Return the pattern that should be used to get the # problematics files""" # raise NotImplementedError('users must define __get_pattern_hint__ to\ # use this base class') # # @abc.abstractmethod # def get_problem_msg(self): # """Return the problem message of the checker""" # raise NotImplementedError('users must define __get_problem_msg__ to \ # use this base class') # # @abc.abstractmethod # def get_problem_type(self): # """Return the problem type of the checker""" # raise NotImplementedError('users must define __get_problem_type__ to \ # use this base class') . Output only the next line.
class PthreadChecker(Checker):
Given the code snippet: <|code_start|>#! /usr/bin/env python # -*- coding: utf-8 -*- """ Copyright (C) 2017 IBM Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Contributors: * Diego Fernandez-Merjildo <merjildo@br.ibm.com> """ class AssemblyReplacerTest(unittest.TestCase): """ Test cases for the Assembly replacer """ def get_replace_test(self): '''This test aim to check correct replace value return from get_replace() method in AssemblyReplacer class''' <|code_end|> , generate the next line using the imports in this file: import unittest from ma.xml_loader.asm_to_ppc import AssemblyReplacer and context (functions, classes, or occasionally code) from other files: # Path: ma/xml_loader/asm_to_ppc.py # class AssemblyReplacer(object): # """Class to assembly replacer for MA. # This class get information stored in XML file # into a python module""" # def __init__(self): # self.replacer = {} # self.load_xml(LOCAL_XML_ASM) # # def load_xml(self, file_name): # '''Method to load ASM replace strings. # This method open XML file and load info inside a # dictionary data structure''' # tree = elemTree.parse(file_name) # root = tree.getroot() # for asm in root.iter('asm'): # self.replacer[asm.attrib['target']] = [asm.attrib['type'], # asm.attrib['replacer']] # # def get_replace(self, target): # '''Method to get the replace for selected target''' # return self.replacer[target][1] # # def get_type(self, target): # '''Method to get the type for selected target''' # return self.replacer[target][0] . Output only the next line.
asm_replacer = AssemblyReplacer()
Continue the code snippet: <|code_start|># coding: utf-8 def configure(app): @app.context_processor def inject(): return dict( <|code_end|> . Use current file imports: from lingobarter.core.models.config import Config and context (classes, functions, or code) from other files: # Path: lingobarter/core/models/config.py # class Config(HasCustomValue, ContentFormat, Publishable, db.DynamicDocument): # group = db.StringField(max_length=255) # description = db.StringField() # # @classmethod # def get(cls, group, name=None, default=None): # # try: # instance = cls.objects.get(group=group) # except: # return None # # if not name: # ret = instance.values # if group == 'settings': # ret = {} # ret.update(current_app.config) # ret.update({item.name: item.value for item in instance.values}) # else: # try: # ret = instance.values.get(name=name).value # except (MultipleObjectsReturned, AttributeError): # ret = None # # if not ret and group == 'settings' and name is not None: # # get direct from store to avoid infinite loop # ret = current_app.config.store.get(name) # # return ret or default # # def __unicode__(self): # return self.group . Output only the next line.
Config=Config,
Using the snippet: <|code_start|> @classmethod def get(cls, group, name=None, default=None): try: instance = cls.objects.get(group=group) except: return None if not name: ret = instance.values if group == 'settings': ret = {} ret.update(current_app.config) ret.update({item.name: item.value for item in instance.values}) else: try: ret = instance.values.get(name=name).value except (MultipleObjectsReturned, AttributeError): ret = None if not ret and group == 'settings' and name is not None: # get direct from store to avoid infinite loop ret = current_app.config.store.get(name) return ret or default def __unicode__(self): return self.group <|code_end|> , determine the next line of code. You have imports: import logging from flask import current_app from lingobarter.core.db import db from lingobarter.core.fields import MultipleObjectsReturned from lingobarter.core.models.custom_values import HasCustomValue from lingobarter.core.models.signature import ( Publishable, ContentFormat, Dated, Slugged ) and context (class names, function names, or code) available: # Path: lingobarter/core/db.py # # Path: lingobarter/core/models/custom_values.py # class HasCustomValue(object): # values = db.ListField(db.EmbeddedDocumentField(CustomValue)) # # def get_values_tuple(self): # return [(value.name, value.value, value.formatter) # for value in self.values] # # def get_value(self, name, default=None): # try: # return self.values.get(name=name).value # except: # return default # # def add_value(self, name, value, formatter='text'): # """ # Another implementation # data = {"name": name, "rawvalue": value, "formatter": formatter} # self.values.update(data, name=name) or self.values.create(**data) # """ # custom_value = CustomValue( # name=name, # value=value, # formatter=formatter # ) # self.values.append(custom_value) # # def clean(self): # current_names = [value.name for value in self.values] # for name in current_names: # if current_names.count(name) > 1: # raise Exception(lazy_gettext("%(name)s already exists", # name=name)) # super(HasCustomValue, self).clean() # # Path: lingobarter/core/models/signature.py # class Publishable(Dated, Owned): # published = db.BooleanField(default=False) # # @property # def is_available(self): # now = datetime.datetime.now() # return ( # self.published and # self.available_at <= now and # (self.available_until is None or # self.available_until >= now) # ) # # def save(self, *args, **kwargs): # self.updated_at = datetime.datetime.now() # # user = get_current_user_for_models() # # if not self.id and not self.created_by: # self.created_by = user # self.last_updated_by = user # # super(Publishable, self).save(*args, **kwargs) # # class ContentFormat(object): # content_format = db.StringField( # choices=TEXT_FORMATS, # default=get_setting_value('DEFAULT_TEXT_FORMAT', 'html') # ) # # class Dated(object): # available_at = db.DateTimeField(default=datetime.datetime.now) # available_until = db.DateTimeField(required=False) # created_at = db.DateTimeField(default=datetime.datetime.now) # updated_at = db.DateTimeField(default=datetime.datetime.now) # # class Slugged(object): # slug = db.StringField(max_length=255, required=True) # # def validate_slug(self, title=None): # if self.slug: # self.slug = slugify(self.slug) # else: # self.slug = slugify(title or self.title) . Output only the next line.
class Lingobarter(Dated, Slugged, db.DynamicDocument):
Here is a snippet: <|code_start|> @classmethod def get(cls, group, name=None, default=None): try: instance = cls.objects.get(group=group) except: return None if not name: ret = instance.values if group == 'settings': ret = {} ret.update(current_app.config) ret.update({item.name: item.value for item in instance.values}) else: try: ret = instance.values.get(name=name).value except (MultipleObjectsReturned, AttributeError): ret = None if not ret and group == 'settings' and name is not None: # get direct from store to avoid infinite loop ret = current_app.config.store.get(name) return ret or default def __unicode__(self): return self.group <|code_end|> . Write the next line using the current file imports: import logging from flask import current_app from lingobarter.core.db import db from lingobarter.core.fields import MultipleObjectsReturned from lingobarter.core.models.custom_values import HasCustomValue from lingobarter.core.models.signature import ( Publishable, ContentFormat, Dated, Slugged ) and context from other files: # Path: lingobarter/core/db.py # # Path: lingobarter/core/models/custom_values.py # class HasCustomValue(object): # values = db.ListField(db.EmbeddedDocumentField(CustomValue)) # # def get_values_tuple(self): # return [(value.name, value.value, value.formatter) # for value in self.values] # # def get_value(self, name, default=None): # try: # return self.values.get(name=name).value # except: # return default # # def add_value(self, name, value, formatter='text'): # """ # Another implementation # data = {"name": name, "rawvalue": value, "formatter": formatter} # self.values.update(data, name=name) or self.values.create(**data) # """ # custom_value = CustomValue( # name=name, # value=value, # formatter=formatter # ) # self.values.append(custom_value) # # def clean(self): # current_names = [value.name for value in self.values] # for name in current_names: # if current_names.count(name) > 1: # raise Exception(lazy_gettext("%(name)s already exists", # name=name)) # super(HasCustomValue, self).clean() # # Path: lingobarter/core/models/signature.py # class Publishable(Dated, Owned): # published = db.BooleanField(default=False) # # @property # def is_available(self): # now = datetime.datetime.now() # return ( # self.published and # self.available_at <= now and # (self.available_until is None or # self.available_until >= now) # ) # # def save(self, *args, **kwargs): # self.updated_at = datetime.datetime.now() # # user = get_current_user_for_models() # # if not self.id and not self.created_by: # self.created_by = user # self.last_updated_by = user # # super(Publishable, self).save(*args, **kwargs) # # class ContentFormat(object): # content_format = db.StringField( # choices=TEXT_FORMATS, # default=get_setting_value('DEFAULT_TEXT_FORMAT', 'html') # ) # # class Dated(object): # available_at = db.DateTimeField(default=datetime.datetime.now) # available_until = db.DateTimeField(required=False) # created_at = db.DateTimeField(default=datetime.datetime.now) # updated_at = db.DateTimeField(default=datetime.datetime.now) # # class Slugged(object): # slug = db.StringField(max_length=255, required=True) # # def validate_slug(self, title=None): # if self.slug: # self.slug = slugify(self.slug) # else: # self.slug = slugify(title or self.title) , which may include functions, classes, or code. Output only the next line.
class Lingobarter(Dated, Slugged, db.DynamicDocument):
Next line prediction: <|code_start|> blueprint = getattr(mods[fname], object_name) app.logger.info("registering blueprint: %s" % blueprint.name) app.register_blueprint(blueprint) # register socket.io events module_events = ".".join([module_root, events_file]) try: events = getattr(importlib.import_module(module_events), 'register_events') app.logger.info("registering events for blueprint: %s" % blueprint.name) events(socket_io) except ImportError: pass # TODO: admin pending!!! # register admin # try: # importlib.import_module(".".join([module_root, 'admin'])) # except ImportError as e: # app.logger.info( # "%s module does not define admin or error: %s", fname, e # ) app.logger.info("%s modules loaded", mods.keys()) def blueprint_commands(app): blueprints_path = app.config.get('BLUEPRINTS_PATH', 'modules') modules_path = os.path.join( app.config.get('PROJECT_ROOT', '..'), blueprints_path ) base_module_name = ".".join([app.name, blueprints_path]) <|code_end|> . Use current file imports: (import importlib import os from lingobarter.ext.commands_collector import CommandsCollector) and context including class names, function names, or small code snippets from other files: # Path: lingobarter/ext/commands_collector.py # class CommandsCollector(click.MultiCommand): # """ # A MultiCommand to collect all click commands from a given # modules path and base name for the module. # The commands functions needs to be in a module inside commands # folder and the name of the file will be used as the command name. # """ # # def __init__(self, modules_path, base_module_name, **attrs): # click.MultiCommand.__init__(self, **attrs) # self.base_module_name = base_module_name # self.modules_path = modules_path # # def list_commands(self, *args, **kwargs): # commands = [] # for _path, _dir, _ in os.walk(self.modules_path): # if 'commands' not in _dir: # continue # for filename in os.listdir(os.path.join(_path, 'commands')): # if filename.endswith('.py') and filename != '__init__.py': # cmd = filename[:-3] # _, module_name = os.path.split(_path) # commands.append('{0}_{1}'.format(module_name, cmd)) # commands.sort() # return commands # # def get_command(self, ctx, name): # try: # if sys.version_info[0] == 2: # name = name.encode('ascii', 'replace') # splitted = name.split('_') # if len(splitted) <= 1: # return # module_name, command_name = splitted # if not all([module_name, command_name]): # return # module = '{0}.{1}.commands.{2}'.format( # self.base_module_name, # module_name, # command_name) # mod = importlib.import_module(module) # except ImportError: # return # return getattr(mod, 'cli', None) . Output only the next line.
cmds = CommandsCollector(modules_path, base_module_name)
Given the following code snippet before the placeholder: <|code_start|># coding: utf-8 class LanguageResource(Resource): def get(self): languages = {} for lang in Language.objects: languages[lang.name] = { 'id': str(lang.id), "name": lang.name, "u_name": lang.u_name, "abbrev": lang.abbrev } <|code_end|> , predict the next line using imports from the current file: from flask_restful import Resource from lingobarter.core.json import render_json from lingobarter.modules.accounts.models import Language and context including class names, function names, and sometimes code from other files: # Path: lingobarter/core/json.py # def render_json(message, status, **kwargs): # ret = { # 'message': message, # 'status': status, # } # if kwargs is not None and len(kwargs.keys()) != 0: # ret['response'] = kwargs # return ret . Output only the next line.
return render_json(message="Successfully fetch all languages", status=200, **languages)
Predict the next line for this snippet: <|code_start|> logger = logging.getLogger() def create_app_min(config=None, test=False): app = LingobarterApp('lingobarter') app.config.load_lingobarter_config(config=config, test=test) return app def get_site_url(): try: # why import models module instead of config.py? to avoid circular import from_site_config = m.config.Config.get('site', 'site_domain', None) from_settings = get_setting_value('SERVER_NAME', None) if from_settings and not from_settings.startswith('http'): from_settings = 'http://%s/' % from_settings return from_site_config or from_settings or request.url_root except RuntimeError: return 'http://localhost/' def get_setting_value(key, default=None): try: return current_app.config.get(key, default) except RuntimeError as e: logger.warning('current_app is inaccessible: %s' % e) try: app = create_app_min() <|code_end|> with the help of current file imports: import logging import lingobarter.core.models as m from flask import current_app, request from lingobarter.core.app import LingobarterApp from lingobarter.core.db import db and context from other files: # Path: lingobarter/core/db.py , which may contain function names, class names, or code. Output only the next line.
db.init_app(app)
Given snippet: <|code_start|> class ChannelIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.EdgeNgramField(document=True) name = indexes.CharField(model_attr='name') status = indexes.CharField(model_attr='status') def get_model(self): <|code_end|> , continue by predicting the next line. Consider current file imports: import datetime from haystack import indexes from channels.models import Channel and context: # Path: channels/models.py # class Channel(models.Model): # name = models.CharField(max_length=64, unique=True) # # STATUS_ACTIVE = 'AC' # STATUS_DELETED = 'DL' # # STATUS_CHOICES = ( # (STATUS_ACTIVE, 'Active'), # (STATUS_DELETED, 'Deleted'), # ) # # status = models.CharField(max_length=2, choices=STATUS_CHOICES, default=STATUS_ACTIVE) # subscribers = models.ManyToManyField('auth.user', related_name="subscriptions") # members = models.ManyToManyField('auth.user', related_name="members") # # def get_absolute_url(self): # return reverse("view_channel", kwargs={"slug": self.name}) # # def clean(self): # if len(self.name) < 2: # raise ValidationError('Name is to short (<2 Chars)') # # if not re.match(r'^\w+$', self.name): # raise ValidationError("Name must only contain letters, numbers and underscores.") which might include code, classes, or functions. Output only the next line.
return Channel
Predict the next line after this snippet: <|code_start|> class ChannelDetailView(DetailView): #A view for when users look for a single Channel model = Channel #Tells the DetailView to use the Channel model template_name = "view_channel.html" context_object = "channel" #Sets the name in the template context #Sets the field to use for lookups; in this case the name field slug_field = "name" <|code_end|> using the current file's imports: from django.shortcuts import render from django.contrib.auth.decorators import login_required from models import Channel from django.db import IntegrityError from django.core.urlresolvers import reverse from django.http import HttpResponse, HttpResponseRedirect, HttpResponseBadRequest from django.views.generic import TemplateView, CreateView, DetailView from main.views import LoginRequiredMixin from channels.forms import ChannelForm and any relevant context from other files: # Path: main/views.py # class LoginRequiredMixin(object): # @method_decorator(login_required) # def dispatch(self, request, *args, **kwargs): # return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs) # # Path: channels/forms.py # class ChannelForm(ModelForm): # # class Meta: # model = Channel # fields = ["name"] . Output only the next line.
class ChannelListView(LoginRequiredMixin, TemplateView):
Given snippet: <|code_start|> class ChannelDetailView(DetailView): #A view for when users look for a single Channel model = Channel #Tells the DetailView to use the Channel model template_name = "view_channel.html" context_object = "channel" #Sets the name in the template context #Sets the field to use for lookups; in this case the name field slug_field = "name" class ChannelListView(LoginRequiredMixin, TemplateView): #A view for when users look at all channels template_name = "channels.html" class ChannelCreateView(LoginRequiredMixin, CreateView): template_name = "create_channel.html" model = Channel <|code_end|> , continue by predicting the next line. Consider current file imports: from django.shortcuts import render from django.contrib.auth.decorators import login_required from models import Channel from django.db import IntegrityError from django.core.urlresolvers import reverse from django.http import HttpResponse, HttpResponseRedirect, HttpResponseBadRequest from django.views.generic import TemplateView, CreateView, DetailView from main.views import LoginRequiredMixin from channels.forms import ChannelForm and context: # Path: main/views.py # class LoginRequiredMixin(object): # @method_decorator(login_required) # def dispatch(self, request, *args, **kwargs): # return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs) # # Path: channels/forms.py # class ChannelForm(ModelForm): # # class Meta: # model = Channel # fields = ["name"] which might include code, classes, or functions. Output only the next line.
form_class = ChannelForm
Predict the next line for this snippet: <|code_start|> try: except: VIDEO_BUCKET_NAME = "bitvid-video" # Create your views here. @login_required def upload(request): if request.method == "GET": <|code_end|> with the help of current file imports: from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect, HttpResponseBadRequest from django.contrib.auth.decorators import login_required from models import VideoFile, Video from channels.models import Channel from bitvid.settings import VIDEO_BUCKET_NAME import boto.s3.connection import boto.s3.key import re import bitvid.dbinfo and context from other files: # Path: channels/models.py # class Channel(models.Model): # name = models.CharField(max_length=64, unique=True) # # STATUS_ACTIVE = 'AC' # STATUS_DELETED = 'DL' # # STATUS_CHOICES = ( # (STATUS_ACTIVE, 'Active'), # (STATUS_DELETED, 'Deleted'), # ) # # status = models.CharField(max_length=2, choices=STATUS_CHOICES, default=STATUS_ACTIVE) # subscribers = models.ManyToManyField('auth.user', related_name="subscriptions") # members = models.ManyToManyField('auth.user', related_name="members") # # def get_absolute_url(self): # return reverse("view_channel", kwargs={"slug": self.name}) # # def clean(self): # if len(self.name) < 2: # raise ValidationError('Name is to short (<2 Chars)') # # if not re.match(r'^\w+$', self.name): # raise ValidationError("Name must only contain letters, numbers and underscores.") , which may contain function names, class names, or code. Output only the next line.
chans = Channel.objects.filter(members__in=[request.user])
Next line prediction: <|code_start|># -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2015-2019 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Storage module tests.""" def test_make_path(): """Test path for files.""" myid = 'deadbeef-dead-dead-dead-deaddeafbeef' base = '/base' f = 'data' <|code_end|> . Use current file imports: (import pytest from invenio_files_rest.helpers import make_path) and context including class names, function names, or small code snippets from other files: # Path: invenio_files_rest/helpers.py # def make_path(base_uri, path, filename, path_dimensions, split_length): # """Generate a path as base location for file instance. # # :param base_uri: The base URI. # :param path: The relative path. # :param path_dimensions: Number of chunks the path should be split into. # :param split_length: The length of any chunk. # :returns: A string representing the full path. # """ # assert len(path) > path_dimensions * split_length # # uri_parts = [] # for i in range(path_dimensions): # uri_parts.append(path[0:split_length]) # path = path[split_length:] # uri_parts.append(path) # uri_parts.append(filename) # # return os.path.join(base_uri, *uri_parts) . Output only the next line.
assert make_path(base, myid, f, 1, 1) == \
Predict the next line after this snippet: <|code_start|> ensure_readable = ensure_state( lambda o: o.readable, FileInstanceUnreadableError) """Ensure file is readable.""" ensure_writable = ensure_state( lambda o: o.writable, ValueError, 'File is not writable.') """Ensure file is writeable.""" ensure_completed = ensure_state( lambda o: o.completed, MultipartNotCompleted) """Ensure file is completed.""" ensure_uncompleted = ensure_state( lambda o: not o.completed, MultipartAlreadyCompleted) """Ensure file is not completed.""" ensure_not_deleted = ensure_state( lambda o: not o.deleted, InvalidOperationError, [BucketError('Cannot make snapshot of a deleted bucket.')]) """Ensure file is not deleted.""" ensure_unlocked = ensure_state( lambda o: not o.locked, <|code_end|> using the current file's imports: import re import sys import uuid from datetime import datetime from flask import current_app from functools import wraps from invenio_db import db from os.path import basename from sqlalchemy.dialects import mysql from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy.orm import validates from sqlalchemy.orm.exc import MultipleResultsFound from sqlalchemy_utils.types import UUIDType from .errors import BucketLockedError, FileInstanceAlreadySetError, \ FileInstanceUnreadableError, FileSizeError, InvalidKeyError, \ InvalidOperationError, MultipartAlreadyCompleted, \ MultipartInvalidChunkSize, MultipartInvalidPartNumber, \ MultipartInvalidSize, MultipartMissingParts, MultipartNotCompleted from .proxies import current_files_rest from .utils import guess_mimetype and any relevant context from other files: # Path: invenio_files_rest/errors.py # class BucketLockedError(InvalidOperationError): # """Exception raised when a bucket is locked.""" # # code = 403 # description = "Bucket is locked for modifications." # # class FileInstanceAlreadySetError(InvalidOperationError): # """Exception raised when file instance already set on object.""" # # class FileInstanceUnreadableError(InvalidOperationError): # """Exception raised when trying to get an unreadable file.""" # # code = 503 # description = "File storage is offline." # # class FileSizeError(StorageError): # """Exception raised when a file larger than allowed.""" # # code = 400 # # class InvalidKeyError(InvalidOperationError): # """Invalid key.""" # # code = 400 # description = "Filename is too long." # # class InvalidOperationError(FilesException): # """Exception raised when an invalid operation is performed.""" # # code = 403 # # class MultipartAlreadyCompleted(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 403 # description = "Multipart upload is already completed." # # class MultipartInvalidChunkSize(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Invalid part size." # # class MultipartInvalidPartNumber(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Invalid part number." # # class MultipartInvalidSize(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Invalid file size." # # class MultipartMissingParts(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Not all parts have been uploaded." # # class MultipartNotCompleted(MultipartException): # """Exception raised when multipart object is not already completed.""" # # code = 400 # description = "Multipart upload is already completed." # # Path: invenio_files_rest/proxies.py # # Path: invenio_files_rest/utils.py # def guess_mimetype(filename): # """Map extra mimetype with the encoding provided. # # :returns: The extra mimetype. # """ # m, encoding = mimetypes.guess_type(filename) # if encoding: # m = ENCODING_MIMETYPES.get(encoding, None) # return m or 'application/octet-stream' . Output only the next line.
BucketLockedError)
Continue the code snippet: <|code_start|>"""Ensure file is readable.""" ensure_writable = ensure_state( lambda o: o.writable, ValueError, 'File is not writable.') """Ensure file is writeable.""" ensure_completed = ensure_state( lambda o: o.completed, MultipartNotCompleted) """Ensure file is completed.""" ensure_uncompleted = ensure_state( lambda o: not o.completed, MultipartAlreadyCompleted) """Ensure file is not completed.""" ensure_not_deleted = ensure_state( lambda o: not o.deleted, InvalidOperationError, [BucketError('Cannot make snapshot of a deleted bucket.')]) """Ensure file is not deleted.""" ensure_unlocked = ensure_state( lambda o: not o.locked, BucketLockedError) """Ensure bucket is locked.""" ensure_no_file = ensure_state( lambda o: o.file_id is None, <|code_end|> . Use current file imports: import re import sys import uuid from datetime import datetime from flask import current_app from functools import wraps from invenio_db import db from os.path import basename from sqlalchemy.dialects import mysql from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy.orm import validates from sqlalchemy.orm.exc import MultipleResultsFound from sqlalchemy_utils.types import UUIDType from .errors import BucketLockedError, FileInstanceAlreadySetError, \ FileInstanceUnreadableError, FileSizeError, InvalidKeyError, \ InvalidOperationError, MultipartAlreadyCompleted, \ MultipartInvalidChunkSize, MultipartInvalidPartNumber, \ MultipartInvalidSize, MultipartMissingParts, MultipartNotCompleted from .proxies import current_files_rest from .utils import guess_mimetype and context (classes, functions, or code) from other files: # Path: invenio_files_rest/errors.py # class BucketLockedError(InvalidOperationError): # """Exception raised when a bucket is locked.""" # # code = 403 # description = "Bucket is locked for modifications." # # class FileInstanceAlreadySetError(InvalidOperationError): # """Exception raised when file instance already set on object.""" # # class FileInstanceUnreadableError(InvalidOperationError): # """Exception raised when trying to get an unreadable file.""" # # code = 503 # description = "File storage is offline." # # class FileSizeError(StorageError): # """Exception raised when a file larger than allowed.""" # # code = 400 # # class InvalidKeyError(InvalidOperationError): # """Invalid key.""" # # code = 400 # description = "Filename is too long." # # class InvalidOperationError(FilesException): # """Exception raised when an invalid operation is performed.""" # # code = 403 # # class MultipartAlreadyCompleted(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 403 # description = "Multipart upload is already completed." # # class MultipartInvalidChunkSize(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Invalid part size." # # class MultipartInvalidPartNumber(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Invalid part number." # # class MultipartInvalidSize(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Invalid file size." # # class MultipartMissingParts(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Not all parts have been uploaded." # # class MultipartNotCompleted(MultipartException): # """Exception raised when multipart object is not already completed.""" # # code = 400 # description = "Multipart upload is already completed." # # Path: invenio_files_rest/proxies.py # # Path: invenio_files_rest/utils.py # def guess_mimetype(filename): # """Map extra mimetype with the encoding provided. # # :returns: The extra mimetype. # """ # m, encoding = mimetypes.guess_type(filename) # if encoding: # m = ENCODING_MIMETYPES.get(encoding, None) # return m or 'application/octet-stream' . Output only the next line.
FileInstanceAlreadySetError)
Continue the code snippet: <|code_start|> class BucketError(object): """Represents a bucket level error. .. note:: This is not an actual exception. """ def __init__(self, message): self.res = dict(message=message) def to_dict(self): return self.res class ObjectVersionError(object): """Represents an object version level error. .. note:: This is not an actual exception. """ def __init__(self, message): self.res = dict(message=message) def to_dict(self): return self.res ensure_readable = ensure_state( lambda o: o.readable, <|code_end|> . Use current file imports: import re import sys import uuid from datetime import datetime from flask import current_app from functools import wraps from invenio_db import db from os.path import basename from sqlalchemy.dialects import mysql from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy.orm import validates from sqlalchemy.orm.exc import MultipleResultsFound from sqlalchemy_utils.types import UUIDType from .errors import BucketLockedError, FileInstanceAlreadySetError, \ FileInstanceUnreadableError, FileSizeError, InvalidKeyError, \ InvalidOperationError, MultipartAlreadyCompleted, \ MultipartInvalidChunkSize, MultipartInvalidPartNumber, \ MultipartInvalidSize, MultipartMissingParts, MultipartNotCompleted from .proxies import current_files_rest from .utils import guess_mimetype and context (classes, functions, or code) from other files: # Path: invenio_files_rest/errors.py # class BucketLockedError(InvalidOperationError): # """Exception raised when a bucket is locked.""" # # code = 403 # description = "Bucket is locked for modifications." # # class FileInstanceAlreadySetError(InvalidOperationError): # """Exception raised when file instance already set on object.""" # # class FileInstanceUnreadableError(InvalidOperationError): # """Exception raised when trying to get an unreadable file.""" # # code = 503 # description = "File storage is offline." # # class FileSizeError(StorageError): # """Exception raised when a file larger than allowed.""" # # code = 400 # # class InvalidKeyError(InvalidOperationError): # """Invalid key.""" # # code = 400 # description = "Filename is too long." # # class InvalidOperationError(FilesException): # """Exception raised when an invalid operation is performed.""" # # code = 403 # # class MultipartAlreadyCompleted(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 403 # description = "Multipart upload is already completed." # # class MultipartInvalidChunkSize(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Invalid part size." # # class MultipartInvalidPartNumber(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Invalid part number." # # class MultipartInvalidSize(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Invalid file size." # # class MultipartMissingParts(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Not all parts have been uploaded." # # class MultipartNotCompleted(MultipartException): # """Exception raised when multipart object is not already completed.""" # # code = 400 # description = "Multipart upload is already completed." # # Path: invenio_files_rest/proxies.py # # Path: invenio_files_rest/utils.py # def guess_mimetype(filename): # """Map extra mimetype with the encoding provided. # # :returns: The extra mimetype. # """ # m, encoding = mimetypes.guess_type(filename) # if encoding: # m = ENCODING_MIMETYPES.get(encoding, None) # return m or 'application/octet-stream' . Output only the next line.
FileInstanceUnreadableError)
Given the code snippet: <|code_start|> def delete(self): """Delete a multipart object.""" # Update bucket size. self.bucket.size -= self.size # Remove parts Part.query_by_multipart(self).delete() # Remove self self.query.filter_by(upload_id=self.upload_id).delete() @classmethod def create(cls, bucket, key, size, chunk_size): """Create a new object in a bucket.""" bucket = as_bucket(bucket) if bucket.locked: raise BucketLockedError() # Validate chunk size. if not cls.is_valid_chunksize(chunk_size): raise MultipartInvalidChunkSize() # Validate max theoretical size. if not cls.is_valid_size(size, chunk_size): raise MultipartInvalidSize() # Validate max bucket size. bucket_limit = bucket.size_limit if bucket_limit and size > bucket_limit: desc = 'File size limit exceeded.' \ if isinstance(bucket_limit, int) else bucket_limit.reason <|code_end|> , generate the next line using the imports in this file: import re import sys import uuid from datetime import datetime from flask import current_app from functools import wraps from invenio_db import db from os.path import basename from sqlalchemy.dialects import mysql from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy.orm import validates from sqlalchemy.orm.exc import MultipleResultsFound from sqlalchemy_utils.types import UUIDType from .errors import BucketLockedError, FileInstanceAlreadySetError, \ FileInstanceUnreadableError, FileSizeError, InvalidKeyError, \ InvalidOperationError, MultipartAlreadyCompleted, \ MultipartInvalidChunkSize, MultipartInvalidPartNumber, \ MultipartInvalidSize, MultipartMissingParts, MultipartNotCompleted from .proxies import current_files_rest from .utils import guess_mimetype and context (functions, classes, or occasionally code) from other files: # Path: invenio_files_rest/errors.py # class BucketLockedError(InvalidOperationError): # """Exception raised when a bucket is locked.""" # # code = 403 # description = "Bucket is locked for modifications." # # class FileInstanceAlreadySetError(InvalidOperationError): # """Exception raised when file instance already set on object.""" # # class FileInstanceUnreadableError(InvalidOperationError): # """Exception raised when trying to get an unreadable file.""" # # code = 503 # description = "File storage is offline." # # class FileSizeError(StorageError): # """Exception raised when a file larger than allowed.""" # # code = 400 # # class InvalidKeyError(InvalidOperationError): # """Invalid key.""" # # code = 400 # description = "Filename is too long." # # class InvalidOperationError(FilesException): # """Exception raised when an invalid operation is performed.""" # # code = 403 # # class MultipartAlreadyCompleted(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 403 # description = "Multipart upload is already completed." # # class MultipartInvalidChunkSize(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Invalid part size." # # class MultipartInvalidPartNumber(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Invalid part number." # # class MultipartInvalidSize(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Invalid file size." # # class MultipartMissingParts(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Not all parts have been uploaded." # # class MultipartNotCompleted(MultipartException): # """Exception raised when multipart object is not already completed.""" # # code = 400 # description = "Multipart upload is already completed." # # Path: invenio_files_rest/proxies.py # # Path: invenio_files_rest/utils.py # def guess_mimetype(filename): # """Map extra mimetype with the encoding provided. # # :returns: The extra mimetype. # """ # m, encoding = mimetypes.guess_type(filename) # if encoding: # m = ENCODING_MIMETYPES.get(encoding, None) # return m or 'application/octet-stream' . Output only the next line.
raise FileSizeError(description=desc)
Here is a snippet: <|code_start|> many object versions. * **Locations** - A bucket belongs to a specific location. Locations can be used to represent e.g. different storage systems. * **Multipart Objects** - Identified by UUIDs and belongs to a specific bucket and key. * **Part object** - Identified by their multipart object and a part number. The actual file access is handled by a storage interface. Also, objects do not have their own model, but are represented via the :py:data:`ObjectVersion` model. """ slug_pattern = re.compile('^[a-z][a-z0-9-]+$') # # Helpers # def validate_key(key): """Validate key. :param key: The key to validate. :raises invenio_files_rest.errors.InvalidKeyError: If the key is longer than the maximum length defined in :data:`invenio_files_rest.config.FILES_REST_FILE_URI_MAX_LEN`. :returns: The key. """ if len(key) > current_app.config['FILES_REST_OBJECT_KEY_MAX_LEN']: <|code_end|> . Write the next line using the current file imports: import re import sys import uuid from datetime import datetime from flask import current_app from functools import wraps from invenio_db import db from os.path import basename from sqlalchemy.dialects import mysql from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy.orm import validates from sqlalchemy.orm.exc import MultipleResultsFound from sqlalchemy_utils.types import UUIDType from .errors import BucketLockedError, FileInstanceAlreadySetError, \ FileInstanceUnreadableError, FileSizeError, InvalidKeyError, \ InvalidOperationError, MultipartAlreadyCompleted, \ MultipartInvalidChunkSize, MultipartInvalidPartNumber, \ MultipartInvalidSize, MultipartMissingParts, MultipartNotCompleted from .proxies import current_files_rest from .utils import guess_mimetype and context from other files: # Path: invenio_files_rest/errors.py # class BucketLockedError(InvalidOperationError): # """Exception raised when a bucket is locked.""" # # code = 403 # description = "Bucket is locked for modifications." # # class FileInstanceAlreadySetError(InvalidOperationError): # """Exception raised when file instance already set on object.""" # # class FileInstanceUnreadableError(InvalidOperationError): # """Exception raised when trying to get an unreadable file.""" # # code = 503 # description = "File storage is offline." # # class FileSizeError(StorageError): # """Exception raised when a file larger than allowed.""" # # code = 400 # # class InvalidKeyError(InvalidOperationError): # """Invalid key.""" # # code = 400 # description = "Filename is too long." # # class InvalidOperationError(FilesException): # """Exception raised when an invalid operation is performed.""" # # code = 403 # # class MultipartAlreadyCompleted(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 403 # description = "Multipart upload is already completed." # # class MultipartInvalidChunkSize(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Invalid part size." # # class MultipartInvalidPartNumber(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Invalid part number." # # class MultipartInvalidSize(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Invalid file size." # # class MultipartMissingParts(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Not all parts have been uploaded." # # class MultipartNotCompleted(MultipartException): # """Exception raised when multipart object is not already completed.""" # # code = 400 # description = "Multipart upload is already completed." # # Path: invenio_files_rest/proxies.py # # Path: invenio_files_rest/utils.py # def guess_mimetype(filename): # """Map extra mimetype with the encoding provided. # # :returns: The extra mimetype. # """ # m, encoding = mimetypes.guess_type(filename) # if encoding: # m = ENCODING_MIMETYPES.get(encoding, None) # return m or 'application/octet-stream' , which may include functions, classes, or code. Output only the next line.
raise InvalidKeyError()
Next line prediction: <|code_start|> def __init__(self, message): self.res = dict(message=message) def to_dict(self): return self.res ensure_readable = ensure_state( lambda o: o.readable, FileInstanceUnreadableError) """Ensure file is readable.""" ensure_writable = ensure_state( lambda o: o.writable, ValueError, 'File is not writable.') """Ensure file is writeable.""" ensure_completed = ensure_state( lambda o: o.completed, MultipartNotCompleted) """Ensure file is completed.""" ensure_uncompleted = ensure_state( lambda o: not o.completed, MultipartAlreadyCompleted) """Ensure file is not completed.""" ensure_not_deleted = ensure_state( lambda o: not o.deleted, <|code_end|> . Use current file imports: (import re import sys import uuid from datetime import datetime from flask import current_app from functools import wraps from invenio_db import db from os.path import basename from sqlalchemy.dialects import mysql from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy.orm import validates from sqlalchemy.orm.exc import MultipleResultsFound from sqlalchemy_utils.types import UUIDType from .errors import BucketLockedError, FileInstanceAlreadySetError, \ FileInstanceUnreadableError, FileSizeError, InvalidKeyError, \ InvalidOperationError, MultipartAlreadyCompleted, \ MultipartInvalidChunkSize, MultipartInvalidPartNumber, \ MultipartInvalidSize, MultipartMissingParts, MultipartNotCompleted from .proxies import current_files_rest from .utils import guess_mimetype) and context including class names, function names, or small code snippets from other files: # Path: invenio_files_rest/errors.py # class BucketLockedError(InvalidOperationError): # """Exception raised when a bucket is locked.""" # # code = 403 # description = "Bucket is locked for modifications." # # class FileInstanceAlreadySetError(InvalidOperationError): # """Exception raised when file instance already set on object.""" # # class FileInstanceUnreadableError(InvalidOperationError): # """Exception raised when trying to get an unreadable file.""" # # code = 503 # description = "File storage is offline." # # class FileSizeError(StorageError): # """Exception raised when a file larger than allowed.""" # # code = 400 # # class InvalidKeyError(InvalidOperationError): # """Invalid key.""" # # code = 400 # description = "Filename is too long." # # class InvalidOperationError(FilesException): # """Exception raised when an invalid operation is performed.""" # # code = 403 # # class MultipartAlreadyCompleted(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 403 # description = "Multipart upload is already completed." # # class MultipartInvalidChunkSize(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Invalid part size." # # class MultipartInvalidPartNumber(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Invalid part number." # # class MultipartInvalidSize(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Invalid file size." # # class MultipartMissingParts(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Not all parts have been uploaded." # # class MultipartNotCompleted(MultipartException): # """Exception raised when multipart object is not already completed.""" # # code = 400 # description = "Multipart upload is already completed." # # Path: invenio_files_rest/proxies.py # # Path: invenio_files_rest/utils.py # def guess_mimetype(filename): # """Map extra mimetype with the encoding provided. # # :returns: The extra mimetype. # """ # m, encoding = mimetypes.guess_type(filename) # if encoding: # m = ENCODING_MIMETYPES.get(encoding, None) # return m or 'application/octet-stream' . Output only the next line.
InvalidOperationError,
Predict the next line for this snippet: <|code_start|>class ObjectVersionError(object): """Represents an object version level error. .. note:: This is not an actual exception. """ def __init__(self, message): self.res = dict(message=message) def to_dict(self): return self.res ensure_readable = ensure_state( lambda o: o.readable, FileInstanceUnreadableError) """Ensure file is readable.""" ensure_writable = ensure_state( lambda o: o.writable, ValueError, 'File is not writable.') """Ensure file is writeable.""" ensure_completed = ensure_state( lambda o: o.completed, MultipartNotCompleted) """Ensure file is completed.""" ensure_uncompleted = ensure_state( lambda o: not o.completed, <|code_end|> with the help of current file imports: import re import sys import uuid from datetime import datetime from flask import current_app from functools import wraps from invenio_db import db from os.path import basename from sqlalchemy.dialects import mysql from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy.orm import validates from sqlalchemy.orm.exc import MultipleResultsFound from sqlalchemy_utils.types import UUIDType from .errors import BucketLockedError, FileInstanceAlreadySetError, \ FileInstanceUnreadableError, FileSizeError, InvalidKeyError, \ InvalidOperationError, MultipartAlreadyCompleted, \ MultipartInvalidChunkSize, MultipartInvalidPartNumber, \ MultipartInvalidSize, MultipartMissingParts, MultipartNotCompleted from .proxies import current_files_rest from .utils import guess_mimetype and context from other files: # Path: invenio_files_rest/errors.py # class BucketLockedError(InvalidOperationError): # """Exception raised when a bucket is locked.""" # # code = 403 # description = "Bucket is locked for modifications." # # class FileInstanceAlreadySetError(InvalidOperationError): # """Exception raised when file instance already set on object.""" # # class FileInstanceUnreadableError(InvalidOperationError): # """Exception raised when trying to get an unreadable file.""" # # code = 503 # description = "File storage is offline." # # class FileSizeError(StorageError): # """Exception raised when a file larger than allowed.""" # # code = 400 # # class InvalidKeyError(InvalidOperationError): # """Invalid key.""" # # code = 400 # description = "Filename is too long." # # class InvalidOperationError(FilesException): # """Exception raised when an invalid operation is performed.""" # # code = 403 # # class MultipartAlreadyCompleted(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 403 # description = "Multipart upload is already completed." # # class MultipartInvalidChunkSize(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Invalid part size." # # class MultipartInvalidPartNumber(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Invalid part number." # # class MultipartInvalidSize(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Invalid file size." # # class MultipartMissingParts(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Not all parts have been uploaded." # # class MultipartNotCompleted(MultipartException): # """Exception raised when multipart object is not already completed.""" # # code = 400 # description = "Multipart upload is already completed." # # Path: invenio_files_rest/proxies.py # # Path: invenio_files_rest/utils.py # def guess_mimetype(filename): # """Map extra mimetype with the encoding provided. # # :returns: The extra mimetype. # """ # m, encoding = mimetypes.guess_type(filename) # if encoding: # m = ENCODING_MIMETYPES.get(encoding, None) # return m or 'application/octet-stream' , which may contain function names, class names, or code. Output only the next line.
MultipartAlreadyCompleted)
Continue the code snippet: <|code_start|> self.file.update_checksum(**kwargs) with db.session.begin_nested(): obj = ObjectVersion.create( self.bucket, self.key, _file_id=self.file_id, version_id=version_id ) self.delete() return obj def delete(self): """Delete a multipart object.""" # Update bucket size. self.bucket.size -= self.size # Remove parts Part.query_by_multipart(self).delete() # Remove self self.query.filter_by(upload_id=self.upload_id).delete() @classmethod def create(cls, bucket, key, size, chunk_size): """Create a new object in a bucket.""" bucket = as_bucket(bucket) if bucket.locked: raise BucketLockedError() # Validate chunk size. if not cls.is_valid_chunksize(chunk_size): <|code_end|> . Use current file imports: import re import sys import uuid from datetime import datetime from flask import current_app from functools import wraps from invenio_db import db from os.path import basename from sqlalchemy.dialects import mysql from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy.orm import validates from sqlalchemy.orm.exc import MultipleResultsFound from sqlalchemy_utils.types import UUIDType from .errors import BucketLockedError, FileInstanceAlreadySetError, \ FileInstanceUnreadableError, FileSizeError, InvalidKeyError, \ InvalidOperationError, MultipartAlreadyCompleted, \ MultipartInvalidChunkSize, MultipartInvalidPartNumber, \ MultipartInvalidSize, MultipartMissingParts, MultipartNotCompleted from .proxies import current_files_rest from .utils import guess_mimetype and context (classes, functions, or code) from other files: # Path: invenio_files_rest/errors.py # class BucketLockedError(InvalidOperationError): # """Exception raised when a bucket is locked.""" # # code = 403 # description = "Bucket is locked for modifications." # # class FileInstanceAlreadySetError(InvalidOperationError): # """Exception raised when file instance already set on object.""" # # class FileInstanceUnreadableError(InvalidOperationError): # """Exception raised when trying to get an unreadable file.""" # # code = 503 # description = "File storage is offline." # # class FileSizeError(StorageError): # """Exception raised when a file larger than allowed.""" # # code = 400 # # class InvalidKeyError(InvalidOperationError): # """Invalid key.""" # # code = 400 # description = "Filename is too long." # # class InvalidOperationError(FilesException): # """Exception raised when an invalid operation is performed.""" # # code = 403 # # class MultipartAlreadyCompleted(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 403 # description = "Multipart upload is already completed." # # class MultipartInvalidChunkSize(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Invalid part size." # # class MultipartInvalidPartNumber(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Invalid part number." # # class MultipartInvalidSize(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Invalid file size." # # class MultipartMissingParts(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Not all parts have been uploaded." # # class MultipartNotCompleted(MultipartException): # """Exception raised when multipart object is not already completed.""" # # code = 400 # description = "Multipart upload is already completed." # # Path: invenio_files_rest/proxies.py # # Path: invenio_files_rest/utils.py # def guess_mimetype(filename): # """Map extra mimetype with the encoding provided. # # :returns: The extra mimetype. # """ # m, encoding = mimetypes.guess_type(filename) # if encoding: # m = ENCODING_MIMETYPES.get(encoding, None) # return m or 'application/octet-stream' . Output only the next line.
raise MultipartInvalidChunkSize()
Continue the code snippet: <|code_start|> @validates('key') def validate_key(self, key, key_): """Validate key.""" return validate_key(key_) @staticmethod def is_valid_chunksize(chunk_size): """Check if size is valid.""" min_csize = current_app.config['FILES_REST_MULTIPART_CHUNKSIZE_MIN'] max_csize = current_app.config['FILES_REST_MULTIPART_CHUNKSIZE_MAX'] return chunk_size >= min_csize and chunk_size <= max_csize @staticmethod def is_valid_size(size, chunk_size): """Validate max theoretical size.""" min_csize = current_app.config['FILES_REST_MULTIPART_CHUNKSIZE_MIN'] max_size = \ chunk_size * current_app.config['FILES_REST_MULTIPART_MAX_PARTS'] return size > min_csize and size <= max_size def expected_part_size(self, part_number): """Get expected part size for a particular part number.""" last_part = self.multipart.last_part_number if part_number == last_part: return self.multipart.last_part_size elif part_number >= 0 and part_number < last_part: return self.multipart.chunk_size else: <|code_end|> . Use current file imports: import re import sys import uuid from datetime import datetime from flask import current_app from functools import wraps from invenio_db import db from os.path import basename from sqlalchemy.dialects import mysql from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy.orm import validates from sqlalchemy.orm.exc import MultipleResultsFound from sqlalchemy_utils.types import UUIDType from .errors import BucketLockedError, FileInstanceAlreadySetError, \ FileInstanceUnreadableError, FileSizeError, InvalidKeyError, \ InvalidOperationError, MultipartAlreadyCompleted, \ MultipartInvalidChunkSize, MultipartInvalidPartNumber, \ MultipartInvalidSize, MultipartMissingParts, MultipartNotCompleted from .proxies import current_files_rest from .utils import guess_mimetype and context (classes, functions, or code) from other files: # Path: invenio_files_rest/errors.py # class BucketLockedError(InvalidOperationError): # """Exception raised when a bucket is locked.""" # # code = 403 # description = "Bucket is locked for modifications." # # class FileInstanceAlreadySetError(InvalidOperationError): # """Exception raised when file instance already set on object.""" # # class FileInstanceUnreadableError(InvalidOperationError): # """Exception raised when trying to get an unreadable file.""" # # code = 503 # description = "File storage is offline." # # class FileSizeError(StorageError): # """Exception raised when a file larger than allowed.""" # # code = 400 # # class InvalidKeyError(InvalidOperationError): # """Invalid key.""" # # code = 400 # description = "Filename is too long." # # class InvalidOperationError(FilesException): # """Exception raised when an invalid operation is performed.""" # # code = 403 # # class MultipartAlreadyCompleted(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 403 # description = "Multipart upload is already completed." # # class MultipartInvalidChunkSize(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Invalid part size." # # class MultipartInvalidPartNumber(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Invalid part number." # # class MultipartInvalidSize(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Invalid file size." # # class MultipartMissingParts(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Not all parts have been uploaded." # # class MultipartNotCompleted(MultipartException): # """Exception raised when multipart object is not already completed.""" # # code = 400 # description = "Multipart upload is already completed." # # Path: invenio_files_rest/proxies.py # # Path: invenio_files_rest/utils.py # def guess_mimetype(filename): # """Map extra mimetype with the encoding provided. # # :returns: The extra mimetype. # """ # m, encoding = mimetypes.guess_type(filename) # if encoding: # m = ENCODING_MIMETYPES.get(encoding, None) # return m or 'application/octet-stream' . Output only the next line.
raise MultipartInvalidPartNumber()
Given the following code snippet before the placeholder: <|code_start|> self.key, _file_id=self.file_id, version_id=version_id ) self.delete() return obj def delete(self): """Delete a multipart object.""" # Update bucket size. self.bucket.size -= self.size # Remove parts Part.query_by_multipart(self).delete() # Remove self self.query.filter_by(upload_id=self.upload_id).delete() @classmethod def create(cls, bucket, key, size, chunk_size): """Create a new object in a bucket.""" bucket = as_bucket(bucket) if bucket.locked: raise BucketLockedError() # Validate chunk size. if not cls.is_valid_chunksize(chunk_size): raise MultipartInvalidChunkSize() # Validate max theoretical size. if not cls.is_valid_size(size, chunk_size): <|code_end|> , predict the next line using imports from the current file: import re import sys import uuid from datetime import datetime from flask import current_app from functools import wraps from invenio_db import db from os.path import basename from sqlalchemy.dialects import mysql from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy.orm import validates from sqlalchemy.orm.exc import MultipleResultsFound from sqlalchemy_utils.types import UUIDType from .errors import BucketLockedError, FileInstanceAlreadySetError, \ FileInstanceUnreadableError, FileSizeError, InvalidKeyError, \ InvalidOperationError, MultipartAlreadyCompleted, \ MultipartInvalidChunkSize, MultipartInvalidPartNumber, \ MultipartInvalidSize, MultipartMissingParts, MultipartNotCompleted from .proxies import current_files_rest from .utils import guess_mimetype and context including class names, function names, and sometimes code from other files: # Path: invenio_files_rest/errors.py # class BucketLockedError(InvalidOperationError): # """Exception raised when a bucket is locked.""" # # code = 403 # description = "Bucket is locked for modifications." # # class FileInstanceAlreadySetError(InvalidOperationError): # """Exception raised when file instance already set on object.""" # # class FileInstanceUnreadableError(InvalidOperationError): # """Exception raised when trying to get an unreadable file.""" # # code = 503 # description = "File storage is offline." # # class FileSizeError(StorageError): # """Exception raised when a file larger than allowed.""" # # code = 400 # # class InvalidKeyError(InvalidOperationError): # """Invalid key.""" # # code = 400 # description = "Filename is too long." # # class InvalidOperationError(FilesException): # """Exception raised when an invalid operation is performed.""" # # code = 403 # # class MultipartAlreadyCompleted(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 403 # description = "Multipart upload is already completed." # # class MultipartInvalidChunkSize(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Invalid part size." # # class MultipartInvalidPartNumber(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Invalid part number." # # class MultipartInvalidSize(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Invalid file size." # # class MultipartMissingParts(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Not all parts have been uploaded." # # class MultipartNotCompleted(MultipartException): # """Exception raised when multipart object is not already completed.""" # # code = 400 # description = "Multipart upload is already completed." # # Path: invenio_files_rest/proxies.py # # Path: invenio_files_rest/utils.py # def guess_mimetype(filename): # """Map extra mimetype with the encoding provided. # # :returns: The extra mimetype. # """ # m, encoding = mimetypes.guess_type(filename) # if encoding: # m = ENCODING_MIMETYPES.get(encoding, None) # return m or 'application/octet-stream' . Output only the next line.
raise MultipartInvalidSize()
Predict the next line for this snippet: <|code_start|> @staticmethod def is_valid_chunksize(chunk_size): """Check if size is valid.""" min_csize = current_app.config['FILES_REST_MULTIPART_CHUNKSIZE_MIN'] max_csize = current_app.config['FILES_REST_MULTIPART_CHUNKSIZE_MAX'] return chunk_size >= min_csize and chunk_size <= max_csize @staticmethod def is_valid_size(size, chunk_size): """Validate max theoretical size.""" min_csize = current_app.config['FILES_REST_MULTIPART_CHUNKSIZE_MIN'] max_size = \ chunk_size * current_app.config['FILES_REST_MULTIPART_MAX_PARTS'] return size > min_csize and size <= max_size def expected_part_size(self, part_number): """Get expected part size for a particular part number.""" last_part = self.multipart.last_part_number if part_number == last_part: return self.multipart.last_part_size elif part_number >= 0 and part_number < last_part: return self.multipart.chunk_size else: raise MultipartInvalidPartNumber() @ensure_uncompleted() def complete(self): """Mark a multipart object as complete.""" if Part.count(self) != self.last_part_number + 1: <|code_end|> with the help of current file imports: import re import sys import uuid from datetime import datetime from flask import current_app from functools import wraps from invenio_db import db from os.path import basename from sqlalchemy.dialects import mysql from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy.orm import validates from sqlalchemy.orm.exc import MultipleResultsFound from sqlalchemy_utils.types import UUIDType from .errors import BucketLockedError, FileInstanceAlreadySetError, \ FileInstanceUnreadableError, FileSizeError, InvalidKeyError, \ InvalidOperationError, MultipartAlreadyCompleted, \ MultipartInvalidChunkSize, MultipartInvalidPartNumber, \ MultipartInvalidSize, MultipartMissingParts, MultipartNotCompleted from .proxies import current_files_rest from .utils import guess_mimetype and context from other files: # Path: invenio_files_rest/errors.py # class BucketLockedError(InvalidOperationError): # """Exception raised when a bucket is locked.""" # # code = 403 # description = "Bucket is locked for modifications." # # class FileInstanceAlreadySetError(InvalidOperationError): # """Exception raised when file instance already set on object.""" # # class FileInstanceUnreadableError(InvalidOperationError): # """Exception raised when trying to get an unreadable file.""" # # code = 503 # description = "File storage is offline." # # class FileSizeError(StorageError): # """Exception raised when a file larger than allowed.""" # # code = 400 # # class InvalidKeyError(InvalidOperationError): # """Invalid key.""" # # code = 400 # description = "Filename is too long." # # class InvalidOperationError(FilesException): # """Exception raised when an invalid operation is performed.""" # # code = 403 # # class MultipartAlreadyCompleted(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 403 # description = "Multipart upload is already completed." # # class MultipartInvalidChunkSize(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Invalid part size." # # class MultipartInvalidPartNumber(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Invalid part number." # # class MultipartInvalidSize(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Invalid file size." # # class MultipartMissingParts(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Not all parts have been uploaded." # # class MultipartNotCompleted(MultipartException): # """Exception raised when multipart object is not already completed.""" # # code = 400 # description = "Multipart upload is already completed." # # Path: invenio_files_rest/proxies.py # # Path: invenio_files_rest/utils.py # def guess_mimetype(filename): # """Map extra mimetype with the encoding provided. # # :returns: The extra mimetype. # """ # m, encoding = mimetypes.guess_type(filename) # if encoding: # m = ENCODING_MIMETYPES.get(encoding, None) # return m or 'application/octet-stream' , which may contain function names, class names, or code. Output only the next line.
raise MultipartMissingParts()
Based on the snippet: <|code_start|> def to_dict(self): return self.res class ObjectVersionError(object): """Represents an object version level error. .. note:: This is not an actual exception. """ def __init__(self, message): self.res = dict(message=message) def to_dict(self): return self.res ensure_readable = ensure_state( lambda o: o.readable, FileInstanceUnreadableError) """Ensure file is readable.""" ensure_writable = ensure_state( lambda o: o.writable, ValueError, 'File is not writable.') """Ensure file is writeable.""" ensure_completed = ensure_state( lambda o: o.completed, <|code_end|> , predict the immediate next line with the help of imports: import re import sys import uuid from datetime import datetime from flask import current_app from functools import wraps from invenio_db import db from os.path import basename from sqlalchemy.dialects import mysql from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy.orm import validates from sqlalchemy.orm.exc import MultipleResultsFound from sqlalchemy_utils.types import UUIDType from .errors import BucketLockedError, FileInstanceAlreadySetError, \ FileInstanceUnreadableError, FileSizeError, InvalidKeyError, \ InvalidOperationError, MultipartAlreadyCompleted, \ MultipartInvalidChunkSize, MultipartInvalidPartNumber, \ MultipartInvalidSize, MultipartMissingParts, MultipartNotCompleted from .proxies import current_files_rest from .utils import guess_mimetype and context (classes, functions, sometimes code) from other files: # Path: invenio_files_rest/errors.py # class BucketLockedError(InvalidOperationError): # """Exception raised when a bucket is locked.""" # # code = 403 # description = "Bucket is locked for modifications." # # class FileInstanceAlreadySetError(InvalidOperationError): # """Exception raised when file instance already set on object.""" # # class FileInstanceUnreadableError(InvalidOperationError): # """Exception raised when trying to get an unreadable file.""" # # code = 503 # description = "File storage is offline." # # class FileSizeError(StorageError): # """Exception raised when a file larger than allowed.""" # # code = 400 # # class InvalidKeyError(InvalidOperationError): # """Invalid key.""" # # code = 400 # description = "Filename is too long." # # class InvalidOperationError(FilesException): # """Exception raised when an invalid operation is performed.""" # # code = 403 # # class MultipartAlreadyCompleted(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 403 # description = "Multipart upload is already completed." # # class MultipartInvalidChunkSize(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Invalid part size." # # class MultipartInvalidPartNumber(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Invalid part number." # # class MultipartInvalidSize(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Invalid file size." # # class MultipartMissingParts(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Not all parts have been uploaded." # # class MultipartNotCompleted(MultipartException): # """Exception raised when multipart object is not already completed.""" # # code = 400 # description = "Multipart upload is already completed." # # Path: invenio_files_rest/proxies.py # # Path: invenio_files_rest/utils.py # def guess_mimetype(filename): # """Map extra mimetype with the encoding provided. # # :returns: The extra mimetype. # """ # m, encoding = mimetypes.guess_type(filename) # if encoding: # m = ENCODING_MIMETYPES.get(encoding, None) # return m or 'application/octet-stream' . Output only the next line.
MultipartNotCompleted)
Predict the next line after this snippet: <|code_start|> """Lock state of bucket. Modifications are not allowed on a locked bucket. """ deleted = db.Column(db.Boolean(name='deleted'), default=False, nullable=False) """Delete state of bucket.""" location = db.relationship(Location, backref='buckets') """Location associated with this bucket.""" def __repr__(self): """Return representation of location.""" return str(self.id) @property def quota_left(self): """Get how much space is left in the bucket.""" if self.quota_size: return max(self.quota_size - self.size, 0) @property def size_limit(self): """Get size limit for this bucket. The limit is based on the minimum output of the file size limiters. """ limits = [ <|code_end|> using the current file's imports: import re import sys import uuid from datetime import datetime from flask import current_app from functools import wraps from invenio_db import db from os.path import basename from sqlalchemy.dialects import mysql from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy.orm import validates from sqlalchemy.orm.exc import MultipleResultsFound from sqlalchemy_utils.types import UUIDType from .errors import BucketLockedError, FileInstanceAlreadySetError, \ FileInstanceUnreadableError, FileSizeError, InvalidKeyError, \ InvalidOperationError, MultipartAlreadyCompleted, \ MultipartInvalidChunkSize, MultipartInvalidPartNumber, \ MultipartInvalidSize, MultipartMissingParts, MultipartNotCompleted from .proxies import current_files_rest from .utils import guess_mimetype and any relevant context from other files: # Path: invenio_files_rest/errors.py # class BucketLockedError(InvalidOperationError): # """Exception raised when a bucket is locked.""" # # code = 403 # description = "Bucket is locked for modifications." # # class FileInstanceAlreadySetError(InvalidOperationError): # """Exception raised when file instance already set on object.""" # # class FileInstanceUnreadableError(InvalidOperationError): # """Exception raised when trying to get an unreadable file.""" # # code = 503 # description = "File storage is offline." # # class FileSizeError(StorageError): # """Exception raised when a file larger than allowed.""" # # code = 400 # # class InvalidKeyError(InvalidOperationError): # """Invalid key.""" # # code = 400 # description = "Filename is too long." # # class InvalidOperationError(FilesException): # """Exception raised when an invalid operation is performed.""" # # code = 403 # # class MultipartAlreadyCompleted(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 403 # description = "Multipart upload is already completed." # # class MultipartInvalidChunkSize(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Invalid part size." # # class MultipartInvalidPartNumber(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Invalid part number." # # class MultipartInvalidSize(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Invalid file size." # # class MultipartMissingParts(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Not all parts have been uploaded." # # class MultipartNotCompleted(MultipartException): # """Exception raised when multipart object is not already completed.""" # # code = 400 # description = "Multipart upload is already completed." # # Path: invenio_files_rest/proxies.py # # Path: invenio_files_rest/utils.py # def guess_mimetype(filename): # """Map extra mimetype with the encoding provided. # # :returns: The extra mimetype. # """ # m, encoding = mimetypes.guess_type(filename) # if encoding: # m = ENCODING_MIMETYPES.get(encoding, None) # return m or 'application/octet-stream' . Output only the next line.
lim for lim in current_files_rest.file_size_limiters(
Continue the code snippet: <|code_start|> file = db.relationship(FileInstance, backref='objects') """Relationship to file instance.""" __table_args__ = ( db.UniqueConstraint('bucket_id', 'version_id', 'key'), ) @validates('key') def validate_key(self, key, key_): """Validate key.""" return validate_key(key_) def __unicode__(self): """Return unicoded object.""" return u"{0}:{1}:{2}".format( self.bucket_id, self.version_id, self.key) # https://docs.python.org/3.3/howto/pyporting.html#str-unicode if sys.version_info[0] >= 3: # Python 3 def __repr__(self): """Return representation of location.""" return self.__unicode__() else: # Python 2 def __repr__(self): """Return representation of location.""" return self.__unicode__().encode('utf8') @hybrid_property def mimetype(self): """Get MIME type of object.""" <|code_end|> . Use current file imports: import re import sys import uuid from datetime import datetime from flask import current_app from functools import wraps from invenio_db import db from os.path import basename from sqlalchemy.dialects import mysql from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy.orm import validates from sqlalchemy.orm.exc import MultipleResultsFound from sqlalchemy_utils.types import UUIDType from .errors import BucketLockedError, FileInstanceAlreadySetError, \ FileInstanceUnreadableError, FileSizeError, InvalidKeyError, \ InvalidOperationError, MultipartAlreadyCompleted, \ MultipartInvalidChunkSize, MultipartInvalidPartNumber, \ MultipartInvalidSize, MultipartMissingParts, MultipartNotCompleted from .proxies import current_files_rest from .utils import guess_mimetype and context (classes, functions, or code) from other files: # Path: invenio_files_rest/errors.py # class BucketLockedError(InvalidOperationError): # """Exception raised when a bucket is locked.""" # # code = 403 # description = "Bucket is locked for modifications." # # class FileInstanceAlreadySetError(InvalidOperationError): # """Exception raised when file instance already set on object.""" # # class FileInstanceUnreadableError(InvalidOperationError): # """Exception raised when trying to get an unreadable file.""" # # code = 503 # description = "File storage is offline." # # class FileSizeError(StorageError): # """Exception raised when a file larger than allowed.""" # # code = 400 # # class InvalidKeyError(InvalidOperationError): # """Invalid key.""" # # code = 400 # description = "Filename is too long." # # class InvalidOperationError(FilesException): # """Exception raised when an invalid operation is performed.""" # # code = 403 # # class MultipartAlreadyCompleted(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 403 # description = "Multipart upload is already completed." # # class MultipartInvalidChunkSize(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Invalid part size." # # class MultipartInvalidPartNumber(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Invalid part number." # # class MultipartInvalidSize(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Invalid file size." # # class MultipartMissingParts(MultipartException): # """Exception raised when multipart object is already completed.""" # # code = 400 # description = "Not all parts have been uploaded." # # class MultipartNotCompleted(MultipartException): # """Exception raised when multipart object is not already completed.""" # # code = 400 # description = "Multipart upload is already completed." # # Path: invenio_files_rest/proxies.py # # Path: invenio_files_rest/utils.py # def guess_mimetype(filename): # """Map extra mimetype with the encoding provided. # # :returns: The extra mimetype. # """ # m, encoding = mimetypes.guess_type(filename) # if encoding: # m = ENCODING_MIMETYPES.get(encoding, None) # return m or 'application/octet-stream' . Output only the next line.
return self._mimetype if self._mimetype else guess_mimetype(self.key)
Based on the snippet: <|code_start|># -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2019 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Test serializer.""" def test_serialize_pretty(app): """Test pretty JSON.""" class TestSchema(BaseSchema): title = fields.Str(attribute='title') data = {'title': 'test'} context = {'bucket': '11111111-1111-1111-1111-111111111111', 'class': 'TestSchema', 'many': False} serializer_mapping['TestSchema'] = TestSchema # TODO This test should be checked if it shouldn't have # BaseSchema instead of Schema with app.test_request_context(): <|code_end|> , predict the immediate next line with the help of imports: from marshmallow import fields from invenio_files_rest.serializer import BaseSchema, json_serializer, \ serializer_mapping and context (classes, functions, sometimes code) from other files: # Path: invenio_files_rest/serializer.py # class BaseSchema(InvenioRestBaseSchema): # class BucketSchema(BaseSchema): # class ObjectVersionSchema(BaseSchema): # class MultipartObjectSchema(BaseSchema): # class PartSchema(BaseSchema): # def dump_links(self, o): # def dump_links(self, o): # def dump_tags(self, o): # def dump_links(self, o): # def wrap(self, data, many): # def dump_links(self, o): # def wrap(self, data, many): # def schema_from_context(context, serializer_mapping): # def _format_args(): # def wait_for_taskresult(task_result, content, interval, max_rounds): # def _whitespace_waiting(): # def json_serializer(data=None, code=200, headers=None, context=None, # etag=None, task_result=None, # serializer_mapping=serializer_mapping, view_name=None): . Output only the next line.
assert json_serializer(data=data, context=context).data == \
Based on the snippet: <|code_start|># -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2019 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Test serializer.""" def test_serialize_pretty(app): """Test pretty JSON.""" class TestSchema(BaseSchema): title = fields.Str(attribute='title') data = {'title': 'test'} context = {'bucket': '11111111-1111-1111-1111-111111111111', 'class': 'TestSchema', 'many': False} <|code_end|> , predict the immediate next line with the help of imports: from marshmallow import fields from invenio_files_rest.serializer import BaseSchema, json_serializer, \ serializer_mapping and context (classes, functions, sometimes code) from other files: # Path: invenio_files_rest/serializer.py # class BaseSchema(InvenioRestBaseSchema): # class BucketSchema(BaseSchema): # class ObjectVersionSchema(BaseSchema): # class MultipartObjectSchema(BaseSchema): # class PartSchema(BaseSchema): # def dump_links(self, o): # def dump_links(self, o): # def dump_tags(self, o): # def dump_links(self, o): # def wrap(self, data, many): # def dump_links(self, o): # def wrap(self, data, many): # def schema_from_context(context, serializer_mapping): # def _format_args(): # def wait_for_taskresult(task_result, content, interval, max_rounds): # def _whitespace_waiting(): # def json_serializer(data=None, code=200, headers=None, context=None, # etag=None, task_result=None, # serializer_mapping=serializer_mapping, view_name=None): . Output only the next line.
serializer_mapping['TestSchema'] = TestSchema
Using the snippet: <|code_start|>def bucket(): """Manage buckets.""" @bucket.command() @with_appcontext def touch(): """Create new bucket.""" bucket = Bucket.create() db.session.commit() click.secho(str(bucket), fg='green') @bucket.command() @click.argument('source', type=click.Path(exists=True, resolve_path=True)) @click.argument('bucket') @click.option('--checksum/--no-checksum', default=False) @click.option('--key-prefix', default='') @with_appcontext def cp(source, bucket, checksum, key_prefix): """Create new bucket from all files in directory.""" for object_version in populate_from_path( Bucket.get(bucket), source, checksum=checksum, key_prefix=key_prefix): click.secho(str(object_version)) db.session.commit() def _unset_default_location(): """Unset default location, if there is one.""" <|code_end|> , determine the next line of code. You have imports: import click from click_default_group import DefaultGroup from flask.cli import with_appcontext from invenio_db import db from .models import Location from .models import Bucket from .helpers import populate_from_path from .models import Bucket and context (class names, function names, or code) available: # Path: invenio_files_rest/models.py # class Location(db.Model, Timestamp): # """Model defining base locations.""" # # __tablename__ = 'files_location' # # id = db.Column(db.Integer, primary_key=True) # """Internal identifier for locations. # # The internal identifier is used only used as foreign key for buckets in # order to decrease storage requirements per row for buckets. # """ # # name = db.Column(db.String(20), unique=True, nullable=False) # """External identifier of the location.""" # # uri = db.Column(db.String(255), nullable=False) # """URI of the location.""" # # default = db.Column(db.Boolean(name='default'), # nullable=False, # default=False) # """True if the location is the default location. # # At least one location should be the default location. # """ # # @validates('name') # def validate_name(self, key, name): # """Validate name.""" # if not slug_pattern.match(name) or len(name) > 20: # raise ValueError( # 'Invalid location name (lower-case alphanumeric + dashes).') # return name # # @classmethod # def get_by_name(cls, name): # """Fetch a specific location object.""" # return cls.query.filter_by( # name=name, # ).one_or_none() # # @classmethod # def get_default(cls): # """Fetch the default location object.""" # try: # return cls.query.filter_by(default=True).one_or_none() # except MultipleResultsFound: # return None # # @classmethod # def all(cls): # """Return query that fetches all locations.""" # return Location.query.all() # # def __repr__(self): # """Return representation of location.""" # return self.name . Output only the next line.
default_location = Location.get_default()
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2016-2019 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Test CLI.""" def test_simple_workflow(app, db, tmpdir): """Run simple workflow.""" runner = CliRunner() script_info = ScriptInfo(create_app=lambda info: app) source = os.path.join(os.path.dirname(__file__), 'fixtures', 'source') # Create a location to use <|code_end|> , predict the next line using imports from the current file: import os from click.testing import CliRunner from flask.cli import ScriptInfo from invenio_files_rest.cli import files as cmd and context including class names, function names, and sometimes code from other files: # Path: invenio_files_rest/cli.py # @click.group() # def files(): # """File management commands.""" . Output only the next line.
result = runner.invoke(cmd, [
Predict the next line after this snippet: <|code_start|> Factories that reads ``request.stream`` directly must be first in the list, otherwise Werkzeug's form-data parser will read the stream. """ FILES_REST_MULTIPART_MAX_PARTS = 10000 """Maximum number of parts when uploading files with multipart uploads.""" FILES_REST_MULTIPART_CHUNKSIZE_MIN = 5 * 1024 * 1024 # 5 MiB """Minimum chunk size in bytes of multipart objects.""" FILES_REST_MULTIPART_CHUNKSIZE_MAX = 5 * 1024 * 1024 * 1024 # 5 GiB """Maximum chunk size in bytes of multipart objects.""" FILES_REST_MULTIPART_EXPIRES = timedelta(days=4) """Time delta after which a multipart upload is considered expired.""" FILES_REST_TASK_WAIT_INTERVAL = 2 """Interval in seconds between sending a whitespace to not close connection.""" FILES_REST_TASK_WAIT_MAX_SECONDS = 600 """Maximum number of seconds to wait for a task to finish.""" FILES_REST_FILE_TAGS_HEADER = 'X-Invenio-File-Tags' """Header for updating file tags.""" FILES_REST_XSENDFILE_ENABLED = False """Use the X-Accel-Redirect header to stream the file through a reverse proxy( e.g NGINX).""" FILES_REST_XSENDFILE_RESPONSE_FUNC = \ <|code_end|> using the current file's imports: from datetime import timedelta from invenio_files_rest.helpers import create_file_streaming_redirect_response and any relevant context from other files: # Path: invenio_files_rest/helpers.py # def create_file_streaming_redirect_response(obj): # """Redirect response generating function.""" # warnings.warn('This streaming does not support multiple storage backends.') # response = make_response() # redirect_url_base = '/user_files/' # redirect_url_key = urlsplit(obj.file.uri).path # response.headers['X-Accel-Redirect'] = redirect_url_base + \ # redirect_url_key[1:] # return response . Output only the next line.
create_file_streaming_redirect_response
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2015-2019 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Module tests.""" def test_version(): """Test version import.""" assert __version__ def test_init(): """Test extension initialization.""" app = Flask('testapp') <|code_end|> . Use current file imports: import pytest from flask import Flask, current_app from invenio_files_rest import InvenioFilesREST from invenio_files_rest import __version__ and context (classes, functions, or code) from other files: # Path: invenio_files_rest/ext.py # class InvenioFilesREST(object): # """Invenio-Files-REST extension.""" # # def __init__(self, app=None): # """Extension initialization.""" # if app: # self.init_app(app) # # def init_app(self, app): # """Flask application initialization.""" # self.init_config(app) # if hasattr(app, 'cli'): # app.cli.add_command(files_cmd) # app.extensions['invenio-files-rest'] = _FilesRESTState(app) # # def init_config(self, app): # """Initialize configuration.""" # for k in dir(config): # if k.startswith('FILES_REST_'): # app.config.setdefault(k, getattr(config, k)) . Output only the next line.
ext = InvenioFilesREST(app)
Next line prediction: <|code_start|># -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2015-2019 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Form data parser customization. Flask and Werkzeug by default checks a request's content length against ``MAX_CONTENT_LENGTH`` configuration variable as soon as *any* content type is specified in the request and not only when a form data content type is specified. This behavior prevents both setting a MAX_CONTENT_LENGTH for form data *and* allowing streaming uploads of large binary files. In order to allow for both max content length checking and streaming uploads of large files, we provide a custom form data parser which only checks the content length if a form data content type is specified. The custom form data parser is installed by using the custom Flask application class provided provided in this module. """ class Flask(FlaskBase): """Flask application class needed to use custom request class.""" <|code_end|> . Use current file imports: (from flask import Flask as FlaskBase from .wrappers import Request) and context including class names, function names, or small code snippets from other files: # Path: invenio_files_rest/wrappers.py # class Request(RequestBase): # """Custom request class needed for using custom form data parser.""" # # form_data_parser_class = FormDataParser . Output only the next line.
request_class = Request
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2016-2019 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Test file signals.""" def test_signals(app, client, headers, bucket, permissions): """Test file_uploaded and file_deleted signals.""" login_user(client, permissions['bucket']) key = 'myfile.txt' data = b'content of my file' object_url = url_for( 'invenio_files_rest.object_api', bucket_id=bucket.id, key=key) calls = [] def upload_listener(sender, obj=None): calls.append("file-uploaded") def delete_listener(sender, obj=None): calls.append("file-deleted") file_uploaded.connect(upload_listener, weak=False) <|code_end|> . Write the next line using the current file imports: from flask import url_for from io import BytesIO from testutils import login_user from invenio_files_rest.signals import file_deleted, file_uploaded and context from other files: # Path: invenio_files_rest/signals.py , which may include functions, classes, or code. Output only the next line.
file_deleted.connect(delete_listener, weak=False)
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2016-2019 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Test file signals.""" def test_signals(app, client, headers, bucket, permissions): """Test file_uploaded and file_deleted signals.""" login_user(client, permissions['bucket']) key = 'myfile.txt' data = b'content of my file' object_url = url_for( 'invenio_files_rest.object_api', bucket_id=bucket.id, key=key) calls = [] def upload_listener(sender, obj=None): calls.append("file-uploaded") def delete_listener(sender, obj=None): calls.append("file-deleted") <|code_end|> . Use current file imports: from flask import url_for from io import BytesIO from testutils import login_user from invenio_files_rest.signals import file_deleted, file_uploaded and context (classes, functions, or code) from other files: # Path: invenio_files_rest/signals.py . Output only the next line.
file_uploaded.connect(upload_listener, weak=False)
Next line prediction: <|code_start|>"""example URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', IndexView.as_view(), name='index'), # Login url(r'^accounts/login/$', auth_views.login, {'template_name': 'login.html'}, name='login'), url(r'^logout/$', auth_views.logout, {'template_name': 'logged_out.html'}, name='logout'), # Live job status url(r'^example/$', ExampleJobStatusView.as_view(), name='example'), <|code_end|> . Use current file imports: (from django.conf.urls import include, url from django.conf.urls.static import static from django.conf import settings from django.contrib import admin from django.contrib.auth import views as auth_views from .views import (ExampleJobLogView, ExampleJobStatusView, IndexView, JobDetail, JobList, ServerDetail, ServerList)) and context including class names, function names, or small code snippets from other files: # Path: example/server/views.py # class ExampleJobLogView(LoginRequiredMixin, TemplateView): # template_name = 'example_job_log.html' # # def get_context_data(self, **kwargs): # context = super(ExampleJobLogView, self).get_context_data(**kwargs) # context['job_pk'] = kwargs['job_pk'] # return context # # class ExampleJobStatusView(LoginRequiredMixin, TemplateView): # template_name = 'example_job_status.html' # # def post(self, request, *args, **kwargs): # (interpreter, _) = Interpreter.objects.get_or_create( # name='Python', # path=settings.EXAMPLE_PYTHON_PATH, # arguments=settings.EXAMPLE_PYTHON_ARGUMENTS, # ) # # (server, _) = Server.objects.get_or_create( # title='Example Server', # hostname=settings.EXAMPLE_SERVER_HOSTNAME, # port=settings.EXAMPLE_SERVER_PORT, # ) # # logger.debug("Running job in {} using {}".format(server, interpreter)) # # num_jobs = len(Job.objects.all()) # # program = textwrap.dedent('''\ # from __future__ import print_function # import time # for i in range(10): # with open('django_remote_submission_example_out_{}.txt'.format(i), 'wt') as f: # print('Line {}'.format(i), file=f) # print('Line {}'.format(i)) # time.sleep(1) # ''') # # (job, _) = Job.objects.get_or_create( # title='Example Job #{}'.format(num_jobs), # program=program, # remote_directory=settings.EXAMPLE_REMOTE_DIRECTORY, # remote_filename=settings.EXAMPLE_REMOTE_FILENAME, # owner=request.user, # server=server, # interpreter=interpreter, # ) # # submit_job_to_server.delay( # job_pk=job.pk, # password=settings.EXAMPLE_REMOTE_PASSWORD, # username=settings.EXAMPLE_REMOTE_USER, # ) # # return HttpResponse('success') # # class IndexView(LoginRequiredMixin, TemplateView): # template_name = "index.html" # # def get_context_data(self, **kwargs): # context = super(IndexView, self).get_context_data(**kwargs) # context['job_list'] = Job.objects.all() # context['server_list'] = Server.objects.all() # context['Log_list'] = Log.objects.all() # return context # # class JobDetail(LoginRequiredMixin, DetailView): # model = Job # # class JobList(LoginRequiredMixin, ListView): # model = Job # # class ServerDetail(LoginRequiredMixin, DetailView): # model = Server # # class ServerList(LoginRequiredMixin, ListView): # model = Server . Output only the next line.
url(r'^logs/(?P<job_pk>[0-9]+)/$', ExampleJobLogView.as_view(), name='logs'),
Next line prediction: <|code_start|>"""example URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', IndexView.as_view(), name='index'), # Login url(r'^accounts/login/$', auth_views.login, {'template_name': 'login.html'}, name='login'), url(r'^logout/$', auth_views.logout, {'template_name': 'logged_out.html'}, name='logout'), # Live job status <|code_end|> . Use current file imports: (from django.conf.urls import include, url from django.conf.urls.static import static from django.conf import settings from django.contrib import admin from django.contrib.auth import views as auth_views from .views import (ExampleJobLogView, ExampleJobStatusView, IndexView, JobDetail, JobList, ServerDetail, ServerList)) and context including class names, function names, or small code snippets from other files: # Path: example/server/views.py # class ExampleJobLogView(LoginRequiredMixin, TemplateView): # template_name = 'example_job_log.html' # # def get_context_data(self, **kwargs): # context = super(ExampleJobLogView, self).get_context_data(**kwargs) # context['job_pk'] = kwargs['job_pk'] # return context # # class ExampleJobStatusView(LoginRequiredMixin, TemplateView): # template_name = 'example_job_status.html' # # def post(self, request, *args, **kwargs): # (interpreter, _) = Interpreter.objects.get_or_create( # name='Python', # path=settings.EXAMPLE_PYTHON_PATH, # arguments=settings.EXAMPLE_PYTHON_ARGUMENTS, # ) # # (server, _) = Server.objects.get_or_create( # title='Example Server', # hostname=settings.EXAMPLE_SERVER_HOSTNAME, # port=settings.EXAMPLE_SERVER_PORT, # ) # # logger.debug("Running job in {} using {}".format(server, interpreter)) # # num_jobs = len(Job.objects.all()) # # program = textwrap.dedent('''\ # from __future__ import print_function # import time # for i in range(10): # with open('django_remote_submission_example_out_{}.txt'.format(i), 'wt') as f: # print('Line {}'.format(i), file=f) # print('Line {}'.format(i)) # time.sleep(1) # ''') # # (job, _) = Job.objects.get_or_create( # title='Example Job #{}'.format(num_jobs), # program=program, # remote_directory=settings.EXAMPLE_REMOTE_DIRECTORY, # remote_filename=settings.EXAMPLE_REMOTE_FILENAME, # owner=request.user, # server=server, # interpreter=interpreter, # ) # # submit_job_to_server.delay( # job_pk=job.pk, # password=settings.EXAMPLE_REMOTE_PASSWORD, # username=settings.EXAMPLE_REMOTE_USER, # ) # # return HttpResponse('success') # # class IndexView(LoginRequiredMixin, TemplateView): # template_name = "index.html" # # def get_context_data(self, **kwargs): # context = super(IndexView, self).get_context_data(**kwargs) # context['job_list'] = Job.objects.all() # context['server_list'] = Server.objects.all() # context['Log_list'] = Log.objects.all() # return context # # class JobDetail(LoginRequiredMixin, DetailView): # model = Job # # class JobList(LoginRequiredMixin, ListView): # model = Job # # class ServerDetail(LoginRequiredMixin, DetailView): # model = Server # # class ServerList(LoginRequiredMixin, ListView): # model = Server . Output only the next line.
url(r'^example/$', ExampleJobStatusView.as_view(), name='example'),
Continue the code snippet: <|code_start|>"""example URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ urlpatterns = [ url(r'^admin/', admin.site.urls), <|code_end|> . Use current file imports: from django.conf.urls import include, url from django.conf.urls.static import static from django.conf import settings from django.contrib import admin from django.contrib.auth import views as auth_views from .views import (ExampleJobLogView, ExampleJobStatusView, IndexView, JobDetail, JobList, ServerDetail, ServerList) and context (classes, functions, or code) from other files: # Path: example/server/views.py # class ExampleJobLogView(LoginRequiredMixin, TemplateView): # template_name = 'example_job_log.html' # # def get_context_data(self, **kwargs): # context = super(ExampleJobLogView, self).get_context_data(**kwargs) # context['job_pk'] = kwargs['job_pk'] # return context # # class ExampleJobStatusView(LoginRequiredMixin, TemplateView): # template_name = 'example_job_status.html' # # def post(self, request, *args, **kwargs): # (interpreter, _) = Interpreter.objects.get_or_create( # name='Python', # path=settings.EXAMPLE_PYTHON_PATH, # arguments=settings.EXAMPLE_PYTHON_ARGUMENTS, # ) # # (server, _) = Server.objects.get_or_create( # title='Example Server', # hostname=settings.EXAMPLE_SERVER_HOSTNAME, # port=settings.EXAMPLE_SERVER_PORT, # ) # # logger.debug("Running job in {} using {}".format(server, interpreter)) # # num_jobs = len(Job.objects.all()) # # program = textwrap.dedent('''\ # from __future__ import print_function # import time # for i in range(10): # with open('django_remote_submission_example_out_{}.txt'.format(i), 'wt') as f: # print('Line {}'.format(i), file=f) # print('Line {}'.format(i)) # time.sleep(1) # ''') # # (job, _) = Job.objects.get_or_create( # title='Example Job #{}'.format(num_jobs), # program=program, # remote_directory=settings.EXAMPLE_REMOTE_DIRECTORY, # remote_filename=settings.EXAMPLE_REMOTE_FILENAME, # owner=request.user, # server=server, # interpreter=interpreter, # ) # # submit_job_to_server.delay( # job_pk=job.pk, # password=settings.EXAMPLE_REMOTE_PASSWORD, # username=settings.EXAMPLE_REMOTE_USER, # ) # # return HttpResponse('success') # # class IndexView(LoginRequiredMixin, TemplateView): # template_name = "index.html" # # def get_context_data(self, **kwargs): # context = super(IndexView, self).get_context_data(**kwargs) # context['job_list'] = Job.objects.all() # context['server_list'] = Server.objects.all() # context['Log_list'] = Log.objects.all() # return context # # class JobDetail(LoginRequiredMixin, DetailView): # model = Job # # class JobList(LoginRequiredMixin, ListView): # model = Job # # class ServerDetail(LoginRequiredMixin, DetailView): # model = Server # # class ServerList(LoginRequiredMixin, ListView): # model = Server . Output only the next line.
url(r'^$', IndexView.as_view(), name='index'),
Next line prediction: <|code_start|>"""example URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', IndexView.as_view(), name='index'), # Login url(r'^accounts/login/$', auth_views.login, {'template_name': 'login.html'}, name='login'), url(r'^logout/$', auth_views.logout, {'template_name': 'logged_out.html'}, name='logout'), # Live job status url(r'^example/$', ExampleJobStatusView.as_view(), name='example'), url(r'^logs/(?P<job_pk>[0-9]+)/$', ExampleJobLogView.as_view(), name='logs'), url(r'^servers/$', ServerList.as_view(), name='server-list'), url(r'^servers/(?P<pk>[0-9]+)/$', ServerDetail.as_view(), name='server-detail'), <|code_end|> . Use current file imports: (from django.conf.urls import include, url from django.conf.urls.static import static from django.conf import settings from django.contrib import admin from django.contrib.auth import views as auth_views from .views import (ExampleJobLogView, ExampleJobStatusView, IndexView, JobDetail, JobList, ServerDetail, ServerList)) and context including class names, function names, or small code snippets from other files: # Path: example/server/views.py # class ExampleJobLogView(LoginRequiredMixin, TemplateView): # template_name = 'example_job_log.html' # # def get_context_data(self, **kwargs): # context = super(ExampleJobLogView, self).get_context_data(**kwargs) # context['job_pk'] = kwargs['job_pk'] # return context # # class ExampleJobStatusView(LoginRequiredMixin, TemplateView): # template_name = 'example_job_status.html' # # def post(self, request, *args, **kwargs): # (interpreter, _) = Interpreter.objects.get_or_create( # name='Python', # path=settings.EXAMPLE_PYTHON_PATH, # arguments=settings.EXAMPLE_PYTHON_ARGUMENTS, # ) # # (server, _) = Server.objects.get_or_create( # title='Example Server', # hostname=settings.EXAMPLE_SERVER_HOSTNAME, # port=settings.EXAMPLE_SERVER_PORT, # ) # # logger.debug("Running job in {} using {}".format(server, interpreter)) # # num_jobs = len(Job.objects.all()) # # program = textwrap.dedent('''\ # from __future__ import print_function # import time # for i in range(10): # with open('django_remote_submission_example_out_{}.txt'.format(i), 'wt') as f: # print('Line {}'.format(i), file=f) # print('Line {}'.format(i)) # time.sleep(1) # ''') # # (job, _) = Job.objects.get_or_create( # title='Example Job #{}'.format(num_jobs), # program=program, # remote_directory=settings.EXAMPLE_REMOTE_DIRECTORY, # remote_filename=settings.EXAMPLE_REMOTE_FILENAME, # owner=request.user, # server=server, # interpreter=interpreter, # ) # # submit_job_to_server.delay( # job_pk=job.pk, # password=settings.EXAMPLE_REMOTE_PASSWORD, # username=settings.EXAMPLE_REMOTE_USER, # ) # # return HttpResponse('success') # # class IndexView(LoginRequiredMixin, TemplateView): # template_name = "index.html" # # def get_context_data(self, **kwargs): # context = super(IndexView, self).get_context_data(**kwargs) # context['job_list'] = Job.objects.all() # context['server_list'] = Server.objects.all() # context['Log_list'] = Log.objects.all() # return context # # class JobDetail(LoginRequiredMixin, DetailView): # model = Job # # class JobList(LoginRequiredMixin, ListView): # model = Job # # class ServerDetail(LoginRequiredMixin, DetailView): # model = Server # # class ServerList(LoginRequiredMixin, ListView): # model = Server . Output only the next line.
url(r'^jobs/$', JobList.as_view(), name='job-list'),
Based on the snippet: <|code_start|>"""example URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', IndexView.as_view(), name='index'), # Login url(r'^accounts/login/$', auth_views.login, {'template_name': 'login.html'}, name='login'), url(r'^logout/$', auth_views.logout, {'template_name': 'logged_out.html'}, name='logout'), # Live job status url(r'^example/$', ExampleJobStatusView.as_view(), name='example'), url(r'^logs/(?P<job_pk>[0-9]+)/$', ExampleJobLogView.as_view(), name='logs'), url(r'^servers/$', ServerList.as_view(), name='server-list'), <|code_end|> , predict the immediate next line with the help of imports: from django.conf.urls import include, url from django.conf.urls.static import static from django.conf import settings from django.contrib import admin from django.contrib.auth import views as auth_views from .views import (ExampleJobLogView, ExampleJobStatusView, IndexView, JobDetail, JobList, ServerDetail, ServerList) and context (classes, functions, sometimes code) from other files: # Path: example/server/views.py # class ExampleJobLogView(LoginRequiredMixin, TemplateView): # template_name = 'example_job_log.html' # # def get_context_data(self, **kwargs): # context = super(ExampleJobLogView, self).get_context_data(**kwargs) # context['job_pk'] = kwargs['job_pk'] # return context # # class ExampleJobStatusView(LoginRequiredMixin, TemplateView): # template_name = 'example_job_status.html' # # def post(self, request, *args, **kwargs): # (interpreter, _) = Interpreter.objects.get_or_create( # name='Python', # path=settings.EXAMPLE_PYTHON_PATH, # arguments=settings.EXAMPLE_PYTHON_ARGUMENTS, # ) # # (server, _) = Server.objects.get_or_create( # title='Example Server', # hostname=settings.EXAMPLE_SERVER_HOSTNAME, # port=settings.EXAMPLE_SERVER_PORT, # ) # # logger.debug("Running job in {} using {}".format(server, interpreter)) # # num_jobs = len(Job.objects.all()) # # program = textwrap.dedent('''\ # from __future__ import print_function # import time # for i in range(10): # with open('django_remote_submission_example_out_{}.txt'.format(i), 'wt') as f: # print('Line {}'.format(i), file=f) # print('Line {}'.format(i)) # time.sleep(1) # ''') # # (job, _) = Job.objects.get_or_create( # title='Example Job #{}'.format(num_jobs), # program=program, # remote_directory=settings.EXAMPLE_REMOTE_DIRECTORY, # remote_filename=settings.EXAMPLE_REMOTE_FILENAME, # owner=request.user, # server=server, # interpreter=interpreter, # ) # # submit_job_to_server.delay( # job_pk=job.pk, # password=settings.EXAMPLE_REMOTE_PASSWORD, # username=settings.EXAMPLE_REMOTE_USER, # ) # # return HttpResponse('success') # # class IndexView(LoginRequiredMixin, TemplateView): # template_name = "index.html" # # def get_context_data(self, **kwargs): # context = super(IndexView, self).get_context_data(**kwargs) # context['job_list'] = Job.objects.all() # context['server_list'] = Server.objects.all() # context['Log_list'] = Log.objects.all() # return context # # class JobDetail(LoginRequiredMixin, DetailView): # model = Job # # class JobList(LoginRequiredMixin, ListView): # model = Job # # class ServerDetail(LoginRequiredMixin, DetailView): # model = Server # # class ServerList(LoginRequiredMixin, ListView): # model = Server . Output only the next line.
url(r'^servers/(?P<pk>[0-9]+)/$', ServerDetail.as_view(), name='server-detail'),
Based on the snippet: <|code_start|>"""example URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', IndexView.as_view(), name='index'), # Login url(r'^accounts/login/$', auth_views.login, {'template_name': 'login.html'}, name='login'), url(r'^logout/$', auth_views.logout, {'template_name': 'logged_out.html'}, name='logout'), # Live job status url(r'^example/$', ExampleJobStatusView.as_view(), name='example'), url(r'^logs/(?P<job_pk>[0-9]+)/$', ExampleJobLogView.as_view(), name='logs'), <|code_end|> , predict the immediate next line with the help of imports: from django.conf.urls import include, url from django.conf.urls.static import static from django.conf import settings from django.contrib import admin from django.contrib.auth import views as auth_views from .views import (ExampleJobLogView, ExampleJobStatusView, IndexView, JobDetail, JobList, ServerDetail, ServerList) and context (classes, functions, sometimes code) from other files: # Path: example/server/views.py # class ExampleJobLogView(LoginRequiredMixin, TemplateView): # template_name = 'example_job_log.html' # # def get_context_data(self, **kwargs): # context = super(ExampleJobLogView, self).get_context_data(**kwargs) # context['job_pk'] = kwargs['job_pk'] # return context # # class ExampleJobStatusView(LoginRequiredMixin, TemplateView): # template_name = 'example_job_status.html' # # def post(self, request, *args, **kwargs): # (interpreter, _) = Interpreter.objects.get_or_create( # name='Python', # path=settings.EXAMPLE_PYTHON_PATH, # arguments=settings.EXAMPLE_PYTHON_ARGUMENTS, # ) # # (server, _) = Server.objects.get_or_create( # title='Example Server', # hostname=settings.EXAMPLE_SERVER_HOSTNAME, # port=settings.EXAMPLE_SERVER_PORT, # ) # # logger.debug("Running job in {} using {}".format(server, interpreter)) # # num_jobs = len(Job.objects.all()) # # program = textwrap.dedent('''\ # from __future__ import print_function # import time # for i in range(10): # with open('django_remote_submission_example_out_{}.txt'.format(i), 'wt') as f: # print('Line {}'.format(i), file=f) # print('Line {}'.format(i)) # time.sleep(1) # ''') # # (job, _) = Job.objects.get_or_create( # title='Example Job #{}'.format(num_jobs), # program=program, # remote_directory=settings.EXAMPLE_REMOTE_DIRECTORY, # remote_filename=settings.EXAMPLE_REMOTE_FILENAME, # owner=request.user, # server=server, # interpreter=interpreter, # ) # # submit_job_to_server.delay( # job_pk=job.pk, # password=settings.EXAMPLE_REMOTE_PASSWORD, # username=settings.EXAMPLE_REMOTE_USER, # ) # # return HttpResponse('success') # # class IndexView(LoginRequiredMixin, TemplateView): # template_name = "index.html" # # def get_context_data(self, **kwargs): # context = super(IndexView, self).get_context_data(**kwargs) # context['job_list'] = Job.objects.all() # context['server_list'] = Server.objects.all() # context['Log_list'] = Log.objects.all() # return context # # class JobDetail(LoginRequiredMixin, DetailView): # model = Job # # class JobList(LoginRequiredMixin, ListView): # model = Job # # class ServerDetail(LoginRequiredMixin, DetailView): # model = Server # # class ServerList(LoginRequiredMixin, ListView): # model = Server . Output only the next line.
url(r'^servers/$', ServerList.as_view(), name='server-list'),
Continue the code snippet: <|code_start|>"""Provide default route mappings for serializers.""" # -*- coding: utf-8 -*- router = DefaultRouter() router.register(r'servers', ServerViewSet) router.register(r'jobs', JobViewSet) <|code_end|> . Use current file imports: from rest_framework.routers import DefaultRouter from django.conf.urls import url from .views import ( ServerViewSet, JobViewSet, LogViewSet, JobUserStatus, ResultViewSet ) and context (classes, functions, or code) from other files: # Path: django_remote_submission/views.py # class ServerViewSet(viewsets.ModelViewSet): # """Allow users to create, read, and update :class:`Server` instances.""" # # queryset = Server.objects.all() # serializer_class = ServerSerializer # permission_classes = (IsAuthenticatedOrReadOnly,) # filter_backends = (DjangoFilterBackend,) # filter_fields = ('title', 'hostname', 'port') # pagination_class = StandardPagination # # class JobViewSet(viewsets.ModelViewSet): # """Allow users to create, read, and update :class:`Job` instances.""" # # queryset = Job.objects.all() # serializer_class = JobSerializer # permission_classes = (IsAuthenticatedOrReadOnly,) # filter_backends = (DjangoFilterBackend,) # filter_fields = ('title', 'program', 'status', 'owner', 'server') # pagination_class = StandardPagination # # class LogViewSet(viewsets.ModelViewSet): # """Allow users to create, read, and update :class:`Log` instances.""" # # queryset = Log.objects.all() # serializer_class = LogSerializer # permission_classes = (IsAuthenticatedOrReadOnly,) # filter_backends = (DjangoFilterBackend,) # filter_fields = ('time', 'content', 'stream', 'job') # pagination_class = StandardPagination # # class JobUserStatus(TemplateView): # """Show status of all of user's jobs with live updates.""" # # template_name = "django_remote_submission/job-user-status.html" # # class ResultViewSet(viewsets.ModelViewSet): # """Allow users to create, read, and update :class:`Result` instances.""" # # queryset = Result.objects.all() # serializer_class = ResultSerializer # permission_classes = (IsAuthenticatedOrReadOnly,) # filter_backends = (DjangoFilterBackend,) # filter_fields = ('remote_filename', 'job') # 'local_file', # pagination_class = StandardPagination # # class Meta: # filter_overrides = { # models.FileField: { # 'filter_class': django_filters.CharFilter, # 'extra': lambda f: { # 'lookup_expr': 'icontains', # }, # }, # } . Output only the next line.
router.register(r'logs', LogViewSet)
Predict the next line for this snippet: <|code_start|>"""Provide default route mappings for serializers.""" # -*- coding: utf-8 -*- router = DefaultRouter() router.register(r'servers', ServerViewSet) router.register(r'jobs', JobViewSet) router.register(r'logs', LogViewSet) router.register(r'results', ResultViewSet) urlpatterns = router.urls + [ <|code_end|> with the help of current file imports: from rest_framework.routers import DefaultRouter from django.conf.urls import url from .views import ( ServerViewSet, JobViewSet, LogViewSet, JobUserStatus, ResultViewSet ) and context from other files: # Path: django_remote_submission/views.py # class ServerViewSet(viewsets.ModelViewSet): # """Allow users to create, read, and update :class:`Server` instances.""" # # queryset = Server.objects.all() # serializer_class = ServerSerializer # permission_classes = (IsAuthenticatedOrReadOnly,) # filter_backends = (DjangoFilterBackend,) # filter_fields = ('title', 'hostname', 'port') # pagination_class = StandardPagination # # class JobViewSet(viewsets.ModelViewSet): # """Allow users to create, read, and update :class:`Job` instances.""" # # queryset = Job.objects.all() # serializer_class = JobSerializer # permission_classes = (IsAuthenticatedOrReadOnly,) # filter_backends = (DjangoFilterBackend,) # filter_fields = ('title', 'program', 'status', 'owner', 'server') # pagination_class = StandardPagination # # class LogViewSet(viewsets.ModelViewSet): # """Allow users to create, read, and update :class:`Log` instances.""" # # queryset = Log.objects.all() # serializer_class = LogSerializer # permission_classes = (IsAuthenticatedOrReadOnly,) # filter_backends = (DjangoFilterBackend,) # filter_fields = ('time', 'content', 'stream', 'job') # pagination_class = StandardPagination # # class JobUserStatus(TemplateView): # """Show status of all of user's jobs with live updates.""" # # template_name = "django_remote_submission/job-user-status.html" # # class ResultViewSet(viewsets.ModelViewSet): # """Allow users to create, read, and update :class:`Result` instances.""" # # queryset = Result.objects.all() # serializer_class = ResultSerializer # permission_classes = (IsAuthenticatedOrReadOnly,) # filter_backends = (DjangoFilterBackend,) # filter_fields = ('remote_filename', 'job') # 'local_file', # pagination_class = StandardPagination # # class Meta: # filter_overrides = { # models.FileField: { # 'filter_class': django_filters.CharFilter, # 'extra': lambda f: { # 'lookup_expr': 'icontains', # }, # }, # } , which may contain function names, class names, or code. Output only the next line.
url(r'^job-user-status/$', JobUserStatus.as_view()),
Given snippet: <|code_start|>"""Provide default route mappings for serializers.""" # -*- coding: utf-8 -*- router = DefaultRouter() router.register(r'servers', ServerViewSet) router.register(r'jobs', JobViewSet) router.register(r'logs', LogViewSet) <|code_end|> , continue by predicting the next line. Consider current file imports: from rest_framework.routers import DefaultRouter from django.conf.urls import url from .views import ( ServerViewSet, JobViewSet, LogViewSet, JobUserStatus, ResultViewSet ) and context: # Path: django_remote_submission/views.py # class ServerViewSet(viewsets.ModelViewSet): # """Allow users to create, read, and update :class:`Server` instances.""" # # queryset = Server.objects.all() # serializer_class = ServerSerializer # permission_classes = (IsAuthenticatedOrReadOnly,) # filter_backends = (DjangoFilterBackend,) # filter_fields = ('title', 'hostname', 'port') # pagination_class = StandardPagination # # class JobViewSet(viewsets.ModelViewSet): # """Allow users to create, read, and update :class:`Job` instances.""" # # queryset = Job.objects.all() # serializer_class = JobSerializer # permission_classes = (IsAuthenticatedOrReadOnly,) # filter_backends = (DjangoFilterBackend,) # filter_fields = ('title', 'program', 'status', 'owner', 'server') # pagination_class = StandardPagination # # class LogViewSet(viewsets.ModelViewSet): # """Allow users to create, read, and update :class:`Log` instances.""" # # queryset = Log.objects.all() # serializer_class = LogSerializer # permission_classes = (IsAuthenticatedOrReadOnly,) # filter_backends = (DjangoFilterBackend,) # filter_fields = ('time', 'content', 'stream', 'job') # pagination_class = StandardPagination # # class JobUserStatus(TemplateView): # """Show status of all of user's jobs with live updates.""" # # template_name = "django_remote_submission/job-user-status.html" # # class ResultViewSet(viewsets.ModelViewSet): # """Allow users to create, read, and update :class:`Result` instances.""" # # queryset = Result.objects.all() # serializer_class = ResultSerializer # permission_classes = (IsAuthenticatedOrReadOnly,) # filter_backends = (DjangoFilterBackend,) # filter_fields = ('remote_filename', 'job') # 'local_file', # pagination_class = StandardPagination # # class Meta: # filter_overrides = { # models.FileField: { # 'filter_class': django_filters.CharFilter, # 'extra': lambda f: { # 'lookup_expr': 'icontains', # }, # }, # } which might include code, classes, or functions. Output only the next line.
router.register(r'results', ResultViewSet)
Predict the next line for this snippet: <|code_start|> )) class JobLogConsumer(AsyncWebsocketConsumer): async def connect(self): ''' Creates group, add to the valid channels Connects and sends to the browser the log ''' job_pk = self.scope['url_route']['kwargs']['job_pk'] self.group_name = 'job-log-{}'.format(job_pk) await self.channel_layer.group_add( self.group_name, self.channel_name ) await self.accept() await self.send_log(job_pk) async def disconnect(self, close_code): await self.channel_layer.group_discard( self.group_name, self.channel_name ) async def send_log(self, job_pk): <|code_end|> with the help of current file imports: import json from channels.generic.websocket import AsyncWebsocketConsumer from .models import Job and context from other files: # Path: django_remote_submission/models.py # class Job(TimeStampedModel): # """Encapsulates the information about a particular job. # # .. testsetup:: # # from django_remote_submission.models import Server, Interpreter # from django.contrib.auth import get_user_model # python3 = Interpreter(name='Python 3', path='/bin/python3', arguments=['-u']) # server = Server(title='Remote', hostname='foo.invalid', port=22) # user = get_user_model()(username='john') # # >>> from django_remote_submission.models import Job # >>> job = Job( # ... title='My Job', # ... program='print("hello world")', # ... remote_directory='/tmp/', # ... remote_filename='foobar.py', # ... owner=user, # ... server=server, # ... interpreter=python3, # ... ) # >>> job # <Job: My Job> # # """ # # title = models.CharField( # _('Job Name'), # help_text=_('The human-readable name of the job'), # max_length=250, # ) # # uuid = models.UUIDField( # _('Job UUID'), # help_text=_('A unique identifier for use in grouping Result files'), # default=uuid.uuid4, # editable=False, # ) # # program = models.TextField( # _('Job Program'), # help_text=_('The actual program to run (starting with a #!)'), # ) # # STATUS = Choices( # ('initial', _('initial')), # ('submitted', _('submitted')), # ('success', _('success')), # ('failure', _('failure')), # ) # status = StatusField( # _('Job Status'), # help_text=_('The current status of the program'), # default=STATUS.initial, # ) # # remote_directory = models.CharField( # _('Job Remote Directory'), # help_text=_('The directory on the remote host to store the program'), # max_length=250, # ) # # remote_filename = models.CharField( # _('Job Remote Filename'), # help_text=_('The filename to store the program to (e.g. reduce.py)'), # max_length=250, # ) # # owner = models.ForeignKey( # settings.AUTH_USER_MODEL, # models.PROTECT, # related_name='jobs', # verbose_name=_('Job Owner'), # help_text=_('The user that owns this job'), # ) # # server = models.ForeignKey( # 'Server', # models.PROTECT, # related_name='jobs', # verbose_name=_('Job Server'), # help_text=_('The server that this job will run on'), # ) # # interpreter = models.ForeignKey( # Interpreter, # models.PROTECT, # related_name='jobs', # verbose_name=_('Job Interpreter'), # help_text=_('The interpreter that this job will run on'), # ) # # class Meta: # noqa: D101 # verbose_name = _('job') # verbose_name_plural = _('jobs') # # def __str__(self): # """Convert model to string, e.g. ``"My Job"``.""" # return '{self.title}'.format(self=self) # # def clean(self): # """Ensure that the selected interpreter exists on the server. # # To use effectively, add this to the # :func:`django.db.models.signals.pre_save` signal for the :class:`Job` # model. # # """ # available_interpreters = self.server.interpreters.all() # if self.interpreter not in available_interpreters: # raise ValidationError(_('The Interpreter picked is not valid for this server. ')) # #'Please, choose one from: {0!s}.').format(available_interpreters)) # else: # cleaned_data = super(Job, self).clean() # return cleaned_data # # # def save(self, *args, **kwargs): # # ''' # # From Two scoops of django: "Use signals as a last resort." # # ''' # # # super().save(*args, **kwargs) # # # Post save # # # import channels.layers # # from asgiref.sync import async_to_sync # # # def send_message(event): # # message = event['text'] # # channel_layer = channels.layers.get_channel_layer() # # # Send message to WebSocket # # async_to_sync(channel_layer.send)(text_data=json.dumps( # # message # # )) # # # user = self.owner # # group_name = 'job-user-{}'.format(user.username) # # # message = { # # 'job_id': self.id, # # 'title': self.title, # # 'status': self.status, # # 'modified': self.modified.isoformat(), # # } # # # channel_layer = channels.layers.get_channel_layer() # # # async_to_sync(channel_layer.group_send)( # # group_name, # # { # # 'type': 'send_message', # # 'text': message # # } # # ) , which may contain function names, class names, or code. Output only the next line.
job = Job.objects.get(pk=job_pk)
Given the code snippet: <|code_start|># from channels.routing import route # from .consumers import ( # ws_job_status_connect, ws_job_status_disconnect, # ws_job_log_connect, ws_job_log_disconnect, # ) # channel_routing = [ # route('websocket.connect', ws_job_status_connect, path=r'^/job-user/$'), # route('websocket.disconnect', ws_job_status_disconnect, path=r'^/job-user/$'), # route('websocket.connect', ws_job_log_connect, path=r'^/job-log/(?P<job_pk>[0-9]+)/$'), # route('websocket.disconnect', ws_job_log_disconnect, path=r'^/job-log/(?P<job_pk>[0-9]+)/$'), # ] application = ProtocolTypeRouter({ "websocket": AuthMiddlewareStack( URLRouter([ <|code_end|> , generate the next line using the imports in this file: from django.urls import path from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack from .consumers import JobUserConsumer, JobLogConsumer and context (functions, classes, or occasionally code) from other files: # Path: django_remote_submission/consumers.py # class JobUserConsumer(AsyncWebsocketConsumer): # # async def connect(self): # ''' # Creates group, add to the valid channels # Connects and sends to the browser the last jobs # ''' # user = self.scope["user"] # self.group_name = 'job-user-{}'.format(user.username) # # await self.channel_layer.group_add( # self.group_name, # self.channel_name # ) # # await self.accept() # await self.send_last_jobs(user) # # async def disconnect(self, close_code): # # await self.channel_layer.group_discard( # self.group_name, # self.channel_name # ) # # async def send_last_jobs(self, user): # # last_jobs = user.jobs.order_by('-modified')[:10] # # for job in last_jobs: # # message = { # 'job_id': job.id, # 'title': job.title, # 'status': job.status, # 'modified': job.modified.isoformat(), # } # # await self.channel_layer.group_send( # self.group_name, # { # 'type': 'send_message', # 'text': message # } # ) # # async def send_message(self, event): # message = event['text'] # # # Send message to WebSocket # await self.send(text_data=json.dumps( # message # )) # # class JobLogConsumer(AsyncWebsocketConsumer): # # async def connect(self): # ''' # Creates group, add to the valid channels # Connects and sends to the browser the log # ''' # job_pk = self.scope['url_route']['kwargs']['job_pk'] # self.group_name = 'job-log-{}'.format(job_pk) # # await self.channel_layer.group_add( # self.group_name, # self.channel_name # ) # # await self.accept() # await self.send_log(job_pk) # # async def disconnect(self, close_code): # # await self.channel_layer.group_discard( # self.group_name, # self.channel_name # ) # # async def send_log(self, job_pk): # # job = Job.objects.get(pk=job_pk) # logs = job.logs.order_by('time') # # for log in logs: # message = { # 'log_id': log.id, # 'time': log.time.isoformat(), # 'content': log.content, # 'stream': log.stream, # } # # await self.channel_layer.group_send( # self.group_name, # { # 'type': 'send_message', # 'text': message # } # ) # # async def send_message(self, event): # message = event['text'] # # # Send message to WebSocket # await self.send(text_data=json.dumps( # message # )) . Output only the next line.
path('ws/job-user/', JobUserConsumer),
Continue the code snippet: <|code_start|># from channels.routing import route # from .consumers import ( # ws_job_status_connect, ws_job_status_disconnect, # ws_job_log_connect, ws_job_log_disconnect, # ) # channel_routing = [ # route('websocket.connect', ws_job_status_connect, path=r'^/job-user/$'), # route('websocket.disconnect', ws_job_status_disconnect, path=r'^/job-user/$'), # route('websocket.connect', ws_job_log_connect, path=r'^/job-log/(?P<job_pk>[0-9]+)/$'), # route('websocket.disconnect', ws_job_log_disconnect, path=r'^/job-log/(?P<job_pk>[0-9]+)/$'), # ] application = ProtocolTypeRouter({ "websocket": AuthMiddlewareStack( URLRouter([ path('ws/job-user/', JobUserConsumer), <|code_end|> . Use current file imports: from django.urls import path from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack from .consumers import JobUserConsumer, JobLogConsumer and context (classes, functions, or code) from other files: # Path: django_remote_submission/consumers.py # class JobUserConsumer(AsyncWebsocketConsumer): # # async def connect(self): # ''' # Creates group, add to the valid channels # Connects and sends to the browser the last jobs # ''' # user = self.scope["user"] # self.group_name = 'job-user-{}'.format(user.username) # # await self.channel_layer.group_add( # self.group_name, # self.channel_name # ) # # await self.accept() # await self.send_last_jobs(user) # # async def disconnect(self, close_code): # # await self.channel_layer.group_discard( # self.group_name, # self.channel_name # ) # # async def send_last_jobs(self, user): # # last_jobs = user.jobs.order_by('-modified')[:10] # # for job in last_jobs: # # message = { # 'job_id': job.id, # 'title': job.title, # 'status': job.status, # 'modified': job.modified.isoformat(), # } # # await self.channel_layer.group_send( # self.group_name, # { # 'type': 'send_message', # 'text': message # } # ) # # async def send_message(self, event): # message = event['text'] # # # Send message to WebSocket # await self.send(text_data=json.dumps( # message # )) # # class JobLogConsumer(AsyncWebsocketConsumer): # # async def connect(self): # ''' # Creates group, add to the valid channels # Connects and sends to the browser the log # ''' # job_pk = self.scope['url_route']['kwargs']['job_pk'] # self.group_name = 'job-log-{}'.format(job_pk) # # await self.channel_layer.group_add( # self.group_name, # self.channel_name # ) # # await self.accept() # await self.send_log(job_pk) # # async def disconnect(self, close_code): # # await self.channel_layer.group_discard( # self.group_name, # self.channel_name # ) # # async def send_log(self, job_pk): # # job = Job.objects.get(pk=job_pk) # logs = job.logs.order_by('time') # # for log in logs: # message = { # 'log_id': log.id, # 'time': log.time.isoformat(), # 'content': log.content, # 'stream': log.stream, # } # # await self.channel_layer.group_send( # self.group_name, # { # 'type': 'send_message', # 'text': message # } # ) # # async def send_message(self, event): # message = event['text'] # # # Send message to WebSocket # await self.send(text_data=json.dumps( # message # )) . Output only the next line.
path('ws/job-log/<int:job_pk>/', JobLogConsumer),
Continue the code snippet: <|code_start|> class GameInfoController(BaseController): def __init__(self, core): self.core = core self.window = None <|code_end|> . Use current file imports: import xbmcgui from resources.lib.controller.basecontroller import BaseController, route from resources.lib.views.gameinfo import GameInfo and context (classes, functions, or code) from other files: # Path: resources/lib/controller/basecontroller.py # class BaseController(object): # def render(self, name, args=None): # if args: # return router.render(name, args=args) # else: # return router.render(name) # # def route_exists(self, name): # return router.route_exists(name) # # def cleanup(self): # raise NotImplementedError("Cleanup needs to be implemented.") # # def route(name): # def decorator(func): # xbmc.log("[script.luna.router]: Adding route with name %s to cache" % name) # assert name not in router._routes_cache, "Route with name %s already exists on the same class" % name # router._routes_cache[name] = func # return func # # return decorator # # Path: resources/lib/views/gameinfo.py # class GameInfo(WindowXMLDialog): # def __new__(cls, *args, **kwargs): # return super(GameInfo, cls).__new__(cls, 'gameinfo.xml', xbmcaddon.Addon().getAddonInfo('path')) # # def __init__(self, controller, host, game): # super(GameInfo, self).__init__('gameinfo.xml', xbmcaddon.Addon().getAddonInfo('path')) # self.controller = controller # self.host = host # self.game = game # self.list = None # self.play_btn = None # self.select_poster_btn = None # self.select_fanart_btn = None # # def onInit(self): # self.list = self.getControl(51) # self.play_btn = self.getControl(52) # self.select_poster_btn = self.getControl(53) # self.select_fanart_btn = self.getControl(54) # self.setFocus(self.play_btn) # # item = xbmcgui.ListItem() # item.setLabel(self.game.name) # item.setIconImage(self.game.get_selected_poster()) # item.setThumbnailImage(self.game.get_selected_poster()) # item.setInfo('video', { # 'year': self.game.year, # 'plot': self.game.plot, # 'genre': self.game.genre, # 'originaltitle': self.game.name # }) # item.setProperty('icon', self.game.get_selected_poster()) # item.setProperty('fanart', self.game.get_selected_fanart().get_original()) # item.setProperty('year_genre', '%s • %s' % (self.game.year, ', '.join(self.game.genre))) # item.setProperty('description', self.game.plot) # item.setProperty('id', self.game.id) # # self.list.addItems([item]) # # self.connect(xbmcgui.ACTION_NAV_BACK, self.close) # self.connect(self.play_btn, lambda: self.controller.render("game_launch", {'game': self.game})) # self.connect(self.select_poster_btn, lambda: self.controller.select_cover_art(self.game, item)) # self.connect(self.select_fanart_btn, lambda: self.controller.select_fanart(self.game, item)) . Output only the next line.
@route(name='details')
Given the code snippet: <|code_start|> class GameInfoController(BaseController): def __init__(self, core): self.core = core self.window = None @route(name='details') def show_game_info_action(self, host, game): <|code_end|> , generate the next line using the imports in this file: import xbmcgui from resources.lib.controller.basecontroller import BaseController, route from resources.lib.views.gameinfo import GameInfo and context (functions, classes, or occasionally code) from other files: # Path: resources/lib/controller/basecontroller.py # class BaseController(object): # def render(self, name, args=None): # if args: # return router.render(name, args=args) # else: # return router.render(name) # # def route_exists(self, name): # return router.route_exists(name) # # def cleanup(self): # raise NotImplementedError("Cleanup needs to be implemented.") # # def route(name): # def decorator(func): # xbmc.log("[script.luna.router]: Adding route with name %s to cache" % name) # assert name not in router._routes_cache, "Route with name %s already exists on the same class" % name # router._routes_cache[name] = func # return func # # return decorator # # Path: resources/lib/views/gameinfo.py # class GameInfo(WindowXMLDialog): # def __new__(cls, *args, **kwargs): # return super(GameInfo, cls).__new__(cls, 'gameinfo.xml', xbmcaddon.Addon().getAddonInfo('path')) # # def __init__(self, controller, host, game): # super(GameInfo, self).__init__('gameinfo.xml', xbmcaddon.Addon().getAddonInfo('path')) # self.controller = controller # self.host = host # self.game = game # self.list = None # self.play_btn = None # self.select_poster_btn = None # self.select_fanart_btn = None # # def onInit(self): # self.list = self.getControl(51) # self.play_btn = self.getControl(52) # self.select_poster_btn = self.getControl(53) # self.select_fanart_btn = self.getControl(54) # self.setFocus(self.play_btn) # # item = xbmcgui.ListItem() # item.setLabel(self.game.name) # item.setIconImage(self.game.get_selected_poster()) # item.setThumbnailImage(self.game.get_selected_poster()) # item.setInfo('video', { # 'year': self.game.year, # 'plot': self.game.plot, # 'genre': self.game.genre, # 'originaltitle': self.game.name # }) # item.setProperty('icon', self.game.get_selected_poster()) # item.setProperty('fanart', self.game.get_selected_fanart().get_original()) # item.setProperty('year_genre', '%s • %s' % (self.game.year, ', '.join(self.game.genre))) # item.setProperty('description', self.game.plot) # item.setProperty('id', self.game.id) # # self.list.addItems([item]) # # self.connect(xbmcgui.ACTION_NAV_BACK, self.close) # self.connect(self.play_btn, lambda: self.controller.render("game_launch", {'game': self.game})) # self.connect(self.select_poster_btn, lambda: self.controller.select_cover_art(self.game, item)) # self.connect(self.select_fanart_btn, lambda: self.controller.select_fanart(self.game, item)) . Output only the next line.
self.window = GameInfo(self, host, game)
Continue the code snippet: <|code_start|> 'btn_mode', 'btn_south', 'btn_east', 'btn_west', 'btn_north', 'btn_tl', 'btn_tr', 'btn_tl2', 'btn_tr2' ] class StoppableInputHandler(StoppableThread): def __init__(self, input_queue, input_map, dialog, input_number): self.input_queue = input_queue self.input_map = input_map self.dialog = dialog self.input_number = input_number self._trigger_as_button = True StoppableThread.__init__(self) def stop(self): self._stop.set() def stopped(self): return self._stop.isSet() def run(self): self.input_queue.queue.clear() i = 0 <|code_end|> . Use current file imports: import Queue from resources.lib.model.inputmap import InputMap from resources.lib.util.stoppablethread import StoppableThread and context (classes, functions, or code) from other files: # Path: resources/lib/model/inputmap.py # class InputMap: # STATUS_DONE = 'done' # STATUS_PENDING = 'pending' # STATUS_ERROR = 'error' # # def __init__(self, file_name): # self.file_name = file_name # self.abs_x = -1 # self.abs_y = -1 # self.abs_z = -1 # self.reverse_x = 'false' # self.reverse_y = 'false' # self.abs_rx = -1 # self.abs_ry = -1 # self.abs_rz = -1 # self.reverse_rx = 'false' # self.reverse_ry = 'false' # # TODO: How to calculate deadzone properly? moonlight's default config uses 0 all the time ... # self.abs_deadzone = 0 # self.abs_dpad_x = -1 # self.abs_dpad_y = -1 # self.reverse_dpad_x = 'false' # self.reverse_dpad_y = 'false' # self.btn_north = -1 # self.btn_east = -1 # self.btn_south = -1 # self.btn_west = -1 # self.btn_select = -1 # self.btn_start = -1 # self.btn_mode = -1 # self.btn_thumbl = -1 # self.btn_thumbr = -1 # self.btn_tl = -1 # self.btn_tr = -1 # self.btn_tl2 = -1 # self.btn_tr2 = -1 # self.btn_dpad_up = -1 # self.btn_dpad_down = -1 # self.btn_dpad_left = -1 # self.btn_dpad_right = -1 # self.status = self.STATUS_PENDING # # def __iter__(self): # for attr, value in self.__dict__.iteritems(): # if attr not in ['status', 'file_name']: # yield attr, value # # def set_btn(self, attr, btn_no): # setattr(self, attr, btn_no) # # def write(self): # mapping = ConfigParser.ConfigParser() # print dict(self) # for attr, value in dict(self).iteritems(): # mapping.set('', attr, value) # # if self.status == self.STATUS_DONE: # with open(self.file_name, 'wb') as mapping_file: # mapping.write(mapping_file) # mapping_file.close() # # Path: resources/lib/util/stoppablethread.py # class StoppableThread(Thread): # __metaclass__ = ABCMeta # # def __init__(self): # Thread.__init__(self) # self.daemon = True # self._stop = Event() # self.start() # # def stop(self): # self._stop.set() # # def stopped(self): # return self._stop.isSet() # # @abstractmethod # def run(self): # pass # # @abstractmethod # def cleanup(self): # pass . Output only the next line.
while self.input_map.status is not InputMap.STATUS_DONE:
Predict the next line for this snippet: <|code_start|> input_no = [ 'abs_x', 'reverse_x', 'abs_y', 'reverse_y', 'abs_rx', 'reverse_rx', 'abs_ry', 'reverse_ry', 'abs_dpad_x', 'reverse_dpad_x', 'abs_dpad_y', 'reverse_dpad_y', 'btn_thumbl', 'btn_thumbr', 'btn_select', 'btn_start', 'btn_mode', 'btn_south', 'btn_east', 'btn_west', 'btn_north', 'btn_tl', 'btn_tr', 'btn_tl2', 'btn_tr2' ] <|code_end|> with the help of current file imports: import Queue from resources.lib.model.inputmap import InputMap from resources.lib.util.stoppablethread import StoppableThread and context from other files: # Path: resources/lib/model/inputmap.py # class InputMap: # STATUS_DONE = 'done' # STATUS_PENDING = 'pending' # STATUS_ERROR = 'error' # # def __init__(self, file_name): # self.file_name = file_name # self.abs_x = -1 # self.abs_y = -1 # self.abs_z = -1 # self.reverse_x = 'false' # self.reverse_y = 'false' # self.abs_rx = -1 # self.abs_ry = -1 # self.abs_rz = -1 # self.reverse_rx = 'false' # self.reverse_ry = 'false' # # TODO: How to calculate deadzone properly? moonlight's default config uses 0 all the time ... # self.abs_deadzone = 0 # self.abs_dpad_x = -1 # self.abs_dpad_y = -1 # self.reverse_dpad_x = 'false' # self.reverse_dpad_y = 'false' # self.btn_north = -1 # self.btn_east = -1 # self.btn_south = -1 # self.btn_west = -1 # self.btn_select = -1 # self.btn_start = -1 # self.btn_mode = -1 # self.btn_thumbl = -1 # self.btn_thumbr = -1 # self.btn_tl = -1 # self.btn_tr = -1 # self.btn_tl2 = -1 # self.btn_tr2 = -1 # self.btn_dpad_up = -1 # self.btn_dpad_down = -1 # self.btn_dpad_left = -1 # self.btn_dpad_right = -1 # self.status = self.STATUS_PENDING # # def __iter__(self): # for attr, value in self.__dict__.iteritems(): # if attr not in ['status', 'file_name']: # yield attr, value # # def set_btn(self, attr, btn_no): # setattr(self, attr, btn_no) # # def write(self): # mapping = ConfigParser.ConfigParser() # print dict(self) # for attr, value in dict(self).iteritems(): # mapping.set('', attr, value) # # if self.status == self.STATUS_DONE: # with open(self.file_name, 'wb') as mapping_file: # mapping.write(mapping_file) # mapping_file.close() # # Path: resources/lib/util/stoppablethread.py # class StoppableThread(Thread): # __metaclass__ = ABCMeta # # def __init__(self): # Thread.__init__(self) # self.daemon = True # self._stop = Event() # self.start() # # def stop(self): # self._stop.set() # # def stopped(self): # return self._stop.isSet() # # @abstractmethod # def run(self): # pass # # @abstractmethod # def cleanup(self): # pass , which may contain function names, class names, or code. Output only the next line.
class StoppableInputHandler(StoppableThread):
Continue the code snippet: <|code_start|> class ConnectionManager(object): def __init__(self, request_service, pairing_manager): self.request_service = request_service self.pairing_manager = pairing_manager def pair(self, dialog): message = '' server_info = self.request_service.get_server_info() if self.pairing_manager.get_pair_state(self.request_service, <|code_end|> . Use current file imports: from resources.lib.nvhttp.pairingmanager.abstractpairingmanager import AbstractPairingManager and context (classes, functions, or code) from other files: # Path: resources/lib/nvhttp/pairingmanager/abstractpairingmanager.py # class AbstractPairingManager(object): # __metaclass__ = ABCMeta # # STATE_NOT_PAIRED = 0 # STATE_PAIRED = 1 # STATE_PIN_WRONG = 2 # STATE_FAILED = 3 # # @abstractmethod # def pair(self, request_service, server_info, dialog): # pass # # def unpair(self, request_service, server_info): # try: # request_service.open_http_connection( # request_service.base_url_http + '/unpair?' + request_service.build_uid_uuid_string(), # True # ) # except ValueError: # # Unpairing a host needs to be fire and forget # pass # # @staticmethod # def get_pair_state(request_service, server_info): # if request_service.get_xml_string(server_info, 'PairStatus') != '1': # return AbstractPairingManager.STATE_NOT_PAIRED # else: # return AbstractPairingManager.STATE_PAIRED # # @staticmethod # def generate_pin_string(): # return '%s%s%s%s' % (random.randint(0, 9), random.randint(0, 9), random.randint(0, 9), random.randint(0, 9)) # # @staticmethod # def update_dialog(pin, dialog): # pin_message = 'Please enter the PIN: %s' % pin # dialog.update(0, pin_message) . Output only the next line.
server_info) == AbstractPairingManager.STATE_PAIRED:
Here is a snippet: <|code_start|> class GameContextMenuController(BaseController): def __init__(self): self.window = None <|code_end|> . Write the next line using the current file imports: from resources.lib.controller.basecontroller import BaseController, route from resources.lib.views.gamecontextmenu import GameContextMenu and context from other files: # Path: resources/lib/controller/basecontroller.py # class BaseController(object): # def render(self, name, args=None): # if args: # return router.render(name, args=args) # else: # return router.render(name) # # def route_exists(self, name): # return router.route_exists(name) # # def cleanup(self): # raise NotImplementedError("Cleanup needs to be implemented.") # # def route(name): # def decorator(func): # xbmc.log("[script.luna.router]: Adding route with name %s to cache" % name) # assert name not in router._routes_cache, "Route with name %s already exists on the same class" % name # router._routes_cache[name] = func # return func # # return decorator # # Path: resources/lib/views/gamecontextmenu.py # class GameContextMenu(xbmcgui.WindowXMLDialog): # def __new__(cls, *args, **kwargs): # return super(GameContextMenu, cls).__new__(cls, 'lunacontextmenu.xml', xbmcaddon.Addon().getAddonInfo('path')) # # def __init__(self, controller, host, list_item, current_game): # super(GameContextMenu, self).__init__('lunacontextmenu.xml', xbmcaddon.Addon().getAddonInfo('path')) # self.controller = controller # self.host = host # self.list_item = list_item # self.current_game = current_game # self.list = None # self.refresh_required = False # # def onInit(self): # self.list = self.getControl(70) # self.build_list() # self.setFocus(self.list) # # def build_list(self): # items = ['Game Information', 'Refresh List'] # self.list.addItems(items) # # def onAction(self, action): # focus_item_id = self.getFocusId() # # if focus_item_id: # focus_item = self.getControl(focus_item_id) # # if focus_item == self.list and action.getId() == xbmcgui.ACTION_SELECT_ITEM: # selected_position = self.list.getSelectedPosition() # if selected_position == 0: # self.controller.render('gameinfo_details', {'host': self.host, 'game': self.current_game}) # if selected_position == 1: # self.refresh_required = True # self.close() # # if action == xbmcgui.ACTION_NAV_BACK: # self.close() , which may include functions, classes, or code. Output only the next line.
@route(name='menu')
Using the snippet: <|code_start|> class GameContextMenuController(BaseController): def __init__(self): self.window = None @route(name='menu') def show_context_action(self, host, list_item, game): <|code_end|> , determine the next line of code. You have imports: from resources.lib.controller.basecontroller import BaseController, route from resources.lib.views.gamecontextmenu import GameContextMenu and context (class names, function names, or code) available: # Path: resources/lib/controller/basecontroller.py # class BaseController(object): # def render(self, name, args=None): # if args: # return router.render(name, args=args) # else: # return router.render(name) # # def route_exists(self, name): # return router.route_exists(name) # # def cleanup(self): # raise NotImplementedError("Cleanup needs to be implemented.") # # def route(name): # def decorator(func): # xbmc.log("[script.luna.router]: Adding route with name %s to cache" % name) # assert name not in router._routes_cache, "Route with name %s already exists on the same class" % name # router._routes_cache[name] = func # return func # # return decorator # # Path: resources/lib/views/gamecontextmenu.py # class GameContextMenu(xbmcgui.WindowXMLDialog): # def __new__(cls, *args, **kwargs): # return super(GameContextMenu, cls).__new__(cls, 'lunacontextmenu.xml', xbmcaddon.Addon().getAddonInfo('path')) # # def __init__(self, controller, host, list_item, current_game): # super(GameContextMenu, self).__init__('lunacontextmenu.xml', xbmcaddon.Addon().getAddonInfo('path')) # self.controller = controller # self.host = host # self.list_item = list_item # self.current_game = current_game # self.list = None # self.refresh_required = False # # def onInit(self): # self.list = self.getControl(70) # self.build_list() # self.setFocus(self.list) # # def build_list(self): # items = ['Game Information', 'Refresh List'] # self.list.addItems(items) # # def onAction(self, action): # focus_item_id = self.getFocusId() # # if focus_item_id: # focus_item = self.getControl(focus_item_id) # # if focus_item == self.list and action.getId() == xbmcgui.ACTION_SELECT_ITEM: # selected_position = self.list.getSelectedPosition() # if selected_position == 0: # self.controller.render('gameinfo_details', {'host': self.host, 'game': self.current_game}) # if selected_position == 1: # self.refresh_required = True # self.close() # # if action == xbmcgui.ACTION_NAV_BACK: # self.close() . Output only the next line.
self.window = GameContextMenu(self, host, list_item, game)
Predict the next line for this snippet: <|code_start|> buf = array.array('B', [0]) ioctl(js_dev, 0x80016a11, buf) self.num_axes = buf[0] print self.num_axes buf = array.array('B', [0]) ioctl(js_dev, 0x80016a12, buf) self.num_buttons = buf[0] print self.num_buttons buf = array.array('B', [0] * 0x40) ioctl(js_dev, 0x80406a32, buf) for axis in buf[:self.num_axes]: axis_name = axis_names.get(axis, 'unknown(0x%02x)' % axis) self.axis_map.append(axis_name) self.axis_states[axis_name] = 0.0 self.reverse_axis_map[axis_name] = axis buf = array.array('H', [0] * 200) ioctl(js_dev, 0x80406a34, buf) for btn in buf[:self.num_buttons]: btn_name = button_names.get(btn, 'unknown(0x%03x)' % btn) self.btn_map.append(btn_name) self.button_states[btn_name] = 0 self.reverse_btn_map[btn_name] = btn js_dev.close() def capture_input_events(self, js_dev): <|code_end|> with the help of current file imports: import array import os import struct from fcntl import ioctl from resources.lib.model.inputmap import InputMap and context from other files: # Path: resources/lib/model/inputmap.py # class InputMap: # STATUS_DONE = 'done' # STATUS_PENDING = 'pending' # STATUS_ERROR = 'error' # # def __init__(self, file_name): # self.file_name = file_name # self.abs_x = -1 # self.abs_y = -1 # self.abs_z = -1 # self.reverse_x = 'false' # self.reverse_y = 'false' # self.abs_rx = -1 # self.abs_ry = -1 # self.abs_rz = -1 # self.reverse_rx = 'false' # self.reverse_ry = 'false' # # TODO: How to calculate deadzone properly? moonlight's default config uses 0 all the time ... # self.abs_deadzone = 0 # self.abs_dpad_x = -1 # self.abs_dpad_y = -1 # self.reverse_dpad_x = 'false' # self.reverse_dpad_y = 'false' # self.btn_north = -1 # self.btn_east = -1 # self.btn_south = -1 # self.btn_west = -1 # self.btn_select = -1 # self.btn_start = -1 # self.btn_mode = -1 # self.btn_thumbl = -1 # self.btn_thumbr = -1 # self.btn_tl = -1 # self.btn_tr = -1 # self.btn_tl2 = -1 # self.btn_tr2 = -1 # self.btn_dpad_up = -1 # self.btn_dpad_down = -1 # self.btn_dpad_left = -1 # self.btn_dpad_right = -1 # self.status = self.STATUS_PENDING # # def __iter__(self): # for attr, value in self.__dict__.iteritems(): # if attr not in ['status', 'file_name']: # yield attr, value # # def set_btn(self, attr, btn_no): # setattr(self, attr, btn_no) # # def write(self): # mapping = ConfigParser.ConfigParser() # print dict(self) # for attr, value in dict(self).iteritems(): # mapping.set('', attr, value) # # if self.status == self.STATUS_DONE: # with open(self.file_name, 'wb') as mapping_file: # mapping.write(mapping_file) # mapping_file.close() , which may contain function names, class names, or code. Output only the next line.
if self.input_map.status == InputMap.STATUS_PENDING:
Here is a snippet: <|code_start|> self.core.string('name'), 'Getting game list failed. ' + 'This usually means your host wasn\'t paired properly.', '', 20000 ) return if not silent: progress_dialog = xbmcgui.DialogProgress() progress_dialog.create( self.core.string('name'), 'Refreshing Game List' ) if not silent: if game_list is None or len(game_list) == 0: xbmcgui.Dialog().notification( self.core.string('name'), self.core.string('empty_game_list') ) return bar_movement = int(1.0 / len(game_list) * 100) # TODO: storage should be closed after access -> need to build a list(!!) of games and add them all together games = self.game_manager.get_games(host) game_version_storage = self.core.get_storage('game_version') cache = {} <|code_end|> . Write the next line using the current file imports: import xbmcgui from resources.lib.model.game import Game and context from other files: # Path: resources/lib/model/game.py # class Game: # version = 20161201 # # def __init__(self, name, host_uuid, id=None, year=None, genre=None, plot=None, posters=None, fanarts=None): # if genre is None: # genre = [] # if posters is None: # posters = [] # if fanarts is None: # fanarts = {} # # self.name = name # self.host_uuid = host_uuid # self.id = id # self.year = year # self.genre = genre # self.plot = plot # self.posters = posters # self.fanarts = fanarts # self.selected_fanart = self.get_fanart('') # self.selected_poster = self.get_poster(0, '') # # @classmethod # def from_api_response(cls, api_response): # """ # :param ApiResponse api_response: # :rtype: Game # """ # game = cls( # api_response.name, # None, # None, # api_response.year, # api_response.genre, # api_response.plot, # api_response.posters, # api_response.fanarts # ) # # if game.genre == [None]: # game.genre = [] # return game # # def merge(self, other): # """ # :type other: Game # """ # if self.host_uuid is None: # self.host_uuid = other.host_uuid # # if self.id is None: # self.id = other.id # # if self.year is None: # self.year = other.year # # if self.genre is None: # self.genre = sorted(other.genre, key=str.lower) # elif other.genre is not None: # self.genre = sorted(list(set(self.genre) | set(other.genre)), key=str.lower) # # if self.plot is None: # self.plot = other.plot # elif other.plot is not None and len(other.plot) > len(self.plot): # self.plot = other.plot # # if self.posters is None: # self.posters = other.posters # elif other.posters is not None: # self.posters = list(set(self.posters) | set(other.posters)) # # if self.fanarts is None: # self.fanarts = other.fanarts # elif other.fanarts is not None: # new_dict = self.fanarts.copy() # new_dict.update(other.fanarts) # self.fanarts = new_dict # # if self.selected_fanart is None or self.selected_fanart == '': # self.selected_fanart = other.selected_fanart # # def get_fanart(self, alt): # if self.fanarts is None: # return Fanart(alt, alt) # else: # try: # response = self.fanarts.itervalues().next() # if not os.path.isfile(response.get_original()): # response.set_original(self._replace_thumb(response.get_thumb(), response.get_original())) # except: # response = Fanart(alt, alt) # # return response # # def get_selected_fanart(self): # if hasattr(self, 'selected_fanart'): # if self.selected_fanart.get_thumb() == '': # self.selected_fanart = self.get_fanart('common/mesh.png') # # return self.selected_fanart # else: # self.selected_fanart = self.get_fanart('common/mesh.png') # return self.selected_fanart # # def set_selected_fanart(self, uri): # art = self.fanarts.get(os.path.basename(uri)) # if isinstance(art, Fanart): # if not os.path.isfile(art.get_original()): # art.set_original(self._replace_thumb(art.get_thumb(), art.get_original())) # self.selected_fanart = art # else: # if os.path.isfile(uri): # self.selected_fanart = Fanart(uri, uri) # # def get_genre_as_string(self): # if self.genre is not None: # return ', '.join(self.genre) # else: # return '' # # # TODO: Index param is not used anywhere # def get_poster(self, index, alt): # if self.posters is None: # return alt # else: # try: # response = self.posters[0] # except IndexError: # response = alt # # return response # # def get_selected_poster(self): # if hasattr(self, 'selected_poster'): # if self.selected_poster == '': # self.selected_poster = self.get_poster(0, '') # # return self.selected_poster # else: # self.selected_poster = self.get_poster(0, '') # return self.selected_poster # # def _replace_thumb(self, thumbfile, original): # file_path = thumbfile # with open(file_path, 'wb') as img: # curl = subprocess.Popen(['curl', '-XGET', original], stdout=subprocess.PIPE) # img.write(curl.stdout.read()) # img.close() # # return file_path , which may include functions, classes, or code. Output only the next line.
if game_version_storage.get('version') == Game.version:
Given the following code snippet before the placeholder: <|code_start|> list_item.setProperty('state', str(host[0].state)) return def onAction(self, action): if action == xbmcgui.ACTION_NAV_BACK: self.close() focus_item_id = self.getFocusId() if focus_item_id: focus_item = self.getControl(focus_item_id) if focus_item == self.options_list: if action == xbmcgui.ACTION_SELECT_ITEM: # TODO: Assign actions as item properties and call them if self.options_list.getSelectedPosition() == 0: self.controller.render('settings_index') if self.options_list.getSelectedPosition() == 1: self.controller.render('controller_select') if self.options_list.getSelectedPosition() == 2: self.controller.render('audio_select') if self.options_list.getSelectedPosition() == 3: self.controller.render('main_add_host') if focus_item == self.list: if action == xbmcgui.ACTION_CONTEXT_MENU: selected_item = self.list.getSelectedItem() host = self.hosts[selected_item.getProperty('uuid')] <|code_end|> , predict the next line using imports from the current file: import os import xbmcaddon import xbmcgui import xbmc from resources.lib.views.hostcontextmenu import HostContextMenu from resources.lib.views.windowxml import WindowXML and context including class names, function names, and sometimes code from other files: # Path: resources/lib/views/hostcontextmenu.py # class HostContextMenu(xbmcgui.WindowXMLDialog): # def __new__(cls, *args, **kwargs): # return super(HostContextMenu, cls).__new__(cls, 'lunacontextmenu.xml', xbmcaddon.Addon().getAddonInfo('path')) # # def __init__(self, host, controller): # super(HostContextMenu, self).__init__('lunacontextmenu.xml', xbmcaddon.Addon().getAddonInfo('path')) # self.host = host # self.controller = controller # self.list = None # # def onInit(self): # self.list = self.getControl(70) # self.build_list() # self.setFocus(self.list) # # def build_list(self): # items = ['Wake Host', 'Remove Host'] # self.list.addItems(items) # # def onAction(self, action): # if action == xbmcgui.ACTION_NAV_BACK: # self.close() # # focus_item_id = self.getFocusId() # # if focus_item_id: # focus_item = self.getControl(focus_item_id) # # if focus_item == self.list and action == xbmcgui.ACTION_SELECT_ITEM: # selected_position = self.list.getSelectedPosition() # if selected_position == 0: # self.controller.render('host_wake', {'host': self.host}) # self.close() # if selected_position == 1: # self.controller.render('main_host_remove', {'host': self.host}) # self.close() # # Path: resources/lib/views/windowxml.py # class WindowXML(_BaseWindow, _WindowXML): # def __init__(self, xml_filename, script_path): # _WindowXML.__init__(self, xml_filename, script_path) # _BaseWindow.__init__(self) . Output only the next line.
window = HostContextMenu(host, self.controller)
Based on the snippet: <|code_start|> class DiscoveryAgent(object): service_type = '_nvstream._tcp.local.' def __init__(self): self.available_hosts = {} self.zeroconf = None self.browser = None def service_state_change(self, zeroconf, service_type, name, state_change): if state_change is ServiceStateChange.Added: info = zeroconf.get_service_info(service_type, name) <|code_end|> , predict the immediate next line with the help of imports: import time from zeroconf import ServiceBrowser, Zeroconf, ServiceStateChange from resources.lib.model.mdnscomputer import MdnsComputer and context (classes, functions, sometimes code) from other files: # Path: resources/lib/model/mdnscomputer.py # class MdnsComputer: # # def __init__(self, service_type=None, name=None, address=None, port=None, server=None): # self.service_type = service_type # self.name = name # self.address = address # self.port = port # self.server = server # # @classmethod # def from_service_info(cls, service_info): # mdnscomputer = cls( # service_info.type, # service_info.name, # '.'.join(str(ord(i)) for i in service_info.address), # service_info.port, # service_info.server # ) # # return mdnscomputer . Output only the next line.
self.available_hosts[name] = MdnsComputer.from_service_info(info)
Next line prediction: <|code_start|> class FeatureBroker: def __init__(self, allow_replace=False): self.providers = {} self.tagged_features = {} self.tags = {} self.initialized = {} self.allow_replace = allow_replace def _parse_config(self): if 'xbmcaddon' in sys.modules: features_path = os.path.join(xbmcaddon.Addon().getAddonInfo('path'), 'resources/lib/config/features.yml') else: features_path = 'resources/lib/config/features.yml' with open(features_path) as config: feature_objects = [] service_definitions = yaml.safe_load(config) for _service in service_definitions['services']: <|code_end|> . Use current file imports: (import importlib import os import sys import yaml import xbmcaddon from resources.lib.di.component import Component from resources.lib.di.tag import Tag from resources.lib.di.requiredfeature import RequiredFeature from resources.lib.di.requiredfeature import RequiredFeature) and context including class names, function names, or small code snippets from other files: # Path: resources/lib/di/component.py # class Component(yaml.YAMLObject): # """Symbolic base class for components""" # yaml_tag = u'!component' # # def __init__(self, name, module, class_name, arguments, tags, factory_class, factory_method, lazy, calls): # self.name = name # self.module = module # self.class_name = class_name # self.arguments = arguments # self.tags = tags # self.factory_class = factory_class # self.factory_method = factory_method # self.lazy = lazy # self.calls = calls # # @classmethod # def from_dict(cls, name, module=None, class_name=None, arguments=None, tags=None, factory_class=None, # factory_method=None, lazy=None, calls=None, **kwargs): # return cls(name, module, class_name, arguments, tags, factory_class, factory_method, lazy, calls) # # Path: resources/lib/di/tag.py # class Tag(object): # def __init__(self, name, **kwargs): # self.name = name # # for key, value in kwargs.iteritems(): # self.__setattr__(key, value) # # @classmethod # def from_dict(cls, name, **kwargs): # return cls(name, **kwargs) # # def __str__(self): # if hasattr(self, 'channel'): # return '%s->%s' % (self.name, self.channel) # else: # return self.name . Output only the next line.
feature = Component.from_dict(_service, **service_definitions['services'][_service])
Using the snippet: <|code_start|> class FeatureBroker: def __init__(self, allow_replace=False): self.providers = {} self.tagged_features = {} self.tags = {} self.initialized = {} self.allow_replace = allow_replace def _parse_config(self): if 'xbmcaddon' in sys.modules: features_path = os.path.join(xbmcaddon.Addon().getAddonInfo('path'), 'resources/lib/config/features.yml') else: features_path = 'resources/lib/config/features.yml' with open(features_path) as config: feature_objects = [] service_definitions = yaml.safe_load(config) for _service in service_definitions['services']: feature = Component.from_dict(_service, **service_definitions['services'][_service]) feature_objects.append(feature) for feature in feature_objects: self._provide(feature) tags = getattr(feature, 'tags', None) if tags is not None: for key, tag in enumerate(feature.tags): <|code_end|> , determine the next line of code. You have imports: import importlib import os import sys import yaml import xbmcaddon from resources.lib.di.component import Component from resources.lib.di.tag import Tag from resources.lib.di.requiredfeature import RequiredFeature from resources.lib.di.requiredfeature import RequiredFeature and context (class names, function names, or code) available: # Path: resources/lib/di/component.py # class Component(yaml.YAMLObject): # """Symbolic base class for components""" # yaml_tag = u'!component' # # def __init__(self, name, module, class_name, arguments, tags, factory_class, factory_method, lazy, calls): # self.name = name # self.module = module # self.class_name = class_name # self.arguments = arguments # self.tags = tags # self.factory_class = factory_class # self.factory_method = factory_method # self.lazy = lazy # self.calls = calls # # @classmethod # def from_dict(cls, name, module=None, class_name=None, arguments=None, tags=None, factory_class=None, # factory_method=None, lazy=None, calls=None, **kwargs): # return cls(name, module, class_name, arguments, tags, factory_class, factory_method, lazy, calls) # # Path: resources/lib/di/tag.py # class Tag(object): # def __init__(self, name, **kwargs): # self.name = name # # for key, value in kwargs.iteritems(): # self.__setattr__(key, value) # # @classmethod # def from_dict(cls, name, **kwargs): # return cls(name, **kwargs) # # def __str__(self): # if hasattr(self, 'channel'): # return '%s->%s' % (self.name, self.channel) # else: # return self.name . Output only the next line.
tag = Tag.from_dict(**tag)
Given the code snippet: <|code_start|> def get_game_information(self, nvapp): request_name = nvapp.title.replace(" ", "+").replace(":", "") response = self._gather_information(nvapp, request_name) response.name = nvapp.title return response def return_paths(self): return [self.cover_cache, self.fanart_cache, self.api_cache] def is_enabled(self): return self.core.get_setting('enable_tgdb', bool) def _gather_information(self, nvapp, game): game_cover_path = self._set_up_path(os.path.join(self.cover_cache, nvapp.id)) game_fanart_path = self._set_up_path(os.path.join(self.fanart_cache, nvapp.id)) xml_response_file = self._get_xml_data(nvapp.id, game) try: xml_root = ElementTree(file=xml_response_file).getroot() except: xbmcgui.Dialog().notification( self.core.string('name'), self.core.string('scraper_failed') % (game, self.name()) ) if xml_response_file is not None and os.path.isfile(xml_response_file): os.remove(xml_response_file) <|code_end|> , generate the next line using the imports in this file: import os import subprocess import xbmcgui from xml.etree.ElementTree import ElementTree from xml.etree.ElementTree import Element from xbmcswift2 import xbmcgui from abcscraper import AbstractScraper from resources.lib.model.apiresponse import ApiResponse from resources.lib.model.fanart import Fanart and context (functions, classes, or occasionally code) from other files: # Path: resources/lib/model/apiresponse.py # class ApiResponse: # def __init__(self, name=None, year=None, genre=None, plot=None, posters=None, fanarts=None): # if genre is None: # genre = [] # if posters is None: # posters = [] # if fanarts is None: # fanarts = {} # # self.name = name # self.year = year # self.genre = genre # self.plot = plot # self.posters = posters # self.fanarts = fanarts # # @classmethod # def from_dict(cls, name=None, year=None, genre=None, plot=None, posters=None, fanarts=None, **kwargs): # return cls(name, year, genre, plot, posters, fanarts) # # Path: resources/lib/model/fanart.py # class Fanart: # def __init__(self, original=None, thumb=None): # self.original = original # self.thumb = thumb # # def get_original(self): # return self.original # # def set_original(self, original): # self.original = original # # def get_thumb(self): # return self.thumb # # def set_thumb(self, thumb): # self.thumb = thumb . Output only the next line.
return ApiResponse()
Given snippet: <|code_start|> if not os.path.isfile(file_path): if not os.path.exists(os.path.dirname(file_path)): os.makedirs(os.path.dirname(file_path)) curl = subprocess.Popen(['curl', '-XGET', self.api_url % game], stdout=subprocess.PIPE) with open(file_path, 'w') as response_file: response_file.write(curl.stdout.read()) return file_path @staticmethod def _parse_xml_to_dict(root): """ :rtype: dict :type root: Element """ data = {'year': 'N/A', 'plot': 'N/A', 'posters': [], 'genre': [], 'fanarts': []} similar_id = [] base_img_url = root.find('baseImgUrl').text for game in root.findall('Game'): if game.find('Platform').text == 'PC': if game.find('ReleaseDate') is not None: data['year'] = os.path.basename(game.find('ReleaseDate').text) if game.find('Overview') is not None: data['plot'] = game.find('Overview').text for img in game.find('Images'): if img.get('side') == 'front': data['posters'].append(os.path.join(base_img_url, img.text)) if img.tag == 'fanart': <|code_end|> , continue by predicting the next line. Consider current file imports: import os import subprocess import xbmcgui from xml.etree.ElementTree import ElementTree from xml.etree.ElementTree import Element from xbmcswift2 import xbmcgui from abcscraper import AbstractScraper from resources.lib.model.apiresponse import ApiResponse from resources.lib.model.fanart import Fanart and context: # Path: resources/lib/model/apiresponse.py # class ApiResponse: # def __init__(self, name=None, year=None, genre=None, plot=None, posters=None, fanarts=None): # if genre is None: # genre = [] # if posters is None: # posters = [] # if fanarts is None: # fanarts = {} # # self.name = name # self.year = year # self.genre = genre # self.plot = plot # self.posters = posters # self.fanarts = fanarts # # @classmethod # def from_dict(cls, name=None, year=None, genre=None, plot=None, posters=None, fanarts=None, **kwargs): # return cls(name, year, genre, plot, posters, fanarts) # # Path: resources/lib/model/fanart.py # class Fanart: # def __init__(self, original=None, thumb=None): # self.original = original # self.thumb = thumb # # def get_original(self): # return self.original # # def set_original(self, original): # self.original = original # # def get_thumb(self): # return self.thumb # # def set_thumb(self, thumb): # self.thumb = thumb which might include code, classes, or functions. Output only the next line.
image = Fanart()
Given snippet: <|code_start|>""" Holds all cross-controller routes, read from routing.yml """ class Router(object): def __init__(self): self.routes = {} self._routes_cache = {} self.routing = {} self.main_route = None def _parse_config(self): if 'xbmcaddon' in sys.modules: routing_path = os.path.join(xbmcaddon.Addon().getAddonInfo('path'), 'resources/lib/config/routing.yml') else: routing_path = 'resources/lib/config/routing.yml' with open(routing_path) as config: routing_objects = [] routing = yaml.safe_load(config) for _route_definition in routing['routing']: <|code_end|> , continue by predicting the next line. Consider current file imports: import os import sys import yaml import xbmc import xbmcaddon from resources.lib.routing.route import Route from resources.lib.di.requiredfeature import RequiredFeature and context: # Path: resources/lib/routing/route.py # class Route(yaml.YAMLObject): # """Symbolic base class for routes""" # yaml_tag = u'!route' # # def __init__(self, service_name, class_name, service, prefix): # self.service_name = service_name # self.class_name = class_name # self.service = service # self.prefix = prefix # self.is_main_route = (prefix == 'main') # # @classmethod # def from_dict(cls, service_name=None, class_name=None, service=None, prefix=None, **kwargs): # return cls(service_name, class_name, service, prefix) # # Path: resources/lib/di/requiredfeature.py # class RequiredFeature(object): # def __init__(self, feature, assertion=featurebroker.no_assertion): # self.feature = feature # self.assertion = assertion # # def __get__(self, instance, owner): # return self.result # # def __getattr__(self, name): # assert name == 'result', "Unexpected attribute request other than 'result': %s" % name # self.result = self.request() # return self.result # # def _build_attributes_dict(self, class_, feature): # args = getattr(feature, 'arguments', None) # if args is not None: # for index, arg in enumerate(feature.arguments): # # TODO: checking for instance is generally a bad idea and only a temporary workaround to allow # # eos-helper's functionality # if isinstance(arg, str) and arg[:1] == '@': # feature.arguments[index] = RequiredFeature(arg[1:]).request() # args = inspect.getargspec(class_.__init__)[0] # if args[0] == 'self': # args.pop(0) # argument_dict = dict(zip(args, feature.arguments)) # # return argument_dict # else: # return None # # def request(self): # if featurebroker.features.get_initialized(self.feature) is not None: # instance = featurebroker.features.get_initialized(self.feature) # else: # feature = featurebroker.features[self.feature] # # lazy = getattr(feature, 'lazy', None) # if lazy is not None: # lazy_module = importlib.import_module('resources.lib.di.lazyproxy') # lazy_class = getattr(lazy_module, 'LazyProxy') # # lazy_instance = lazy_class( # original_module=feature.module, # original_class=feature.class_name, # init_args=feature.arguments # ) # # featurebroker.features.set_initialized(self.feature, lazy_instance) # # return lazy_instance # # module = importlib.import_module(feature.module) # class_ = getattr(module, feature.class_name) # # factory = getattr(feature, 'factory_class', None) # if factory is not None: # factory_class = RequiredFeature(feature.factory_class[1:]).request() # factory_method = feature.factory_method # # if featurebroker.has_methods(factory_method)(factory_class): # arguments = self._build_attributes_dict(class_, feature) # if arguments is not None: # instance = getattr(factory_class, factory_method)(**arguments) # else: # instance = getattr(factory_class, factory_method)() # # else: # arguments = self._build_attributes_dict(class_, feature) # if arguments is not None: # instance = class_(**arguments) # else: # instance = class_() # assert self.assertion(instance), \ # "The value %s of %r does not match the specified criteria" \ # % (instance, self.feature) # # try: # tagged_features = featurebroker.features.get_tagged_features(self.feature) # if featurebroker.has_methods('append')(instance): # for key, tagged_feature in enumerate(tagged_features): # tagged_features[key] = RequiredFeature(tagged_feature.name).request() # # instance.append(tagged_features) # except KeyError: # pass # # featurebroker.features.set_initialized(self.feature, instance) # # if hasattr(feature, 'calls') and feature.calls is not None: # for call in feature.calls: # method = call[0] # args = call[1] # # for key, arg in enumerate(args): # if arg[:1] == '@': # if featurebroker.features.get_initialized(arg[:1]) is not None: # args[key] = featurebroker.features.get_initialized(arg[:1]) # # resolved_all_services = True # for key, arg in enumerate(args): # if isinstance(arg, str) and arg[:1] == '@': # resolved_all_services = False # # if resolved_all_services: # method(instance, **args) # # return instance which might include code, classes, or functions. Output only the next line.
route_object = Route.from_dict(_route_definition, **routing['routing'][_route_definition])
Next line prediction: <|code_start|> def register(self, cls): route = self.routing[cls.__name__] routes_cache = {} for key, value in self._routes_cache.iteritems(): xbmc.log('[script.luna.router]: Added Route: %s_%s -> %s' % (route.prefix, key, value)) routes_cache["%s_%s" % (route.prefix, key)] = value self.routes.update(routes_cache) self._routes_cache = {} return cls """ def route(self, name): def decorator(func): xbmc.log("[script.luna.router]: Adding route with name %s" % name) self._routes_cache[name] = func return func return decorator """ def render(self, name, instance=None, args=None): try: # TODO: splitting at the first occurrence isn't the best idea ... # TODO: are duplicate prefixes on different controllers a possible use case? route = None prefix = name.split('_')[0] for key, _route in self.routing.iteritems(): if _route.prefix == prefix: route = _route # TODO: if we need to refactor this, call Dennis if route is not None: <|code_end|> . Use current file imports: (import os import sys import yaml import xbmc import xbmcaddon from resources.lib.routing.route import Route from resources.lib.di.requiredfeature import RequiredFeature) and context including class names, function names, or small code snippets from other files: # Path: resources/lib/routing/route.py # class Route(yaml.YAMLObject): # """Symbolic base class for routes""" # yaml_tag = u'!route' # # def __init__(self, service_name, class_name, service, prefix): # self.service_name = service_name # self.class_name = class_name # self.service = service # self.prefix = prefix # self.is_main_route = (prefix == 'main') # # @classmethod # def from_dict(cls, service_name=None, class_name=None, service=None, prefix=None, **kwargs): # return cls(service_name, class_name, service, prefix) # # Path: resources/lib/di/requiredfeature.py # class RequiredFeature(object): # def __init__(self, feature, assertion=featurebroker.no_assertion): # self.feature = feature # self.assertion = assertion # # def __get__(self, instance, owner): # return self.result # # def __getattr__(self, name): # assert name == 'result', "Unexpected attribute request other than 'result': %s" % name # self.result = self.request() # return self.result # # def _build_attributes_dict(self, class_, feature): # args = getattr(feature, 'arguments', None) # if args is not None: # for index, arg in enumerate(feature.arguments): # # TODO: checking for instance is generally a bad idea and only a temporary workaround to allow # # eos-helper's functionality # if isinstance(arg, str) and arg[:1] == '@': # feature.arguments[index] = RequiredFeature(arg[1:]).request() # args = inspect.getargspec(class_.__init__)[0] # if args[0] == 'self': # args.pop(0) # argument_dict = dict(zip(args, feature.arguments)) # # return argument_dict # else: # return None # # def request(self): # if featurebroker.features.get_initialized(self.feature) is not None: # instance = featurebroker.features.get_initialized(self.feature) # else: # feature = featurebroker.features[self.feature] # # lazy = getattr(feature, 'lazy', None) # if lazy is not None: # lazy_module = importlib.import_module('resources.lib.di.lazyproxy') # lazy_class = getattr(lazy_module, 'LazyProxy') # # lazy_instance = lazy_class( # original_module=feature.module, # original_class=feature.class_name, # init_args=feature.arguments # ) # # featurebroker.features.set_initialized(self.feature, lazy_instance) # # return lazy_instance # # module = importlib.import_module(feature.module) # class_ = getattr(module, feature.class_name) # # factory = getattr(feature, 'factory_class', None) # if factory is not None: # factory_class = RequiredFeature(feature.factory_class[1:]).request() # factory_method = feature.factory_method # # if featurebroker.has_methods(factory_method)(factory_class): # arguments = self._build_attributes_dict(class_, feature) # if arguments is not None: # instance = getattr(factory_class, factory_method)(**arguments) # else: # instance = getattr(factory_class, factory_method)() # # else: # arguments = self._build_attributes_dict(class_, feature) # if arguments is not None: # instance = class_(**arguments) # else: # instance = class_() # assert self.assertion(instance), \ # "The value %s of %r does not match the specified criteria" \ # % (instance, self.feature) # # try: # tagged_features = featurebroker.features.get_tagged_features(self.feature) # if featurebroker.has_methods('append')(instance): # for key, tagged_feature in enumerate(tagged_features): # tagged_features[key] = RequiredFeature(tagged_feature.name).request() # # instance.append(tagged_features) # except KeyError: # pass # # featurebroker.features.set_initialized(self.feature, instance) # # if hasattr(feature, 'calls') and feature.calls is not None: # for call in feature.calls: # method = call[0] # args = call[1] # # for key, arg in enumerate(args): # if arg[:1] == '@': # if featurebroker.features.get_initialized(arg[:1]) is not None: # args[key] = featurebroker.features.get_initialized(arg[:1]) # # resolved_all_services = True # for key, arg in enumerate(args): # if isinstance(arg, str) and arg[:1] == '@': # resolved_all_services = False # # if resolved_all_services: # method(instance, **args) # # return instance . Output only the next line.
instance = RequiredFeature(route.service[1:]).request()
Continue the code snippet: <|code_start|> class CacheController(BaseController): def __init__(self, core, scraper_chain): self.core = core self.base_path = core.storage_path self.scraper_chain = scraper_chain <|code_end|> . Use current file imports: from resources.lib.controller.basecontroller import BaseController, route import xbmcgui and context (classes, functions, or code) from other files: # Path: resources/lib/controller/basecontroller.py # class BaseController(object): # def render(self, name, args=None): # if args: # return router.render(name, args=args) # else: # return router.render(name) # # def route_exists(self, name): # return router.route_exists(name) # # def cleanup(self): # raise NotImplementedError("Cleanup needs to be implemented.") # # def route(name): # def decorator(func): # xbmc.log("[script.luna.router]: Adding route with name %s to cache" % name) # assert name not in router._routes_cache, "Route with name %s already exists on the same class" % name # router._routes_cache[name] = func # return func # # return decorator . Output only the next line.
@route("reset")
Given the following code snippet before the placeholder: <|code_start|> class NvHTTPScraper(AbstractScraper): def __init__(self, core, request_service): AbstractScraper.__init__(self, core) self.cover_cache = self._set_up_path(os.path.join(self.base_path, 'art/poster/')) self.request_service = request_service def name(self): return 'NvHTTP' def return_paths(self): return [self.cover_cache] def is_enabled(self): return True def get_game_information(self, nvapp): game_cover_path = self._set_up_path(os.path.join(self.cover_cache, nvapp.id)) <|code_end|> , predict the next line using imports from the current file: import os from resources.lib.model.apiresponse import ApiResponse from resources.lib.scraper.abcscraper import AbstractScraper and context including class names, function names, and sometimes code from other files: # Path: resources/lib/model/apiresponse.py # class ApiResponse: # def __init__(self, name=None, year=None, genre=None, plot=None, posters=None, fanarts=None): # if genre is None: # genre = [] # if posters is None: # posters = [] # if fanarts is None: # fanarts = {} # # self.name = name # self.year = year # self.genre = genre # self.plot = plot # self.posters = posters # self.fanarts = fanarts # # @classmethod # def from_dict(cls, name=None, year=None, genre=None, plot=None, posters=None, fanarts=None, **kwargs): # return cls(name, year, genre, plot, posters, fanarts) # # Path: resources/lib/scraper/abcscraper.py # class AbstractScraper: # __metaclass__ = ABCMeta # # def __init__(self, core): # self.core = core # self.base_path = self.core.storage_path # # @abstractproperty # def name(self): # """ # Returns human readable name of scraper # :rtype: str # :return: name # """ # pass # # @abstractmethod # def get_game_information(self, nvapp): # """ # Queries game information from API and returns it as a dict # :type nvapp: NvApp # :rtype: dict # """ # pass # # @abstractmethod # def return_paths(self): # """ # Returns a list of used cache paths by this scraper # :rtype: list # """ # pass # # @abstractmethod # def is_enabled(self): # pass # # @staticmethod # def _set_up_path(path): # if not os.path.exists(path): # os.makedirs(path) # # return path # # @staticmethod # def _dump_image(base_path, url): # if url != 'N/A': # file_path = os.path.join(base_path, os.path.basename(url)) # if not os.path.exists(file_path): # if not os.path.exists(os.path.dirname(file_path)): # os.makedirs(os.path.dirname(file_path)) # with open(file_path, 'wb') as img: # curl = subprocess.Popen(['curl', '-XGET', url], stdout=subprocess.PIPE) # img.write(curl.stdout.read()) # img.close() # # return file_path # else: # # return None . Output only the next line.
response = ApiResponse()
Based on the snippet: <|code_start|> class StoppableJSHandler(StoppableThread): def __init__(self, input_wrapper, input_map): self.input = input_wrapper self.input.build_controller_map() self.js_dev = None self.map = input_map StoppableThread.__init__(self) def stop(self): self._stop.set() def stopped(self): return self._stop.isSet() def run(self): print 'Opened input device %s' % self.input.device self.js_dev = open(self.input.device, 'rb') while True: if self.stopped(): self.cleanup() return self.input.capture_input_events(self.js_dev) def cleanup(self): self.js_dev.close() <|code_end|> , predict the immediate next line with the help of imports: from resources.lib.model.inputmap import InputMap from resources.lib.util.stoppablethread import StoppableThread and context (classes, functions, sometimes code) from other files: # Path: resources/lib/model/inputmap.py # class InputMap: # STATUS_DONE = 'done' # STATUS_PENDING = 'pending' # STATUS_ERROR = 'error' # # def __init__(self, file_name): # self.file_name = file_name # self.abs_x = -1 # self.abs_y = -1 # self.abs_z = -1 # self.reverse_x = 'false' # self.reverse_y = 'false' # self.abs_rx = -1 # self.abs_ry = -1 # self.abs_rz = -1 # self.reverse_rx = 'false' # self.reverse_ry = 'false' # # TODO: How to calculate deadzone properly? moonlight's default config uses 0 all the time ... # self.abs_deadzone = 0 # self.abs_dpad_x = -1 # self.abs_dpad_y = -1 # self.reverse_dpad_x = 'false' # self.reverse_dpad_y = 'false' # self.btn_north = -1 # self.btn_east = -1 # self.btn_south = -1 # self.btn_west = -1 # self.btn_select = -1 # self.btn_start = -1 # self.btn_mode = -1 # self.btn_thumbl = -1 # self.btn_thumbr = -1 # self.btn_tl = -1 # self.btn_tr = -1 # self.btn_tl2 = -1 # self.btn_tr2 = -1 # self.btn_dpad_up = -1 # self.btn_dpad_down = -1 # self.btn_dpad_left = -1 # self.btn_dpad_right = -1 # self.status = self.STATUS_PENDING # # def __iter__(self): # for attr, value in self.__dict__.iteritems(): # if attr not in ['status', 'file_name']: # yield attr, value # # def set_btn(self, attr, btn_no): # setattr(self, attr, btn_no) # # def write(self): # mapping = ConfigParser.ConfigParser() # print dict(self) # for attr, value in dict(self).iteritems(): # mapping.set('', attr, value) # # if self.status == self.STATUS_DONE: # with open(self.file_name, 'wb') as mapping_file: # mapping.write(mapping_file) # mapping_file.close() # # Path: resources/lib/util/stoppablethread.py # class StoppableThread(Thread): # __metaclass__ = ABCMeta # # def __init__(self): # Thread.__init__(self) # self.daemon = True # self._stop = Event() # self.start() # # def stop(self): # self._stop.set() # # def stopped(self): # return self._stop.isSet() # # @abstractmethod # def run(self): # pass # # @abstractmethod # def cleanup(self): # pass . Output only the next line.
if self.map.status == InputMap.STATUS_DONE:
Predict the next line after this snippet: <|code_start|> class TestConfigHelper(unittest.TestCase): def setUp(self): path = os.path.join(os.path.expanduser('~'), 'LunaTestTemp/') if not os.path.exists(path): os.makedirs(path) self.addon_path = path self.bin_path = os.path.join(path, 'binary/bin') self.fake_settings = { 'addon_path': self.addon_path, 'binary_path': self.bin_path, 'host_ip': '192.168.1.1', 'enable_custom_res': False, 'resolution_width': '', 'resolution_height': '', 'resolution': '1920x1080', 'framerate': '60', 'graphics_optimizations': False, 'remote_optimizations': False, 'local_audio': False, 'enable_custom_bitrate': False, 'bitrate': '', 'packetsize': 1024, 'enable_custom_input': True, 'input_map': os.path.join(self.addon_path, 'input.map'), 'input_device': os.path.join(self.addon_path, 'input.device'), 'override_default_resolution': False } def testConfigurationDump(self): <|code_end|> using the current file's imports: import os import shutil import unittest from resources.lib.di.requiredfeature import RequiredFeature and any relevant context from other files: # Path: resources/lib/di/requiredfeature.py # class RequiredFeature(object): # def __init__(self, feature, assertion=featurebroker.no_assertion): # self.feature = feature # self.assertion = assertion # # def __get__(self, instance, owner): # return self.result # # def __getattr__(self, name): # assert name == 'result', "Unexpected attribute request other than 'result': %s" % name # self.result = self.request() # return self.result # # def _build_attributes_dict(self, class_, feature): # args = getattr(feature, 'arguments', None) # if args is not None: # for index, arg in enumerate(feature.arguments): # # TODO: checking for instance is generally a bad idea and only a temporary workaround to allow # # eos-helper's functionality # if isinstance(arg, str) and arg[:1] == '@': # feature.arguments[index] = RequiredFeature(arg[1:]).request() # args = inspect.getargspec(class_.__init__)[0] # if args[0] == 'self': # args.pop(0) # argument_dict = dict(zip(args, feature.arguments)) # # return argument_dict # else: # return None # # def request(self): # if featurebroker.features.get_initialized(self.feature) is not None: # instance = featurebroker.features.get_initialized(self.feature) # else: # feature = featurebroker.features[self.feature] # # lazy = getattr(feature, 'lazy', None) # if lazy is not None: # lazy_module = importlib.import_module('resources.lib.di.lazyproxy') # lazy_class = getattr(lazy_module, 'LazyProxy') # # lazy_instance = lazy_class( # original_module=feature.module, # original_class=feature.class_name, # init_args=feature.arguments # ) # # featurebroker.features.set_initialized(self.feature, lazy_instance) # # return lazy_instance # # module = importlib.import_module(feature.module) # class_ = getattr(module, feature.class_name) # # factory = getattr(feature, 'factory_class', None) # if factory is not None: # factory_class = RequiredFeature(feature.factory_class[1:]).request() # factory_method = feature.factory_method # # if featurebroker.has_methods(factory_method)(factory_class): # arguments = self._build_attributes_dict(class_, feature) # if arguments is not None: # instance = getattr(factory_class, factory_method)(**arguments) # else: # instance = getattr(factory_class, factory_method)() # # else: # arguments = self._build_attributes_dict(class_, feature) # if arguments is not None: # instance = class_(**arguments) # else: # instance = class_() # assert self.assertion(instance), \ # "The value %s of %r does not match the specified criteria" \ # % (instance, self.feature) # # try: # tagged_features = featurebroker.features.get_tagged_features(self.feature) # if featurebroker.has_methods('append')(instance): # for key, tagged_feature in enumerate(tagged_features): # tagged_features[key] = RequiredFeature(tagged_feature.name).request() # # instance.append(tagged_features) # except KeyError: # pass # # featurebroker.features.set_initialized(self.feature, instance) # # if hasattr(feature, 'calls') and feature.calls is not None: # for call in feature.calls: # method = call[0] # args = call[1] # # for key, arg in enumerate(args): # if arg[:1] == '@': # if featurebroker.features.get_initialized(arg[:1]) is not None: # args[key] = featurebroker.features.get_initialized(arg[:1]) # # resolved_all_services = True # for key, arg in enumerate(args): # if isinstance(arg, str) and arg[:1] == '@': # resolved_all_services = False # # if resolved_all_services: # method(instance, **args) # # return instance . Output only the next line.
config = RequiredFeature('config-helper').request()
Predict the next line after this snippet: <|code_start|> data = AdvancedPairingManager._pad(data) cipher = AES.new(buffer(key)) return cipher.decrypt(buffer(data)) @staticmethod def _concat_bytes(a, b): c = bytearray(len(a) + len(b)) c[:] = a c[len(a):len(a) + len(b)] = b return c @staticmethod def _verify_signature(data, signature, cert): pubkey = cert.get_pubkey() pubkey.reset_context(md='sha256') pubkey.verify_init() pubkey.verify_update(data) return pubkey.verify_final(signature) @staticmethod def _sign_data(data, key): return key.sign(hashlib.sha256(data).digest(), 'sha256') def pair(self, request_service, server_info, dialog): pin = self.generate_pin_string() self.update_dialog(pin, dialog) server_major_version = request_service.get_server_major_version(server_info) if int(server_major_version) >= 7: <|code_end|> using the current file's imports: import binascii import hashlib import random from Crypto.Cipher import AES from Crypto.Util import asn1 from M2Crypto import X509 from resources.lib.nvhttp.pairinghash.sha256pairinghash import Sha256PairingHash from resources.lib.nvhttp.pairinghash.sha1pairinghash import Sha1PairingHash from resources.lib.nvhttp.pairingmanager.abstractpairingmanager import AbstractPairingManager and any relevant context from other files: # Path: resources/lib/nvhttp/pairinghash/sha256pairinghash.py # class Sha256PairingHash(AbstractPairingHash): # def get_hash_length(self): # return 32 # # def hash_data(self, data): # m = hashlib.sha256() # m.update(data) # return bytearray(m.digest()) # # Path: resources/lib/nvhttp/pairinghash/sha1pairinghash.py # class Sha1PairingHash(AbstractPairingHash): # def get_hash_length(self): # return 20 # # def hash_data(self, data): # m = hashlib.sha1() # m.update(data) # return bytearray(m.digest()) # # Path: resources/lib/nvhttp/pairingmanager/abstractpairingmanager.py # class AbstractPairingManager(object): # __metaclass__ = ABCMeta # # STATE_NOT_PAIRED = 0 # STATE_PAIRED = 1 # STATE_PIN_WRONG = 2 # STATE_FAILED = 3 # # @abstractmethod # def pair(self, request_service, server_info, dialog): # pass # # def unpair(self, request_service, server_info): # try: # request_service.open_http_connection( # request_service.base_url_http + '/unpair?' + request_service.build_uid_uuid_string(), # True # ) # except ValueError: # # Unpairing a host needs to be fire and forget # pass # # @staticmethod # def get_pair_state(request_service, server_info): # if request_service.get_xml_string(server_info, 'PairStatus') != '1': # return AbstractPairingManager.STATE_NOT_PAIRED # else: # return AbstractPairingManager.STATE_PAIRED # # @staticmethod # def generate_pin_string(): # return '%s%s%s%s' % (random.randint(0, 9), random.randint(0, 9), random.randint(0, 9), random.randint(0, 9)) # # @staticmethod # def update_dialog(pin, dialog): # pin_message = 'Please enter the PIN: %s' % pin # dialog.update(0, pin_message) . Output only the next line.
hash_algo = Sha256PairingHash()
Using the snippet: <|code_start|> return cipher.decrypt(buffer(data)) @staticmethod def _concat_bytes(a, b): c = bytearray(len(a) + len(b)) c[:] = a c[len(a):len(a) + len(b)] = b return c @staticmethod def _verify_signature(data, signature, cert): pubkey = cert.get_pubkey() pubkey.reset_context(md='sha256') pubkey.verify_init() pubkey.verify_update(data) return pubkey.verify_final(signature) @staticmethod def _sign_data(data, key): return key.sign(hashlib.sha256(data).digest(), 'sha256') def pair(self, request_service, server_info, dialog): pin = self.generate_pin_string() self.update_dialog(pin, dialog) server_major_version = request_service.get_server_major_version(server_info) if int(server_major_version) >= 7: hash_algo = Sha256PairingHash() else: <|code_end|> , determine the next line of code. You have imports: import binascii import hashlib import random from Crypto.Cipher import AES from Crypto.Util import asn1 from M2Crypto import X509 from resources.lib.nvhttp.pairinghash.sha256pairinghash import Sha256PairingHash from resources.lib.nvhttp.pairinghash.sha1pairinghash import Sha1PairingHash from resources.lib.nvhttp.pairingmanager.abstractpairingmanager import AbstractPairingManager and context (class names, function names, or code) available: # Path: resources/lib/nvhttp/pairinghash/sha256pairinghash.py # class Sha256PairingHash(AbstractPairingHash): # def get_hash_length(self): # return 32 # # def hash_data(self, data): # m = hashlib.sha256() # m.update(data) # return bytearray(m.digest()) # # Path: resources/lib/nvhttp/pairinghash/sha1pairinghash.py # class Sha1PairingHash(AbstractPairingHash): # def get_hash_length(self): # return 20 # # def hash_data(self, data): # m = hashlib.sha1() # m.update(data) # return bytearray(m.digest()) # # Path: resources/lib/nvhttp/pairingmanager/abstractpairingmanager.py # class AbstractPairingManager(object): # __metaclass__ = ABCMeta # # STATE_NOT_PAIRED = 0 # STATE_PAIRED = 1 # STATE_PIN_WRONG = 2 # STATE_FAILED = 3 # # @abstractmethod # def pair(self, request_service, server_info, dialog): # pass # # def unpair(self, request_service, server_info): # try: # request_service.open_http_connection( # request_service.base_url_http + '/unpair?' + request_service.build_uid_uuid_string(), # True # ) # except ValueError: # # Unpairing a host needs to be fire and forget # pass # # @staticmethod # def get_pair_state(request_service, server_info): # if request_service.get_xml_string(server_info, 'PairStatus') != '1': # return AbstractPairingManager.STATE_NOT_PAIRED # else: # return AbstractPairingManager.STATE_PAIRED # # @staticmethod # def generate_pin_string(): # return '%s%s%s%s' % (random.randint(0, 9), random.randint(0, 9), random.randint(0, 9), random.randint(0, 9)) # # @staticmethod # def update_dialog(pin, dialog): # pin_message = 'Please enter the PIN: %s' % pin # dialog.update(0, pin_message) . Output only the next line.
hash_algo = Sha1PairingHash()
Predict the next line for this snippet: <|code_start|> class DeviceWrapper: def __init__(self): self.devices = [] self.init_devices() def init_devices(self): input_bus = '/proc/bus/input/devices' if not os.path.exists(input_bus): message = 'Input bus (%s) could not be accessed.' % input_bus raise OSError(message) with open(input_bus) as f: device = None for line in f.readlines(): if line.startswith('I:'): <|code_end|> with the help of current file imports: import os import re from resources.lib.model.inputdevice import InputDevice and context from other files: # Path: resources/lib/model/inputdevice.py # class InputDevice: # def __init__(self): # self.name = None # self.handlers = [] # self.mapping = None # # def is_kbd(self): # return False # # found_kbd = False # # found_js = False # # for _handler in self.handlers: # # if _handler[:-1] == 'kbd': # # found_kbd = True # # if _handler[:-1] == 'js': # # found_js = True # # # # return found_kbd and not found_js # # def is_mouse(self): # return False # # found_mouse = False # # found_js = False # # for _handler in self.handlers: # # if _handler[:-1] == 'mouse': # # found_mouse = True # # if _handler[:-1] == 'js': # # found_js = True # # # # return found_mouse and not found_js # # def is_none_device(self): # return self.name == 'None (Disabled)' # # def get_evdev(self): # for handler in self.handlers: # if handler[:-1] == 'event': # return os.path.join('/dev/input', handler) , which may contain function names, class names, or code. Output only the next line.
device = InputDevice()
Using the snippet: <|code_start|> return 'OMDB' def get_game_information(self, nvapp): request_name = nvapp.title.replace(" ", "+").replace(":", "") response = self._gather_information(nvapp, request_name) response.name = nvapp.title return response def return_paths(self): return [self.cover_cache, self.api_cache] def is_enabled(self): return self.core.get_setting('enable_omdb', bool) def _gather_information(self, nvapp, game): game_cover_path = self._set_up_path(os.path.join(self.cover_cache, nvapp.id)) game_cache_path = self._set_up_path(os.path.join(self.api_cache, nvapp.id)) json_file = self._get_json_data(game_cache_path, game) try: json_data = json.load(open(json_file)) except: xbmcgui.Dialog().notification( self.core.string('name'), self.core.string('scraper_failed') % (game, self.name()) ) if json_file is not None and os.path.isfile(json_file): os.remove(json_file) <|code_end|> , determine the next line of code. You have imports: import json import os import urllib2 import xbmcgui from xbmcswift2 import xbmcgui from abcscraper import AbstractScraper from resources.lib.model.apiresponse import ApiResponse and context (class names, function names, or code) available: # Path: resources/lib/model/apiresponse.py # class ApiResponse: # def __init__(self, name=None, year=None, genre=None, plot=None, posters=None, fanarts=None): # if genre is None: # genre = [] # if posters is None: # posters = [] # if fanarts is None: # fanarts = {} # # self.name = name # self.year = year # self.genre = genre # self.plot = plot # self.posters = posters # self.fanarts = fanarts # # @classmethod # def from_dict(cls, name=None, year=None, genre=None, plot=None, posters=None, fanarts=None, **kwargs): # return cls(name, year, genre, plot, posters, fanarts) . Output only the next line.
return ApiResponse()
Here is a snippet: <|code_start|> self.settings_hash = self._get_settings_hash() self.settings_dict = {} def _get_settings_hash(self): settings_file = open(self.settings_path, 'rb') hasher = hashlib.sha256() blocksize = 65536 buf = settings_file.read(blocksize) while len(buf) > 0: hasher.update(buf) buf = settings_file.read(blocksize) return hasher.hexdigest() def _reload_settings(self): if self._get_settings_hash() != self.settings_hash: etree = ET.ElementTree(file=self.settings_path) self.settings_tree = etree.getroot() def get_settings(self): if self.settings_hash == self._get_settings_hash() and len(self.settings_dict) > 0: self.update_values() return self.settings_dict else: self._reload_settings() cat_prio = 1 for category in self.settings_tree.findall('category'): cat_label_id = category.get('label') cat_label = self.core.string(int(cat_label_id)) <|code_end|> . Write the next line using the current file imports: import hashlib import os import xml.etree.ElementTree as ET from resources.lib.model.settings.category import Category from resources.lib.model.settings.setting import Setting and context from other files: # Path: resources/lib/model/settings/category.py # class Category(object): # def __init__(self, cat_id, cat_label, priority): # self.cat_id = cat_id # self.cat_label = cat_label # self.priority = priority # self.settings = {} # # Path: resources/lib/model/settings/setting.py # class Setting(object): # def __init__(self, setting_id, setting_label, priority, *args, **kwargs): # self.setting_id = setting_id # self.setting_label = setting_label # self.priority = priority # # if 'type' in kwargs.keys(): # self.type = kwargs['type'] # else: # self.type = None # TODO: This should never happen # # if 'default' in kwargs.keys(): # self.default = kwargs['default'] # else: # self.default = None # # if 'visible' in kwargs.keys(): # self.visible = kwargs['visible'] # else: # self.visible = None # # if 'enable' in kwargs.keys(): # self.enable = kwargs['enable'] # else: # self.enable = None # # if 'values' in kwargs.keys(): # self.values = kwargs['values'] # TODO: Parse into list # else: # self.values = None # # if 'range' in kwargs.keys(): # self.range = kwargs['range'] # TODO: Parse into list # else: # self.range = None # # if 'option' in kwargs.keys(): # self.option = kwargs['option'] # else: # self.option = None # # if 'subsetting' in kwargs.keys(): # self.subsetting = kwargs['subsetting'] # else: # self.subsetting = None # # if 'current_value' in kwargs.keys(): # self.current_value = kwargs['current_value'] # else: # self.current_value = self.default # # if 'action' in kwargs.keys(): # self.route = kwargs['action'] # else: # self.route = None # # if 'file_mask' in kwargs.keys(): # self.file_mask = kwargs['file_mask'] # else: # self.file_mask = "" , which may include functions, classes, or code. Output only the next line.
cat = Category(cat_label_id, cat_label, cat_prio)
Continue the code snippet: <|code_start|> def get_settings(self): if self.settings_hash == self._get_settings_hash() and len(self.settings_dict) > 0: self.update_values() return self.settings_dict else: self._reload_settings() cat_prio = 1 for category in self.settings_tree.findall('category'): cat_label_id = category.get('label') cat_label = self.core.string(int(cat_label_id)) cat = Category(cat_label_id, cat_label, cat_prio) cat_prio += 1 setting_prio = 1 for setting in category.findall('setting'): if setting.get('label') is not None: setting_label_id = setting.get('label') setting_id = setting.get('id') setting_label = self.core.string(int(setting_label_id)) setting_args = {} for item in setting.items(): setting_args[item[0]] = item[1] current_value = self.core.get_setting(setting_id) setting_args['current_value'] = current_value <|code_end|> . Use current file imports: import hashlib import os import xml.etree.ElementTree as ET from resources.lib.model.settings.category import Category from resources.lib.model.settings.setting import Setting and context (classes, functions, or code) from other files: # Path: resources/lib/model/settings/category.py # class Category(object): # def __init__(self, cat_id, cat_label, priority): # self.cat_id = cat_id # self.cat_label = cat_label # self.priority = priority # self.settings = {} # # Path: resources/lib/model/settings/setting.py # class Setting(object): # def __init__(self, setting_id, setting_label, priority, *args, **kwargs): # self.setting_id = setting_id # self.setting_label = setting_label # self.priority = priority # # if 'type' in kwargs.keys(): # self.type = kwargs['type'] # else: # self.type = None # TODO: This should never happen # # if 'default' in kwargs.keys(): # self.default = kwargs['default'] # else: # self.default = None # # if 'visible' in kwargs.keys(): # self.visible = kwargs['visible'] # else: # self.visible = None # # if 'enable' in kwargs.keys(): # self.enable = kwargs['enable'] # else: # self.enable = None # # if 'values' in kwargs.keys(): # self.values = kwargs['values'] # TODO: Parse into list # else: # self.values = None # # if 'range' in kwargs.keys(): # self.range = kwargs['range'] # TODO: Parse into list # else: # self.range = None # # if 'option' in kwargs.keys(): # self.option = kwargs['option'] # else: # self.option = None # # if 'subsetting' in kwargs.keys(): # self.subsetting = kwargs['subsetting'] # else: # self.subsetting = None # # if 'current_value' in kwargs.keys(): # self.current_value = kwargs['current_value'] # else: # self.current_value = self.default # # if 'action' in kwargs.keys(): # self.route = kwargs['action'] # else: # self.route = None # # if 'file_mask' in kwargs.keys(): # self.file_mask = kwargs['file_mask'] # else: # self.file_mask = "" . Output only the next line.
_setting = Setting(setting_id, setting_label, setting_prio, **setting_args)
Given the code snippet: <|code_start|> if self.year is None: self.year = other.year if self.genre is None: self.genre = sorted(other.genre, key=str.lower) elif other.genre is not None: self.genre = sorted(list(set(self.genre) | set(other.genre)), key=str.lower) if self.plot is None: self.plot = other.plot elif other.plot is not None and len(other.plot) > len(self.plot): self.plot = other.plot if self.posters is None: self.posters = other.posters elif other.posters is not None: self.posters = list(set(self.posters) | set(other.posters)) if self.fanarts is None: self.fanarts = other.fanarts elif other.fanarts is not None: new_dict = self.fanarts.copy() new_dict.update(other.fanarts) self.fanarts = new_dict if self.selected_fanart is None or self.selected_fanart == '': self.selected_fanart = other.selected_fanart def get_fanart(self, alt): if self.fanarts is None: <|code_end|> , generate the next line using the imports in this file: import os import subprocess from resources.lib.model.fanart import Fanart and context (functions, classes, or occasionally code) from other files: # Path: resources/lib/model/fanart.py # class Fanart: # def __init__(self, original=None, thumb=None): # self.original = original # self.thumb = thumb # # def get_original(self): # return self.original # # def set_original(self, original): # self.original = original # # def get_thumb(self): # return self.thumb # # def set_thumb(self, thumb): # self.thumb = thumb . Output only the next line.
return Fanart(alt, alt)
Here is a snippet: <|code_start|> file_path = update.file_path with open(file_path, 'wb') as asset: asset.write(urllib2.urlopen(update.asset_url).read()) asset.close() zip_file = zipfile.ZipFile(file_path) zip_file.extractall(self.core.internal_path, self._get_members(zip_file)) xbmcgui.Dialog().ok( self.core.string('name'), 'Luna has been updated to version %s and will now relaunch.' % update.update_version ) xbmc.executebuiltin('RunPlugin(\'script.luna\')') def _get_members(self, zip_file): parts = [] for name in zip_file.namelist(): if not name.endswith('/'): parts.append(name.split('/')[:-1]) prefix = os.path.commonprefix(parts) or '' if prefix: prefix = '/'.join(prefix) + '/' offset = len(prefix) for zipinfo in zip_file.infolist(): name = zipinfo.filename if len(name) > offset: zipinfo.filename = name[offset:] yield zipinfo def parse_release_information(self, release): <|code_end|> . Write the next line using the current file imports: import json import os import re import urllib2 import zipfile import xbmc import xbmcaddon import xbmcgui from resources.lib.model.update import Update from resources.lib.views.updateinfo import UpdateInfo and context from other files: # Path: resources/lib/model/update.py # class Update: # def __init__(self, current_version=None, update_version=None, asset_url=None, asset_name=None, changelog=None, # file_path=None): # self.current_version = current_version, # self.update_version = update_version, # self.asset_url = asset_url, # self.asset_name = asset_name, # self.changelog = changelog # self.file_path = file_path # # Path: resources/lib/views/updateinfo.py # class UpdateInfo(pyxbmct.AddonDialogWindow): # def __init__(self, controller, update, title=''): # super(UpdateInfo, self).__init__(title) # self.controller = controller # self.update = update # background = None # if self.controller.get_active_skin() == 'skin.osmc': # media_path = '/usr/share/kodi/addons/skin.osmc/media' # if os.path.exists(media_path): # background = os.path.join(media_path, 'dialogs/DialogBackground_old.png') # # if background is not None: # self.background.setImage(background) # self.removeControl(self.title_background) # self.removeControl(self.window_close_button) # self.removeControl(self.title_bar) # # # init controls # self.version = None # self.changelog = None # self.button_update = None # self.button_cancel = None # # self.setGeometry(1280, 720, 12, 6, padding=60) # self.set_info_controls(update) # self.set_active_controls() # self.set_navigation() # self.connect(pyxbmct.ACTION_NAV_BACK, self.close) # # def set_info_controls(self, update): # update_headline = 'Luna %s available' % update.update_version # title_label = pyxbmct.Label(update_headline, alignment=pyxbmct.ALIGN_LEFT, font='XLarge', textColor=COLOR_HEADING) # self.placeControl(title_label, 0, 0, 2, 3) # # changelog_label = pyxbmct.Label('Changelog', alignment=pyxbmct.ALIGN_LEFT, font='Med', textColor=COLOR_DETAILS) # self.placeControl(changelog_label, 2, 0) # # self.changelog = pyxbmct.TextBox(font='Med') # self.placeControl(self.changelog, 4, 0, 6, 6) # self.changelog.setText(update.changelog) # self.changelog.autoScroll(delay=5000, time=2000, repeat=10000) # # def set_active_controls(self): # self.button_update = pyxbmct.Button('Update', focusTexture='', noFocusTexture='', focusedColor=COLOR_FO, # textColor=COLOR_NF, font='Med', alignment=pyxbmct.ALIGN_LEFT) # self.placeControl(self.button_update, 11, 0) # self.connect(self.button_update, self.do_update) # # self.button_cancel = pyxbmct.Button('Cancel', focusTexture='', noFocusTexture='', # focusedColor=COLOR_FO, textColor=COLOR_NF, font='Med', # alignment=pyxbmct.ALIGN_LEFT) # self.placeControl(self.button_cancel, 11, 1, columnspan=2) # self.connect(self.button_cancel, self.cancel) # # def set_navigation(self): # self.button_update.controlRight(self.button_cancel) # self.button_update.controlLeft(self.button_cancel) # self.button_cancel.controlRight(self.button_update) # self.button_cancel.controlLeft(self.button_update) # # self.setFocus(self.button_update) # # def do_update(self): # self.controller.do_update(self.update) # self.close() # # def cancel(self): # self.close() # # def setAnimation(self, control): # control.setAnimations( # [ # ('WindowOpen', 'effect=fade start=0 end=100 time=500',), # ('WindowClose', 'effect=fade start=100 end=0 time=500',) # ] # ) , which may include functions, classes, or code. Output only the next line.
update = Update()
Next line prediction: <|code_start|> return None if not pre_updates_enabled: self.parse_release_information(response) else: for release in response: self.logger.info(release) if re.match(self.regexp, release['tag_name'].strip('v')).group() > self.current_version: self.parse_release_information(release) update_storage['checked'] = True update_storage.sync() xbmc.log("[script.luna.updater]: Checking for update ... done") if update is not None: xbmcgui.Dialog().notification( self.core.string('name'), self.core.string('update_available') % update.update_version ) return update else: xbmcgui.Dialog().notification( self.core.string('name'), self.core.string('no_update_available') ) return None else: xbmc.log("[script.luna.updater]: Checking for update ... done") def initiate_update(self, update): if update.asset_name is not None: <|code_end|> . Use current file imports: (import json import os import re import urllib2 import zipfile import xbmc import xbmcaddon import xbmcgui from resources.lib.model.update import Update from resources.lib.views.updateinfo import UpdateInfo) and context including class names, function names, or small code snippets from other files: # Path: resources/lib/model/update.py # class Update: # def __init__(self, current_version=None, update_version=None, asset_url=None, asset_name=None, changelog=None, # file_path=None): # self.current_version = current_version, # self.update_version = update_version, # self.asset_url = asset_url, # self.asset_name = asset_name, # self.changelog = changelog # self.file_path = file_path # # Path: resources/lib/views/updateinfo.py # class UpdateInfo(pyxbmct.AddonDialogWindow): # def __init__(self, controller, update, title=''): # super(UpdateInfo, self).__init__(title) # self.controller = controller # self.update = update # background = None # if self.controller.get_active_skin() == 'skin.osmc': # media_path = '/usr/share/kodi/addons/skin.osmc/media' # if os.path.exists(media_path): # background = os.path.join(media_path, 'dialogs/DialogBackground_old.png') # # if background is not None: # self.background.setImage(background) # self.removeControl(self.title_background) # self.removeControl(self.window_close_button) # self.removeControl(self.title_bar) # # # init controls # self.version = None # self.changelog = None # self.button_update = None # self.button_cancel = None # # self.setGeometry(1280, 720, 12, 6, padding=60) # self.set_info_controls(update) # self.set_active_controls() # self.set_navigation() # self.connect(pyxbmct.ACTION_NAV_BACK, self.close) # # def set_info_controls(self, update): # update_headline = 'Luna %s available' % update.update_version # title_label = pyxbmct.Label(update_headline, alignment=pyxbmct.ALIGN_LEFT, font='XLarge', textColor=COLOR_HEADING) # self.placeControl(title_label, 0, 0, 2, 3) # # changelog_label = pyxbmct.Label('Changelog', alignment=pyxbmct.ALIGN_LEFT, font='Med', textColor=COLOR_DETAILS) # self.placeControl(changelog_label, 2, 0) # # self.changelog = pyxbmct.TextBox(font='Med') # self.placeControl(self.changelog, 4, 0, 6, 6) # self.changelog.setText(update.changelog) # self.changelog.autoScroll(delay=5000, time=2000, repeat=10000) # # def set_active_controls(self): # self.button_update = pyxbmct.Button('Update', focusTexture='', noFocusTexture='', focusedColor=COLOR_FO, # textColor=COLOR_NF, font='Med', alignment=pyxbmct.ALIGN_LEFT) # self.placeControl(self.button_update, 11, 0) # self.connect(self.button_update, self.do_update) # # self.button_cancel = pyxbmct.Button('Cancel', focusTexture='', noFocusTexture='', # focusedColor=COLOR_FO, textColor=COLOR_NF, font='Med', # alignment=pyxbmct.ALIGN_LEFT) # self.placeControl(self.button_cancel, 11, 1, columnspan=2) # self.connect(self.button_cancel, self.cancel) # # def set_navigation(self): # self.button_update.controlRight(self.button_cancel) # self.button_update.controlLeft(self.button_cancel) # self.button_cancel.controlRight(self.button_update) # self.button_cancel.controlLeft(self.button_update) # # self.setFocus(self.button_update) # # def do_update(self): # self.controller.do_update(self.update) # self.close() # # def cancel(self): # self.close() # # def setAnimation(self, control): # control.setAnimations( # [ # ('WindowOpen', 'effect=fade start=0 end=100 time=500',), # ('WindowClose', 'effect=fade start=100 end=0 time=500',) # ] # ) . Output only the next line.
window = UpdateInfo(self, update, 'Update to Luna %s' % self.update_version)
Given snippet: <|code_start|> def init_devices(self): cards_file = '/proc/asound/cards' with open(cards_file) as f: cards = f.readlines() f.close() for card in cards: match = re.match(self.CARDS_REGEX, card) if match: curr_idx = match.group(1) curr_id = match.group(2) curr_name = match.group(3) for device in self.get_card_info(curr_idx, curr_id, curr_name): self.devices.append(device) def get_card_info(self, idx, audio_id, audio_name): card_info_dir = os.path.abspath(os.path.join('/proc/asound/', 'card%s' % idx)) subdevices = [x for x in next(os.walk(card_info_dir))] subdevices_info = [] for subdevice in subdevices[1]: card_info_file = os.path.join(subdevices[0], subdevice, 'info') if not os.path.isfile(card_info_file): return with open(card_info_file) as f: card_info = f.readlines() f.close() <|code_end|> , continue by predicting the next line. Consider current file imports: import os import re import xbmc from resources.lib.model.audiodevice import AudioDevice and context: # Path: resources/lib/model/audiodevice.py # class AudioDevice: # def __init__(self): # self.original_name = None # self.card = None # self.device = None # self.subdevice = None # self.stream = None # self.id = None # self.name = None # self.subname = None # self.cls = None # self.subcls = None # self.subdevices_count = None # self.subdevices_avail = None # self.handler = '' # # def get_name(self): # if self.original_name == self.id: # return '%s - %s' % (self.id, self.name) # else: # return '%s - %s' % (self.id, self.original_name) which might include code, classes, or functions. Output only the next line.
device = AudioDevice()