Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Next line prediction: <|code_start|> def url(self, route="/", query={}, **route_args): """Returns the URL of the remote Igord server with the given route """ _route = route if route_args: _route = re.sub("<([^>:]*)(:[^>]*)?>", "{\\1}", _route) _route = _route.format(**route_args) _query = "?" + urllib.urlencode(query.items()) if query else "" if "<" in _route: self.logger.debug("Route: %s" % route) self.logger.debug("RouteArgs: %s" % route_args) self.logger.debug("Query: %s" % query) self.logger.debug("New Route: %s" % _route) self.logger.debug("New Query: %s" % _query) raise RuntimeError("Some placeholders weren't filled in route.") return "http://{host}:{port}{route}{query}".format(host=self.host, port=self.port, route=_route, query=_query) def route_request(self, route, **route_args): """Request a route and return an XML tree """ url = self.url(route, {"format": "xml"}, **route_args) pagedata = self._http.request(url) tree = etree.XML(pagedata) if pagedata else None return tree def jobs(self): <|code_end|> . Use current file imports: (from igor.common import routes from lxml import etree import io import logging import os import re import subprocess import tarfile import tempfile import time import urllib import urllib2) and context including class names, function names, or small code snippets from other files: # Path: igor/common.py # class routes(object): # static_ui_data = '/ui/<filename>' # static_data = '/static/data/<filename>' # # testsuite_submit = '/jobs/submit/<tname>/with/<pname>/on/<hname>' # # jobs = '/jobs' # job = '/jobs/<cookie>' # job_start = '/jobs/<cookie>/start' # job_abort = '/jobs/<cookie>/abort' # job_status = '/jobs/<cookie>/status' # job_report = '/jobs/<cookie>/report' # job_report_junit = '/jobs/<cookie>/report/junit' # job_testsuite = '/jobs/<cookie>/testsuite' # job_artifacts = '/jobs/<cookie>/artifacts' # job_artifacts_archive = '/jobs/<cookie>/archive' # FIXME # job_artifact = '/jobs/<cookie>/artifacts/<name>' # # job_step_skip = '/jobs/<cookie>/step/<n:int>/skip' # job_step_finish = '/jobs/<cookie>/step/<n:int>/<result:re:success|failed>' # job_step_result = '/jobs/<cookie>/step/<n:int>/result' # job_step_annotate = '/jobs/<cookie>/step/current/annotate' # # job_set_boot_profile = '/jobs/<cookie>/set/enable_pxe/<enable_pxe>' # job_set_kernelargs = '/jobs/<cookie>/set/kernelargs/<kernelargs>' # # job_bootstrap = '/testjob/<cookie>' # # testsuites = '/testsuites' # testsuites_validate = '/testsuites/validate' # testsuite_summary = '/testsuites/<name>/summary' # testsuite_archive = '/testsuites/<name>/download' # # testplans = '/testplans' # testplan = '/testplans/<name>' # testplan_start = '/testplans/<name>/submit' # testplan_abort = '/testplans/<name>/abort' # testplan_status = '/testplans/<name>/status' # testplan_report = '/testplans/<name>/report' # testplan_report_junit = '/testplans/<name>/report/junit' # testplan_summary = '' # # profiles = '/profiles' # profile = '/profiles/<pname>' # profile_delete = '/profiles/<pname>/remove' # profile_set_kernelargs = '/profiles/<pname>/kargs' # # hosts = '/hosts' # # testcase_source = '/testcases/<suitename>/<setname>/<casename>/source' # # server_log = '/server/log' # # datastore = '/store' # datastore_file = '/store/<filename>' # datastore_file_trigger = '/store/<filename>/trigger' . Output only the next line.
return self.route_request(routes.jobs)
Given snippet: <|code_start|> self.filename = filename self.size = size self.format = format class Layout(DiskImage): ''' An image specififcation for a VMHost. This are actually params for truncate and parted. Parameters ---------- size : int-like Size in GB label : string, optional label in ['gpt', 'mbr', 'loop'] partitions : Array of Partitions ''' label = None partitions = None def __init__(self, size, partitions, label="gpt", filename=None): super(Layout, self).__init__(filename, size or 4, "raw") if label not in ["gpt", "mbr"]: raise Exception("Disk label must be gpt or mbr") self.partitions = partitions or [{}] self.label = label def create(self, session_dir): if self.filename is None: <|code_end|> , continue by predicting the next line. Consider current file imports: import os from igor import log from igor.daemon import main from igor.utils import run and context: # Path: igor/log.py # def configure(fn): # def backlog(): # def getLogger(name): # # Path: igor/daemon/main.py # class UpdateableObject(object): # class Host(UpdateableObject): # class Profile(UpdateableObject): # class Origin(object): # class Inventory(object): # class JobSpec(UpdateableObject): # class Testplan(object): # class Testsuite(object): # class Testset(object): # class Testcase(object): # class TestSession(UpdateableObject): # def __init__(self, **kwargs): # def update_props(self, kwargs): # def prepare(self): # def start(self): # def get_name(self): # def get_mac_address(self): # def purge(self): # def __to_dict__(self): # def get_name(self): # def assign_to(self, host, additional_kargs=""): # def enable_pxe(self, enable): # def kargs(self, kargs): # def revoke_from(self, host): # def delete(self): # def __repr__(self): # def __to_dict__(self): # def name(self): # def items(self): # def lookup(self, name): # def create_item(self, **kwargs): # def __to_dict__(self): # def __init__(self, plans={}, testsuites={}, profiles={}, hosts={}): # def _add_origins(self, k, origins): # def _items(self, k): # def _lookup(self, k, q=None): # def plans(self, q=None): # def testsuites(self, q=None): # def profiles(self, q=None): # def hosts(self, q=None): # def check(self): # def create_profile(self, oname, pname, kernel, initrd, kargs): # def __to_dict__(self): # def __str__(self): # def __init__(self, name, job_layouts, inventory=None): # def timeout(self): # def job_specs(self): # def spec_from_layout(self, layout): # def _parse_toplevel_field_value(self, key, value): # def __str__(self): # def __to_dict__(self): # def __hash__(self): # def __init__(self, name, testsets=[]): # def testcases(self): # def libs(self): # def timeout(self): # def __str__(self): # def __to_dict__(self): # def get_archive(self, subdir="testcases"): # def __add_testcases_to_archive(self, archive, subdir): # def __add_testcase_to_archive(self, archive, arcname, testcase): # def __add_data_to_archive(self, archive, arcname, data): # def __add_libs_to_archive(self, archive, subdir): # def validate(self): # def __init__(self, name, testcases=[], libs=None): # def testcases(self): # def libs(self, libs=None): # def timeout(self): # def add(self, cs): # def __str__(self): # def __to_dict__(self): # def __init__(self, filename=None, name=None): # def source(self): # def __str__(self): # def __to_dict__(self): # def __init__(self, cookie, session_path, cleanup=True): # def remove(self): # def remove_artifacts(self): # def __artifacts_path(self, name=""): # def add_artifact(self, name, data): # def get_artifact(self, name): # def artifacts(self, use_abs=False): # def get_artifacts_archive(self, selection=None): # def __enter__(self): # def __exit__(self, _type, value, traceback): # # Path: igor/utils.py # def run(cmd, with_retval=False): # import subprocess # logger.debug("Running: %s" % cmd) # child = subprocess.Popen(cmd, shell=True, # stdout=subprocess.PIPE, # stderr=subprocess.PIPE) # (stdout, stderr) = child.communicate() # # pylint: disable-msg=E1101 # child.wait() # if stderr: # logger.warning(stderr) # r = str(stdout).strip() # if with_retval: # r = (child.returncode, str(stdout).strip()) # # pylint: enable-msg=E1101 # return r which might include code, classes, or functions. Output only the next line.
self.filename = run("mktemp --tmpdir='%s' 'vmimage-XXXX.img'" %
Predict the next line for this snippet: <|code_start|> def follow_events(server, port): r = redis.Redis(host=server, port=int(port)) p = r.pubsub() p.subscribe(common.REDIS_EVENTS_PUBSUB_CHANNEL_NAME) for obj in p.listen(): event = None xmlstr = str(obj["data"]).strip() if not xmlstr.startswith("<"): # Sometimes just an int is sent ... continue try: event = etree.XML(xmlstr) except: logging.exception("Failed to parse: %s -> %s" % (obj, xmlstr)) if event is not None and event.attrib: yield event.attrib p.unsubscribe(common.REDIS_EVENTS_PUBSUB_CHANNEL_NAME) p.close() def __FIXME_retrieve_report(remote, port, sessionid): url = REPORTBASE.format(host=remote, port=port, sessionid=sessionid) print("Fetching %s" % url) #statusdata = urllib2.urlopen(url).read() _statusfile = "/home/fdeutsch/dev/ovirt/igor/daemon/igor/data/st.xml" #_junitfile = "/home/fdeutsch/dev/ovirt/igor/daemon/igor/data/st.junit.xml" statusdata = open(_statusfile).read() <|code_end|> with the help of current file imports: from igor import reports, common from lxml import etree import logging import sys import redis and context from other files: # Path: igor/reports.py # BASE_PATH = os.path.dirname(os.path.abspath(__file__)) # REPORT_PATH = os.path.join(BASE_PATH, "data") # TRANSFORM_MAP = { # "job-rst": os.path.join(REPORT_PATH, "job-report.rst.xsl"), # "job-junit": os.path.join(REPORT_PATH, "job-report.junit.xsl"), # "testplan-rst": os.path.join(REPORT_PATH, "testplan-report.rst.xsl"), # "testplan-junit-xml": os.path.join(REPORT_PATH, # "testplan-report.junit.xsl"), # } # def job_status_to_report_json(txt): # def job_status_to_report(d): # def job_status_to_junit(d): # def testplan_status_to_report(d): # def testplan_status_to_junit_report(d): # def _map_transform(d, t, rootname="status"): # def transform_dict(stylefile, d, rootname): # def transform_xml(stylefile, xml): # def to_xml_str(etree_obj): # # Path: igor/common.py # REDIS_EVENTS_PUBSUB_CHANNEL_NAME = "igor.daemon.events" # class routes(object): , which may contain function names, class names, or code. Output only the next line.
xsltfile = reports.TRANSFORM_MAP["job-junit"]
Continue the code snippet: <|code_start|># # Copyright (C) 2013 Red Hat, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation; either version 2.1 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # Author: Fabian Deutsch <fabiand@fedoraproject.org> # # # DESCRTIPTION # REPORTBASE = "http://{host}:{port}/jobs/{sessionid}/status?format=xml" def follow_events(server, port): r = redis.Redis(host=server, port=int(port)) p = r.pubsub() <|code_end|> . Use current file imports: from igor import reports, common from lxml import etree import logging import sys import redis and context (classes, functions, or code) from other files: # Path: igor/reports.py # BASE_PATH = os.path.dirname(os.path.abspath(__file__)) # REPORT_PATH = os.path.join(BASE_PATH, "data") # TRANSFORM_MAP = { # "job-rst": os.path.join(REPORT_PATH, "job-report.rst.xsl"), # "job-junit": os.path.join(REPORT_PATH, "job-report.junit.xsl"), # "testplan-rst": os.path.join(REPORT_PATH, "testplan-report.rst.xsl"), # "testplan-junit-xml": os.path.join(REPORT_PATH, # "testplan-report.junit.xsl"), # } # def job_status_to_report_json(txt): # def job_status_to_report(d): # def job_status_to_junit(d): # def testplan_status_to_report(d): # def testplan_status_to_junit_report(d): # def _map_transform(d, t, rootname="status"): # def transform_dict(stylefile, d, rootname): # def transform_xml(stylefile, xml): # def to_xml_str(etree_obj): # # Path: igor/common.py # REDIS_EVENTS_PUBSUB_CHANNEL_NAME = "igor.daemon.events" # class routes(object): . Output only the next line.
p.subscribe(common.REDIS_EVENTS_PUBSUB_CHANNEL_NAME)
Next line prediction: <|code_start|> """Returns the source of this testcase """ src = None with open(self.filename, "r") as f: src = f.read() return src def __str__(self): return "%s (%s, %s)" % (self.name, self.filename, self.timeout) def __to_dict__(self): """Is used to derive a JSON and XML description. """ return self.__dict__ class TestSession(UpdateableObject): dirname = None cookie = None do_cleanup = False def __init__(self, cookie, session_path, cleanup=True): assert session_path is not None, "session path can not be None" self.do_cleanup = cleanup self.cookie = cookie self.dirname = tempfile.mkdtemp(suffix="-" + self.cookie, dir=session_path) os.mkdir(self.__artifacts_path()) <|code_end|> . Use current file imports: (from igor import log from igor.utils import run, update_properties_only import io import os import random import tarfile import tempfile import time) and context including class names, function names, or small code snippets from other files: # Path: igor/log.py # def configure(fn): # def backlog(): # def getLogger(name): # # Path: igor/utils.py # def run(cmd, with_retval=False): # import subprocess # logger.debug("Running: %s" % cmd) # child = subprocess.Popen(cmd, shell=True, # stdout=subprocess.PIPE, # stderr=subprocess.PIPE) # (stdout, stderr) = child.communicate() # # pylint: disable-msg=E1101 # child.wait() # if stderr: # logger.warning(stderr) # r = str(stdout).strip() # if with_retval: # r = (child.returncode, str(stdout).strip()) # # pylint: enable-msg=E1101 # return r # # def update_properties_only(obj, kwargs): # """Update the properties of obj according to kwargs if obj has a property # of these names # # Args: # obj: The object to update # kwargs: A dict mapping (prop, value) # # >>> class Foo(object): # ... bar = None # ... def baz(self): # ... return "baz" # # >>> class Foo2(Foo): # ... bar2 = None # # >>> kwargs = {"bar": True, "xyz": False, "baz": None, "bar2": True} # >>> obj = Foo2() # >>> obj.bar # # >>> update_properties_only(obj, kwargs) # # >>> obj.bar # True # >>> obj.bar2 # True # >>> hasattr(obj, "xyz") # False # >>> callable(obj.baz) # True # """ # # subt = type(obj) # tdict = {} # for t in subt.mro(): # tdict.update(t.__dict__) # allowed_args = {k: v for k, v in kwargs.items() # if k in tdict and not callable(tdict[k])} # logger.debug("Updating properties of %s: %s" % (obj, allowed_args)) # if kwargs and not allowed_args: # logger.debug("Request to update props, but non are allowed") # logger.debug("Requested: '%s'" % kwargs) # logger.debug("Object props: '%s'" % tdict) # obj.__dict__.update(allowed_args) . Output only the next line.
run("chmod -R a+X '%s'" % self.dirname)
Using the snippet: <|code_start|> self.variables["planid"] = self.id logger.debug("Replacing vars in spec %s: %s" % (self.name, self.variables)) for layout in self.job_layouts: """A generator is used (yield), because a followup spec might depend on infos from a previous spec (e.g. a host gets created) """ yield self.spec_from_layout(layout) def spec_from_layout(self, layout): spec = JobSpec() logger.debug("Creating spec for job layout '%s'" % layout) for k, func in [("testsuite", self.inventory.testsuites), ("profile", self.inventory.profiles), ("host", self.inventory.hosts), ("additional_kargs", lambda x: x)]: kwargs = {} if k in layout and layout[k] is not None: v, kwargs = self._parse_toplevel_field_value(k, layout[k]) layout[k] = v else: layout[k] = "" logger.debug("Handling top-level item '%s', with kwargs '%s'" % (k, kwargs)) item = func(v) logger.debug("New item: %s" % item) if kwargs and hasattr(item, "__dict__"): <|code_end|> , determine the next line of code. You have imports: from igor import log from igor.utils import run, update_properties_only import io import os import random import tarfile import tempfile import time and context (class names, function names, or code) available: # Path: igor/log.py # def configure(fn): # def backlog(): # def getLogger(name): # # Path: igor/utils.py # def run(cmd, with_retval=False): # import subprocess # logger.debug("Running: %s" % cmd) # child = subprocess.Popen(cmd, shell=True, # stdout=subprocess.PIPE, # stderr=subprocess.PIPE) # (stdout, stderr) = child.communicate() # # pylint: disable-msg=E1101 # child.wait() # if stderr: # logger.warning(stderr) # r = str(stdout).strip() # if with_retval: # r = (child.returncode, str(stdout).strip()) # # pylint: enable-msg=E1101 # return r # # def update_properties_only(obj, kwargs): # """Update the properties of obj according to kwargs if obj has a property # of these names # # Args: # obj: The object to update # kwargs: A dict mapping (prop, value) # # >>> class Foo(object): # ... bar = None # ... def baz(self): # ... return "baz" # # >>> class Foo2(Foo): # ... bar2 = None # # >>> kwargs = {"bar": True, "xyz": False, "baz": None, "bar2": True} # >>> obj = Foo2() # >>> obj.bar # # >>> update_properties_only(obj, kwargs) # # >>> obj.bar # True # >>> obj.bar2 # True # >>> hasattr(obj, "xyz") # False # >>> callable(obj.baz) # True # """ # # subt = type(obj) # tdict = {} # for t in subt.mro(): # tdict.update(t.__dict__) # allowed_args = {k: v for k, v in kwargs.items() # if k in tdict and not callable(tdict[k])} # logger.debug("Updating properties of %s: %s" % (obj, allowed_args)) # if kwargs and not allowed_args: # logger.debug("Request to update props, but non are allowed") # logger.debug("Requested: '%s'" % kwargs) # logger.debug("Object props: '%s'" % tdict) # obj.__dict__.update(allowed_args) . Output only the next line.
update_properties_only(item, kwargs)
Predict the next line after this snippet: <|code_start|> job = self.__igorapi().job(_args.sessionid) def job_reportxml_cb(updated_sessiondid): if updated_sessiondid == _args.sessionid: # Only update screen if "our" job changed return job.report_junit() return None return self.watch_events(job_reportxml_cb) def do_watch_testplan(self, line): """watch_testplan <testplanname> Watch a running testplan """ pargs = [("testplanname", {"nargs": "?", "default": self.ctx.session})] _args = self._parse_do_args("watch_testplan", line, pargs) testplan = self.__igorapi().testplan(_args.testplanname) def job_reportxml_cb(updated_sessiondid): return testplan.report_junit() return self.watch_events(job_reportxml_cb) def watch_events(self, reportxml_cb): is_passed = False remote = self.ctx.remote event_port = self.ctx.event_port <|code_end|> using the current file's imports: from igor.client import junitless, event from igor.client.main import IgordAPI from lxml import etree import argparse import cmd import logging import os import shlex import subprocess import urlparse and any relevant context from other files: # Path: igor/client/junitless.py # def clearscreen(): # def __init__(self, txt, with_markup=True): # def plain(self): # def bold(self): # def italic(self): # def underline(self): # def inverse(self): # def markup(self): # def black(self): # def red(self): # def green(self): # def yellow(self): # def blue(self): # def magenta(self): # def cyan(self): # def white(self): # def write(self, msg): # def writeln(self, msg): # def indented(self, size=1): # def __enter__(self): # def __exit__(self, exc_type, exc_value, traceback): # def _indented(self, msg): # def warn(self, msg=None): # def error(self, msg): # def ok(self, msg=None): # def success(self, msg): # def fail(self, msg): # def header(self, msg): # def subhead(self, msg): # def debug(self, msg): # def __init__(self, log=None): # def from_file(self, filename): # def from_txt(self, txt): # def from_xml(self, xml): # def build(self, node): # def _build_testsuites(self, node): # def _build_testsuite(self, node): # def _build_testcase(self, node): # def sanitize_name(name): # def pp(tree): # class ansi(unicode): # class Log(object): # class IndentedLog(Log): # class LogBuilder(object): # # Path: igor/client/event.py # REPORTBASE = "http://{host}:{port}/jobs/{sessionid}/status?format=xml" # def follow_events(server, port): # def __FIXME_retrieve_report(remote, port, sessionid): # # Path: igor/client/main.py # class IgordAPI(object): # """An interface to the basic REST-API of igor # """ # _http = None # _logger = None # host = None # port = None # # def __init__(self, host="127.0.0.1", port=8080): # self.host = host # self.port = port # self._http = HTTPHelper() # self._logger = logging.getLogger(self.__module__) # # @property # def logger(self): # return self._logger # # def url(self, route="/", query={}, **route_args): # """Returns the URL of the remote Igord server with the given route # """ # _route = route # if route_args: # _route = re.sub("<([^>:]*)(:[^>]*)?>", "{\\1}", _route) # _route = _route.format(**route_args) # _query = "?" + urllib.urlencode(query.items()) if query else "" # if "<" in _route: # self.logger.debug("Route: %s" % route) # self.logger.debug("RouteArgs: %s" % route_args) # self.logger.debug("Query: %s" % query) # self.logger.debug("New Route: %s" % _route) # self.logger.debug("New Query: %s" % _query) # raise RuntimeError("Some placeholders weren't filled in route.") # return "http://{host}:{port}{route}{query}".format(host=self.host, # port=self.port, # route=_route, # query=_query) # # def route_request(self, route, **route_args): # """Request a route and return an XML tree # """ # url = self.url(route, {"format": "xml"}, **route_args) # pagedata = self._http.request(url) # tree = etree.XML(pagedata) if pagedata else None # return tree # # def jobs(self): # return self.route_request(routes.jobs) # # def testsuites(self): # return self.route_request(routes.testsuites) # # def hosts(self): # return self.route_request(routes.hosts) # # def profiles(self): # return self.route_request(routes.profiles) # # def testplans(self): # return self.route_request(routes.testplans) # # def testsuite(self, name): # return TestsuiteAPI(self.host, self.port, name) # # def job(self, sessionid): # return JobAPI(self.host, self.port, sessionid) # # def profile(self, name): # return ProfileAPI(self.host, self.port, name) # # def testplan(self, name): # return TestplanAPI(self.host, self.port, name) # # def datastore(self): # return DatastoreAPI(self.host, self.port) . Output only the next line.
builder = junitless.LogBuilder()
Continue the code snippet: <|code_start|> _args = self._parse_do_args("watch_testplan", line, pargs) testplan = self.__igorapi().testplan(_args.testplanname) def job_reportxml_cb(updated_sessiondid): return testplan.report_junit() return self.watch_events(job_reportxml_cb) def watch_events(self, reportxml_cb): is_passed = False remote = self.ctx.remote event_port = self.ctx.event_port builder = junitless.LogBuilder() def parse_state(reportxml): gp = lambda p: reportxml.xpath("//property[@name='%s']/@value" % p) states = gp("status") is_endstates = gp("is_endstate") is_endstate = all(n == "True" for n in is_endstates) return states, is_endstate try: reportxml = reportxml_cb(None) junitless.clearscreen() builder.from_xml(reportxml) builder.log.writeln("Waiting for event ...") <|code_end|> . Use current file imports: from igor.client import junitless, event from igor.client.main import IgordAPI from lxml import etree import argparse import cmd import logging import os import shlex import subprocess import urlparse and context (classes, functions, or code) from other files: # Path: igor/client/junitless.py # def clearscreen(): # def __init__(self, txt, with_markup=True): # def plain(self): # def bold(self): # def italic(self): # def underline(self): # def inverse(self): # def markup(self): # def black(self): # def red(self): # def green(self): # def yellow(self): # def blue(self): # def magenta(self): # def cyan(self): # def white(self): # def write(self, msg): # def writeln(self, msg): # def indented(self, size=1): # def __enter__(self): # def __exit__(self, exc_type, exc_value, traceback): # def _indented(self, msg): # def warn(self, msg=None): # def error(self, msg): # def ok(self, msg=None): # def success(self, msg): # def fail(self, msg): # def header(self, msg): # def subhead(self, msg): # def debug(self, msg): # def __init__(self, log=None): # def from_file(self, filename): # def from_txt(self, txt): # def from_xml(self, xml): # def build(self, node): # def _build_testsuites(self, node): # def _build_testsuite(self, node): # def _build_testcase(self, node): # def sanitize_name(name): # def pp(tree): # class ansi(unicode): # class Log(object): # class IndentedLog(Log): # class LogBuilder(object): # # Path: igor/client/event.py # REPORTBASE = "http://{host}:{port}/jobs/{sessionid}/status?format=xml" # def follow_events(server, port): # def __FIXME_retrieve_report(remote, port, sessionid): # # Path: igor/client/main.py # class IgordAPI(object): # """An interface to the basic REST-API of igor # """ # _http = None # _logger = None # host = None # port = None # # def __init__(self, host="127.0.0.1", port=8080): # self.host = host # self.port = port # self._http = HTTPHelper() # self._logger = logging.getLogger(self.__module__) # # @property # def logger(self): # return self._logger # # def url(self, route="/", query={}, **route_args): # """Returns the URL of the remote Igord server with the given route # """ # _route = route # if route_args: # _route = re.sub("<([^>:]*)(:[^>]*)?>", "{\\1}", _route) # _route = _route.format(**route_args) # _query = "?" + urllib.urlencode(query.items()) if query else "" # if "<" in _route: # self.logger.debug("Route: %s" % route) # self.logger.debug("RouteArgs: %s" % route_args) # self.logger.debug("Query: %s" % query) # self.logger.debug("New Route: %s" % _route) # self.logger.debug("New Query: %s" % _query) # raise RuntimeError("Some placeholders weren't filled in route.") # return "http://{host}:{port}{route}{query}".format(host=self.host, # port=self.port, # route=_route, # query=_query) # # def route_request(self, route, **route_args): # """Request a route and return an XML tree # """ # url = self.url(route, {"format": "xml"}, **route_args) # pagedata = self._http.request(url) # tree = etree.XML(pagedata) if pagedata else None # return tree # # def jobs(self): # return self.route_request(routes.jobs) # # def testsuites(self): # return self.route_request(routes.testsuites) # # def hosts(self): # return self.route_request(routes.hosts) # # def profiles(self): # return self.route_request(routes.profiles) # # def testplans(self): # return self.route_request(routes.testplans) # # def testsuite(self, name): # return TestsuiteAPI(self.host, self.port, name) # # def job(self, sessionid): # return JobAPI(self.host, self.port, sessionid) # # def profile(self, name): # return ProfileAPI(self.host, self.port, name) # # def testplan(self, name): # return TestplanAPI(self.host, self.port, name) # # def datastore(self): # return DatastoreAPI(self.host, self.port) . Output only the next line.
for ev in event.follow_events(remote, event_port):
Using the snippet: <|code_start|> return True def do_env(self, args): """env Get environment variables """ env = self.ctx.__dict__ print("\n".join("%s: %s" % i for i in env.items())) print("(%d variables)" % len(env)) def _parse_do_args(self, prog, line, arguments): parser = argparse.ArgumentParser(prog=prog) for args, kwargs in arguments: args = (args,) if type(args) in [str, unicode] else args parser.add_argument(*args, **kwargs) return parser.parse_args(shlex.split(line)) def do_set(self, line): """set <key> [<value>] Set environment variables """ pargs = [("key", {}), ("value", {"nargs": "?"})] _args = self._parse_do_args("set", line, pargs) if _args.value: self.ctx.__dict__[_args.key] = _args.value def __igorapi(self): remote = self.ctx.remote port = self.ctx.port <|code_end|> , determine the next line of code. You have imports: from igor.client import junitless, event from igor.client.main import IgordAPI from lxml import etree import argparse import cmd import logging import os import shlex import subprocess import urlparse and context (class names, function names, or code) available: # Path: igor/client/junitless.py # def clearscreen(): # def __init__(self, txt, with_markup=True): # def plain(self): # def bold(self): # def italic(self): # def underline(self): # def inverse(self): # def markup(self): # def black(self): # def red(self): # def green(self): # def yellow(self): # def blue(self): # def magenta(self): # def cyan(self): # def white(self): # def write(self, msg): # def writeln(self, msg): # def indented(self, size=1): # def __enter__(self): # def __exit__(self, exc_type, exc_value, traceback): # def _indented(self, msg): # def warn(self, msg=None): # def error(self, msg): # def ok(self, msg=None): # def success(self, msg): # def fail(self, msg): # def header(self, msg): # def subhead(self, msg): # def debug(self, msg): # def __init__(self, log=None): # def from_file(self, filename): # def from_txt(self, txt): # def from_xml(self, xml): # def build(self, node): # def _build_testsuites(self, node): # def _build_testsuite(self, node): # def _build_testcase(self, node): # def sanitize_name(name): # def pp(tree): # class ansi(unicode): # class Log(object): # class IndentedLog(Log): # class LogBuilder(object): # # Path: igor/client/event.py # REPORTBASE = "http://{host}:{port}/jobs/{sessionid}/status?format=xml" # def follow_events(server, port): # def __FIXME_retrieve_report(remote, port, sessionid): # # Path: igor/client/main.py # class IgordAPI(object): # """An interface to the basic REST-API of igor # """ # _http = None # _logger = None # host = None # port = None # # def __init__(self, host="127.0.0.1", port=8080): # self.host = host # self.port = port # self._http = HTTPHelper() # self._logger = logging.getLogger(self.__module__) # # @property # def logger(self): # return self._logger # # def url(self, route="/", query={}, **route_args): # """Returns the URL of the remote Igord server with the given route # """ # _route = route # if route_args: # _route = re.sub("<([^>:]*)(:[^>]*)?>", "{\\1}", _route) # _route = _route.format(**route_args) # _query = "?" + urllib.urlencode(query.items()) if query else "" # if "<" in _route: # self.logger.debug("Route: %s" % route) # self.logger.debug("RouteArgs: %s" % route_args) # self.logger.debug("Query: %s" % query) # self.logger.debug("New Route: %s" % _route) # self.logger.debug("New Query: %s" % _query) # raise RuntimeError("Some placeholders weren't filled in route.") # return "http://{host}:{port}{route}{query}".format(host=self.host, # port=self.port, # route=_route, # query=_query) # # def route_request(self, route, **route_args): # """Request a route and return an XML tree # """ # url = self.url(route, {"format": "xml"}, **route_args) # pagedata = self._http.request(url) # tree = etree.XML(pagedata) if pagedata else None # return tree # # def jobs(self): # return self.route_request(routes.jobs) # # def testsuites(self): # return self.route_request(routes.testsuites) # # def hosts(self): # return self.route_request(routes.hosts) # # def profiles(self): # return self.route_request(routes.profiles) # # def testplans(self): # return self.route_request(routes.testplans) # # def testsuite(self, name): # return TestsuiteAPI(self.host, self.port, name) # # def job(self, sessionid): # return JobAPI(self.host, self.port, sessionid) # # def profile(self, name): # return ProfileAPI(self.host, self.port, name) # # def testplan(self, name): # return TestplanAPI(self.host, self.port, name) # # def datastore(self): # return DatastoreAPI(self.host, self.port) . Output only the next line.
return IgordAPI(remote, port)
Using the snippet: <|code_start|> if category == "host": origins += [("files", HostsOrigin(CONFIG["hosts"]["paths"]))] return origins class Host(main.Host): """Represents a real server. Wich is currently just specified by a name and it's MAC address. """ name = None mac = None poweron_script = None poweroff_script = None def prepare(self): # Not needed with real hosts pass def get_name(self): return self.name def get_mac_address(self): return self.mac def start(self): logger.debug("Powering on %s: %s" % <|code_end|> , determine the next line of code. You have imports: from igor import log, utils from igor.daemon import main import glob import os import tarfile import tempfile import yaml and context (class names, function names, or code) available: # Path: igor/log.py # def configure(fn): # def backlog(): # def getLogger(name): # # Path: igor/utils.py # def run(cmd, with_retval=False): # def dict_to_args(d): # def cmdline_to_dict(cmdline): # def __init__(self, f): # def __enter__(self): # def __exit__(self, typ, value, traceback): # def mount(self, iso): # def umount(self): # def mount(self, iso): # def umount(self): # def mount(self, iso): # def umount(self): # def surl(number): # def __init__(self, cleanfiles=[]): # def __enter__(self): # def __exit__(self, typ, value, traceback): # def cleanfile(self, f): # def clean(self): # def scanf(pat, txt): # def synchronized(lock): # def wrap(f): # def newFunction(*args, **kw): # def xor(a, b): # def parse_bool(s): # def __init__(self, interval=10): # def _debug(self, msg): # def run(self): # def stop(self): # def is_stopped(self): # def work(self): # def __init__(self, n): # def transition(self, val): # def __str__(self): # def __eq__(self, other): # def __ne__(self, other): # def obj2xml(root, obj, as_string=False): # def __open(filename, fileobj=None): # def __read_yaml(filename, fileobj=None): # def update_properties_only(obj, kwargs): # class MountedArchive: # class GvfsMountedArchive(MountedArchive): # class LosetupMountedArchive(MountedArchive): # class TemporaryDirectory: # class PollingWorkerDaemon(threading.Thread): # class State(object): # class Factory(object): # # Path: igor/daemon/main.py # class UpdateableObject(object): # class Host(UpdateableObject): # class Profile(UpdateableObject): # class Origin(object): # class Inventory(object): # class JobSpec(UpdateableObject): # class Testplan(object): # class Testsuite(object): # class Testset(object): # class Testcase(object): # class TestSession(UpdateableObject): # def __init__(self, **kwargs): # def update_props(self, kwargs): # def prepare(self): # def start(self): # def get_name(self): # def get_mac_address(self): # def purge(self): # def __to_dict__(self): # def get_name(self): # def assign_to(self, host, additional_kargs=""): # def enable_pxe(self, enable): # def kargs(self, kargs): # def revoke_from(self, host): # def delete(self): # def __repr__(self): # def __to_dict__(self): # def name(self): # def items(self): # def lookup(self, name): # def create_item(self, **kwargs): # def __to_dict__(self): # def __init__(self, plans={}, testsuites={}, profiles={}, hosts={}): # def _add_origins(self, k, origins): # def _items(self, k): # def _lookup(self, k, q=None): # def plans(self, q=None): # def testsuites(self, q=None): # def profiles(self, q=None): # def hosts(self, q=None): # def check(self): # def create_profile(self, oname, pname, kernel, initrd, kargs): # def __to_dict__(self): # def __str__(self): # def __init__(self, name, job_layouts, inventory=None): # def timeout(self): # def job_specs(self): # def spec_from_layout(self, layout): # def _parse_toplevel_field_value(self, key, value): # def __str__(self): # def __to_dict__(self): # def __hash__(self): # def __init__(self, name, testsets=[]): # def testcases(self): # def libs(self): # def timeout(self): # def __str__(self): # def __to_dict__(self): # def get_archive(self, subdir="testcases"): # def __add_testcases_to_archive(self, archive, subdir): # def __add_testcase_to_archive(self, archive, arcname, testcase): # def __add_data_to_archive(self, archive, arcname, data): # def __add_libs_to_archive(self, archive, subdir): # def validate(self): # def __init__(self, name, testcases=[], libs=None): # def testcases(self): # def libs(self, libs=None): # def timeout(self): # def add(self, cs): # def __str__(self): # def __to_dict__(self): # def __init__(self, filename=None, name=None): # def source(self): # def __str__(self): # def __to_dict__(self): # def __init__(self, cookie, session_path, cleanup=True): # def remove(self): # def remove_artifacts(self): # def __artifacts_path(self, name=""): # def add_artifact(self, name, data): # def get_artifact(self, name): # def artifacts(self, use_abs=False): # def get_artifacts_archive(self, selection=None): # def __enter__(self): # def __exit__(self, _type, value, traceback): . Output only the next line.
(self.get_name(), utils.run(self.poweron_script)))
Continue the code snippet: <|code_start|> logger = log.getLogger(__name__) def initialize_origins(category, CONFIG): origins = [] superorigin = TestDraftSuperOrigin(tempfile.mkdtemp()) if category == "testplan": origins += [("draft-files", superorigin.get_testplans_origin()), ("files", TestplansOrigin(CONFIG["testplans"]["paths"]))] if category == "testsuite": origins += [("draft-files", superorigin.get_testsuites_origin()), ("files", TestsuitesOrigin(CONFIG["testcases"]["paths"]))] if category == "host": origins += [("files", HostsOrigin(CONFIG["hosts"]["paths"]))] return origins <|code_end|> . Use current file imports: from igor import log, utils from igor.daemon import main import glob import os import tarfile import tempfile import yaml and context (classes, functions, or code) from other files: # Path: igor/log.py # def configure(fn): # def backlog(): # def getLogger(name): # # Path: igor/utils.py # def run(cmd, with_retval=False): # def dict_to_args(d): # def cmdline_to_dict(cmdline): # def __init__(self, f): # def __enter__(self): # def __exit__(self, typ, value, traceback): # def mount(self, iso): # def umount(self): # def mount(self, iso): # def umount(self): # def mount(self, iso): # def umount(self): # def surl(number): # def __init__(self, cleanfiles=[]): # def __enter__(self): # def __exit__(self, typ, value, traceback): # def cleanfile(self, f): # def clean(self): # def scanf(pat, txt): # def synchronized(lock): # def wrap(f): # def newFunction(*args, **kw): # def xor(a, b): # def parse_bool(s): # def __init__(self, interval=10): # def _debug(self, msg): # def run(self): # def stop(self): # def is_stopped(self): # def work(self): # def __init__(self, n): # def transition(self, val): # def __str__(self): # def __eq__(self, other): # def __ne__(self, other): # def obj2xml(root, obj, as_string=False): # def __open(filename, fileobj=None): # def __read_yaml(filename, fileobj=None): # def update_properties_only(obj, kwargs): # class MountedArchive: # class GvfsMountedArchive(MountedArchive): # class LosetupMountedArchive(MountedArchive): # class TemporaryDirectory: # class PollingWorkerDaemon(threading.Thread): # class State(object): # class Factory(object): # # Path: igor/daemon/main.py # class UpdateableObject(object): # class Host(UpdateableObject): # class Profile(UpdateableObject): # class Origin(object): # class Inventory(object): # class JobSpec(UpdateableObject): # class Testplan(object): # class Testsuite(object): # class Testset(object): # class Testcase(object): # class TestSession(UpdateableObject): # def __init__(self, **kwargs): # def update_props(self, kwargs): # def prepare(self): # def start(self): # def get_name(self): # def get_mac_address(self): # def purge(self): # def __to_dict__(self): # def get_name(self): # def assign_to(self, host, additional_kargs=""): # def enable_pxe(self, enable): # def kargs(self, kargs): # def revoke_from(self, host): # def delete(self): # def __repr__(self): # def __to_dict__(self): # def name(self): # def items(self): # def lookup(self, name): # def create_item(self, **kwargs): # def __to_dict__(self): # def __init__(self, plans={}, testsuites={}, profiles={}, hosts={}): # def _add_origins(self, k, origins): # def _items(self, k): # def _lookup(self, k, q=None): # def plans(self, q=None): # def testsuites(self, q=None): # def profiles(self, q=None): # def hosts(self, q=None): # def check(self): # def create_profile(self, oname, pname, kernel, initrd, kargs): # def __to_dict__(self): # def __str__(self): # def __init__(self, name, job_layouts, inventory=None): # def timeout(self): # def job_specs(self): # def spec_from_layout(self, layout): # def _parse_toplevel_field_value(self, key, value): # def __str__(self): # def __to_dict__(self): # def __hash__(self): # def __init__(self, name, testsets=[]): # def testcases(self): # def libs(self): # def timeout(self): # def __str__(self): # def __to_dict__(self): # def get_archive(self, subdir="testcases"): # def __add_testcases_to_archive(self, archive, subdir): # def __add_testcase_to_archive(self, archive, arcname, testcase): # def __add_data_to_archive(self, archive, arcname, data): # def __add_libs_to_archive(self, archive, subdir): # def validate(self): # def __init__(self, name, testcases=[], libs=None): # def testcases(self): # def libs(self, libs=None): # def timeout(self): # def add(self, cs): # def __str__(self): # def __to_dict__(self): # def __init__(self, filename=None, name=None): # def source(self): # def __str__(self): # def __to_dict__(self): # def __init__(self, cookie, session_path, cleanup=True): # def remove(self): # def remove_artifacts(self): # def __artifacts_path(self, name=""): # def add_artifact(self, name, data): # def get_artifact(self, name): # def artifacts(self, use_abs=False): # def get_artifacts_archive(self, selection=None): # def __enter__(self): # def __exit__(self, _type, value, traceback): . Output only the next line.
class Host(main.Host):
Given snippet: <|code_start|># # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # Author: Fabian Deutsch <fabiand@fedoraproject.org> # # -*- coding: utf-8 -*- logger = log.getLogger(__name__) class PhysicalVolume(object): image = None uuid = None def __init__(self, image): self.image = image def create(self): if not os.path.exists(self.image): raise Exception("Backing image does not exist: %s" % self.image) with self.losetup() as losetup: dev = losetup.device <|code_end|> , continue by predicting the next line. Consider current file imports: from igor import log from igor.utils import run import os and context: # Path: igor/log.py # def configure(fn): # def backlog(): # def getLogger(name): # # Path: igor/utils.py # def run(cmd, with_retval=False): # import subprocess # logger.debug("Running: %s" % cmd) # child = subprocess.Popen(cmd, shell=True, # stdout=subprocess.PIPE, # stderr=subprocess.PIPE) # (stdout, stderr) = child.communicate() # # pylint: disable-msg=E1101 # child.wait() # if stderr: # logger.warning(stderr) # r = str(stdout).strip() # if with_retval: # r = (child.returncode, str(stdout).strip()) # # pylint: enable-msg=E1101 # return r which might include code, classes, or functions. Output only the next line.
run("pvcreate -ff -y -v '%s'" % dev)
Given the code snippet: <|code_start|> class ConfigParser: ''' Class that contains functions to constuct the config map from the config file ''' configContent={} def __init__(self,fileName): ''' constructor that generates the map of the config file @param fileName: file containing config @type fileName: string ''' <|code_end|> , generate the next line using the imports in this file: from FileCacheManager import FileCacheManager and context (functions, classes, or occasionally code) from other files: # Path: FileCacheManager.py # class FileCacheManager: # filecontent=[] # def __init__(self,fileName): # ''' # constructor # @param fileName: filename containing config # @type fileName: parses the content and stores the lines in filecontent # ''' # f=open(fileName,'r') # for text in f.readlines(): # self.filecontent.append(text) . Output only the next line.
configFile=FileCacheManager(fileName)
Given the code snippet: <|code_start|> print "algo=", algo data1 = fileToTuples(infile1,delimiter) data2 = fileToTuples(infile2,delimiter) if algo == 'toposort': #dependency verification as multiple topo ordering possible depen_map = dict() for entry in data1: vid = int(entry[0]) val = int(entry[1]) depen_map[vid] = val for entry in data2: vid = int(entry[0]) vertex_rank = depen_map[vid] dependencies = entry[1].split(",") for val in dependencies: depen_rank = depen_map[int(val)] if vertex_rank <= depen_rank: return 1 return 0 else: if len(data1) != len(data2): return 1 else: for i,val in enumerate(data1): if(len(data1[i]) != len(data2[i])): return 1 if(data1[i] != data2[i]): <|code_end|> , generate the next line using the imports in this file: import sys,getopt from CommonDefs import CommonDefs and context (functions, classes, or occasionally code) from other files: # Path: CommonDefs.py # class CommonDefs: # ''' # Class containing some commonly used values # ''' # INT_MAX = "2147483647" # INT_MIN = "-2147483648" # DBL_MAX = "1.79E+308" # DBL_MIN = "1.79E+308" . Output only the next line.
if(CommonDefs.INT_MAX in data1[i] or CommonDefs.INT_MAX in data2[i]):
Continue the code snippet: <|code_start|> #!/usr/bin/python def main(argv): inputfile = '' outputfile = '' print inputfile, outputfile try: opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="]) except getopt.GetoptError: print 'test.py -i <inputfile> -o <outputfile>' sys.exit(2) for opt, arg in opts: if opt == '-h': print 'test.py -i <inputfile> -o <outputfile>' sys.exit() elif opt in ("-i", "--ifile"): inputfile = arg elif opt in ("-o", "--ofile"): outputfile = arg <|code_end|> . Use current file imports: from Grail import Grail import sys, getopt and context (classes, functions, or code) from other files: # Path: Grail.py # class Grail: # ''' # Class that contains functions to generate grail blocks # ''' # filename="" # blocks=[] # def __init__(self,filename): # ''' # constructor # @param filename: file containing config # @type filename: string # ''' # self.filename=filename # def getBlocks(self): # ''' # returns the blocks/sql statements generated by grail # ''' # return self.blocks # # def run(self): # ''' # invokes the config parser, generates the sql statements and runs optimizer # ''' # Parser=ConfigParser(self.filename) # config=Parser.configContent # translator=Translator(config) # translator.translate() # self.blocks=translator.getBlocks() # #op=Optimizer(translator.getConvertedOptions(),self.blocks,translator.getSenders()) # #op.run() . Output only the next line.
grail=Grail(inputfile)
Based on the snippet: <|code_start|> PKEY_FILENAME = os.path.sep.join([os.path.dirname(__file__), 'unit_test_key']) PUB_FILE = "%s.pub" % (PKEY_FILENAME,) class SSH2TestCase(unittest.TestCase): @classmethod def setUpClass(cls): _mask = int('0600') if version_info <= (2,) else 0o600 os.chmod(PKEY_FILENAME, _mask) <|code_end|> , predict the immediate next line with the help of imports: import unittest import pwd import os import socket from sys import version_info from .embedded_server.openssh import OpenSSHServer from ssh2.session import Session and context (classes, functions, sometimes code) from other files: # Path: tests/embedded_server/openssh.py # class OpenSSHServer(object): # # def __init__(self, port=2222): # self.port = port # self.server_proc = None # self._fix_masks() # self.make_config() # # def _fix_masks(self): # _mask = int('0600') if version_info <= (2,) else 0o600 # dir_mask = int('0755') if version_info <= (2,) else 0o755 # os.chmod(SERVER_KEY, _mask) # for _dir in [DIR_NAME, PDIR_NAME, PPDIR_NAME]: # os.chmod(_dir, dir_mask) # # def make_config(self): # with open(SSHD_CONFIG_TMPL) as fh: # tmpl = fh.read() # template = Template(tmpl) # with open(SSHD_CONFIG, 'w') as fh: # fh.write(template.render(parent_dir=os.path.abspath(DIR_NAME))) # fh.write(os.linesep) # # def start_server(self): # cmd = ['/usr/sbin/sshd', '-D', '-p', str(self.port), # '-h', SERVER_KEY, '-f', SSHD_CONFIG] # server = Popen(cmd) # self.server_proc = server # self._wait_for_port() # # def _wait_for_port(self): # sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # while sock.connect_ex(('127.0.0.1', self.port)) != 0: # sleep(.1) # sock.close() # # def stop(self): # if self.server_proc is not None and self.server_proc.returncode is None: # self.server_proc.terminate() # self.server_proc.wait() # # def __del__(self): # self.stop() # os.unlink(SSHD_CONFIG) . Output only the next line.
cls.server = OpenSSHServer()
Given snippet: <|code_start|> cpython = platform.python_implementation() == 'CPython' try: except ImportError: USING_CYTHON = False else: USING_CYTHON = True ON_RTD = os.environ.get('READTHEDOCS') == 'True' SYSTEM_LIBSSH2 = bool(os.environ.get('SYSTEM_LIBSSH2', 0)) or ON_RTD # Only build libssh if running a build if not SYSTEM_LIBSSH2 and (len(sys.argv) >= 2 and not ( '--help' in sys.argv[1:] or sys.argv[1] in ( '--help-commands', 'egg_info', '--version', 'clean', 'sdist', '--long-description')) and __name__ == '__main__'): <|code_end|> , continue by predicting the next line. Consider current file imports: import platform import os import sys import versioneer from glob import glob from multiprocessing import cpu_count from _setup_libssh2 import build_ssh2 from setuptools import setup, find_packages from Cython.Distutils.extension import Extension from Cython.Distutils import build_ext from setuptools import Extension and context: # Path: _setup_libssh2.py # def build_ssh2(): # if bool(os.environ.get('SYSTEM_LIBSSH', False)): # stderr.write("Using system libssh2..%s" % (os.sep)) # return # if os.path.exists('/usr/local/opt/openssl'): # os.environ['OPENSSL_ROOT_DIR'] = '/usr/local/opt/openssl' # # if not os.path.exists('src'): # os.mkdir('src') # # os.chdir('src') # check_call('cmake ../libssh2 -DBUILD_SHARED_LIBS=ON \ # -DENABLE_ZLIB_COMPRESSION=ON -DENABLE_CRYPT_NONE=ON \ # -DENABLE_MAC_NONE=ON -DCRYPTO_BACKEND=OpenSSL', # shell=True, env=os.environ) # check_call('cmake --build . --config Release', shell=True, env=os.environ) # os.chdir('..') # # for src in glob('src/src/libssh2.so*'): # copy2(src, 'ssh2/') which might include code, classes, or functions. Output only the next line.
build_ssh2()
Given snippet: <|code_start|> login_manager = LoginManager() @login_manager.user_loader def load_user(user_id): <|code_end|> , continue by predicting the next line. Consider current file imports: from flask_login import LoginManager from websitemixer.models import User and context: # Path: websitemixer/models.py # class User(db.Model): # __tablename__ = 'user' # id = db.Column( # 'id', # db.Integer, # primary_key=True, # autoincrement=True, index=True) # username = db.Column( # 'username', # db.String(255), # unique=True, # nullable=False, # index=True) # password = db.Column('password', db.String(255), nullable=False) # email = db.Column('email', db.String(50), nullable=False) # registered_on = db.Column('registered_on', db.DateTime) # admin = db.Column('admin', db.Integer, default=0) # name = db.Column('name', db.String(255)) # image = db.Column('image', db.String(255)) # facebook = db.Column('facebook', db.String(255)) # twitter = db.Column('twitter', db.String(255)) # google = db.Column('google', db.String(255)) # # #roles = relationship( # # 'Role', # # secondary=user_roles, # # backref=backref('user', lazy='dynamic'), # #) # # #posts = relationship( # # 'Post', # # secondary=user_posts, # # backref=backref('user', lazy='dynamic') # #) # # #comments = relationship( # # 'Comment', # # secondary=user_comments, # # backref=backref('user', lazy='dynamic') # #) # # #preferences = relationship( # # 'Preference', # # secondary=user_preferences, # # backref=backref('user', lazy='dynamic') # #) # # def __init__(self, username, password, email): # self.username = username # self.password = self.set_password(password) # self.email = email # self.registered_on = datetime.utcnow() # self.is_admin = 0 # # @classmethod # def get(kls, username): # """Returns User object by email. # # :param email: User's email address. # :type email: str # :returns: User() object of the corresponding # :user if found, otherwise None. # :rtype: instance or None # """ # return kls.query.filter(kls.username == username.lower()).first() # # @classmethod # def get_by_id(kls, id): # return kls.query.filter(kls.id == id).first() # # def delete_by_email(kls, email): # """Delete artifacts of a user account then the user account itself. # # :param email: User's email address. # :type email: str # """ # user = kls.query.filter(kls.email == email.lower()).first() # if user: # kls.query.filter(kls.email == email.lower()).first() # # @classmethod # def validate(kls, username, password): # """Validates user without returning a User() object. # # :param email: User's email address. # :type email: str # :param password: User's password. # :type password: str # :returns: True if email/password combo is valid, False if not. # :rtype: bool # """ # user = kls.get(username) # if user is None: # return False # else: # return user.check_password(str(password)) # # def set_password(self, password): # """Sets an encrypted password. # # :param password: User's password. # :type password: str # :returns: Password hash. # :rtype: str # """ # return passlib.hash.sha512_crypt.encrypt(password) # # def check_password(self, password): # """Checks password against stored password for the User() instance. # # :param password: User's password. # :type password: str # :returns: True if supplied password matches instance # :password, False if not. # :rtype: bool # """ # return passlib.hash.sha512_crypt.verify(password, self.password) # # def is_authenticated(self): # return True # # def is_active(self): # return True # # def is_anonymous(self): # return False # # def get_id(self): # return str(self.id) # # def is_admin(self): # if self.admin == 1: # return True # else: # return False # # def __repr__(self): # return "<User email={0}>".format(self.email) which might include code, classes, or functions. Output only the next line.
return User.get_by_id(user_id)
Here is a snippet: <|code_start|> def first_paragraph(content=""): # take content and return just the first <p></p> content, # used in blog loop template soup = BeautifulSoup(content, "html.parser") thespan = soup.find('p') if thespan is None: return '' else: return thespan.string def process_tags(tags): rettags = '' taglist = [x.strip() for x in tags.split(',')] for t in taglist: rettags = rettags + '<a href="/tag/'+t+'/">'+t+'</a> ' return rettags def is_admin(): <|code_end|> . Write the next line using the current file imports: from bs4 import BeautifulSoup from websitemixer.models import User and context from other files: # Path: websitemixer/models.py # class User(db.Model): # __tablename__ = 'user' # id = db.Column( # 'id', # db.Integer, # primary_key=True, # autoincrement=True, index=True) # username = db.Column( # 'username', # db.String(255), # unique=True, # nullable=False, # index=True) # password = db.Column('password', db.String(255), nullable=False) # email = db.Column('email', db.String(50), nullable=False) # registered_on = db.Column('registered_on', db.DateTime) # admin = db.Column('admin', db.Integer, default=0) # name = db.Column('name', db.String(255)) # image = db.Column('image', db.String(255)) # facebook = db.Column('facebook', db.String(255)) # twitter = db.Column('twitter', db.String(255)) # google = db.Column('google', db.String(255)) # # #roles = relationship( # # 'Role', # # secondary=user_roles, # # backref=backref('user', lazy='dynamic'), # #) # # #posts = relationship( # # 'Post', # # secondary=user_posts, # # backref=backref('user', lazy='dynamic') # #) # # #comments = relationship( # # 'Comment', # # secondary=user_comments, # # backref=backref('user', lazy='dynamic') # #) # # #preferences = relationship( # # 'Preference', # # secondary=user_preferences, # # backref=backref('user', lazy='dynamic') # #) # # def __init__(self, username, password, email): # self.username = username # self.password = self.set_password(password) # self.email = email # self.registered_on = datetime.utcnow() # self.is_admin = 0 # # @classmethod # def get(kls, username): # """Returns User object by email. # # :param email: User's email address. # :type email: str # :returns: User() object of the corresponding # :user if found, otherwise None. # :rtype: instance or None # """ # return kls.query.filter(kls.username == username.lower()).first() # # @classmethod # def get_by_id(kls, id): # return kls.query.filter(kls.id == id).first() # # def delete_by_email(kls, email): # """Delete artifacts of a user account then the user account itself. # # :param email: User's email address. # :type email: str # """ # user = kls.query.filter(kls.email == email.lower()).first() # if user: # kls.query.filter(kls.email == email.lower()).first() # # @classmethod # def validate(kls, username, password): # """Validates user without returning a User() object. # # :param email: User's email address. # :type email: str # :param password: User's password. # :type password: str # :returns: True if email/password combo is valid, False if not. # :rtype: bool # """ # user = kls.get(username) # if user is None: # return False # else: # return user.check_password(str(password)) # # def set_password(self, password): # """Sets an encrypted password. # # :param password: User's password. # :type password: str # :returns: Password hash. # :rtype: str # """ # return passlib.hash.sha512_crypt.encrypt(password) # # def check_password(self, password): # """Checks password against stored password for the User() instance. # # :param password: User's password. # :type password: str # :returns: True if supplied password matches instance # :password, False if not. # :rtype: bool # """ # return passlib.hash.sha512_crypt.verify(password, self.password) # # def is_authenticated(self): # return True # # def is_active(self): # return True # # def is_anonymous(self): # return False # # def get_id(self): # return str(self.id) # # def is_admin(self): # if self.admin == 1: # return True # else: # return False # # def __repr__(self): # return "<User email={0}>".format(self.email) , which may include functions, classes, or code. Output only the next line.
check = User.query.filter_by(id=session['user_id']).first()
Given snippet: <|code_start|>""" This module is used to translate Events from Marathon's EventBus system. See: * https://mesosphere.github.io/marathon/docs/event-bus.html * https://github.com/mesosphere/marathon/blob/master/src/main/scala/mesosphere/marathon/core/event/Events.scala """ <|code_end|> , continue by predicting the next line. Consider current file imports: from marathon.models.base import MarathonObject from marathon.models.app import MarathonHealthCheck from marathon.models.task import MarathonIpAddress from marathon.models.deployment import MarathonDeploymentPlan from marathon.exceptions import MarathonError and context: # Path: marathon/models/base.py # class MarathonObject: # """Base Marathon object.""" # # def __repr__(self): # return "{clazz}::{obj}".format(clazz=self.__class__.__name__, obj=self.to_json(minimal=False)) # # def __eq__(self, other): # try: # return self.__dict__ == other.__dict__ # except Exception: # return False # # def __hash__(self): # # Technically this class shouldn't be hashable because it often # # contains mutable fields, but in practice this class is used more # # like a record or namedtuple. # return hash(self.to_json()) # # def json_repr(self, minimal=False): # """Construct a JSON-friendly representation of the object. # # :param bool minimal: Construct a minimal representation of the object (ignore nulls and empty collections) # # :rtype: dict # """ # if minimal: # return {to_camel_case(k): v for k, v in vars(self).items() if (v or v is False or v == 0)} # else: # return {to_camel_case(k): v for k, v in vars(self).items()} # # @classmethod # def from_json(cls, attributes): # """Construct an object from a parsed response. # # :param dict attributes: object attributes from parsed response # """ # return cls(**{to_snake_case(k): v for k, v in attributes.items()}) # # def to_json(self, minimal=True): # """Encode an object as a JSON string. # # :param bool minimal: Construct a minimal representation of the object (ignore nulls and empty collections) # # :rtype: str # """ # if minimal: # return json.dumps(self.json_repr(minimal=True), cls=MarathonMinimalJsonEncoder, sort_keys=True) # else: # return json.dumps(self.json_repr(), cls=MarathonJsonEncoder, sort_keys=True) # # Path: marathon/models/app.py # class MarathonHealthCheck(MarathonObject): # # """Marathon health check. # # See https://mesosphere.github.io/marathon/docs/health-checks.html # # :param str command: health check command (if protocol == 'COMMAND') # :param int grace_period_seconds: how long to ignore health check failures on initial task launch (before first healthy status) # :param int interval_seconds: how long to wait between health checks # :param int max_consecutive_failures: max number of consecutive failures before the task should be killed # :param str path: health check target path (if protocol == 'HTTP') # :param int port_index: target port as indexed in app's `ports` array # :param str protocol: health check protocol ('HTTP', 'TCP', or 'COMMAND') # :param int timeout_seconds: how long before a waiting health check is considered failed # :param bool ignore_http1xx: Ignore HTTP informational status codes 100 to 199. # :param dict kwargs: additional arguments for forward compatibility # """ # # def __init__(self, command=None, grace_period_seconds=None, interval_seconds=None, max_consecutive_failures=None, # path=None, port_index=None, protocol=None, timeout_seconds=None, ignore_http1xx=None, **kwargs): # # if command is None: # self.command = None # elif isinstance(command, str): # self.command = { # "value": command # } # elif type(command) is dict and 'value' in command: # log.warn('Deprecated: Using command as dict instead of string is deprecated') # self.command = { # "value": command['value'] # } # else: # raise ValueError(f'Invalid command format: {command}') # # self.grace_period_seconds = grace_period_seconds # self.interval_seconds = interval_seconds # self.max_consecutive_failures = max_consecutive_failures # self.path = path # self.port_index = port_index # self.protocol = protocol # self.timeout_seconds = timeout_seconds # self.ignore_http1xx = ignore_http1xx # # additional not previously known healthcheck attributes # for k, v in kwargs.items(): # setattr(self, k, v) # # Path: marathon/models/task.py # class MarathonIpAddress(MarathonObject): # """ # """ # def __init__(self, ip_address=None, protocol=None): # self.ip_address = ip_address # self.protocol = protocol # # Path: marathon/models/deployment.py # class MarathonDeploymentPlan(MarathonObject): # # def __init__(self, original=None, target=None, # steps=None, id=None, version=None): # self.original = MarathonDeploymentOriginalState.from_json(original) # self.target = MarathonDeploymentTargetState.from_json(target) # self.steps = [MarathonDeploymentStep.from_json(x) for x in steps] # self.id = id # self.version = version # # Path: marathon/exceptions.py # class MarathonError(Exception): # pass which might include code, classes, or functions. Output only the next line.
class MarathonEvent(MarathonObject):
Using the snippet: <|code_start|>""" This module is used to translate Events from Marathon's EventBus system. See: * https://mesosphere.github.io/marathon/docs/event-bus.html * https://github.com/mesosphere/marathon/blob/master/src/main/scala/mesosphere/marathon/core/event/Events.scala """ class MarathonEvent(MarathonObject): """ The MarathonEvent base class handles the translation of Event objects sent by the Marathon server into library MarathonObjects. """ KNOWN_ATTRIBUTES = [] attribute_name_to_marathon_object = { # Allows embedding of MarathonObjects inside events. <|code_end|> , determine the next line of code. You have imports: from marathon.models.base import MarathonObject from marathon.models.app import MarathonHealthCheck from marathon.models.task import MarathonIpAddress from marathon.models.deployment import MarathonDeploymentPlan from marathon.exceptions import MarathonError and context (class names, function names, or code) available: # Path: marathon/models/base.py # class MarathonObject: # """Base Marathon object.""" # # def __repr__(self): # return "{clazz}::{obj}".format(clazz=self.__class__.__name__, obj=self.to_json(minimal=False)) # # def __eq__(self, other): # try: # return self.__dict__ == other.__dict__ # except Exception: # return False # # def __hash__(self): # # Technically this class shouldn't be hashable because it often # # contains mutable fields, but in practice this class is used more # # like a record or namedtuple. # return hash(self.to_json()) # # def json_repr(self, minimal=False): # """Construct a JSON-friendly representation of the object. # # :param bool minimal: Construct a minimal representation of the object (ignore nulls and empty collections) # # :rtype: dict # """ # if minimal: # return {to_camel_case(k): v for k, v in vars(self).items() if (v or v is False or v == 0)} # else: # return {to_camel_case(k): v for k, v in vars(self).items()} # # @classmethod # def from_json(cls, attributes): # """Construct an object from a parsed response. # # :param dict attributes: object attributes from parsed response # """ # return cls(**{to_snake_case(k): v for k, v in attributes.items()}) # # def to_json(self, minimal=True): # """Encode an object as a JSON string. # # :param bool minimal: Construct a minimal representation of the object (ignore nulls and empty collections) # # :rtype: str # """ # if minimal: # return json.dumps(self.json_repr(minimal=True), cls=MarathonMinimalJsonEncoder, sort_keys=True) # else: # return json.dumps(self.json_repr(), cls=MarathonJsonEncoder, sort_keys=True) # # Path: marathon/models/app.py # class MarathonHealthCheck(MarathonObject): # # """Marathon health check. # # See https://mesosphere.github.io/marathon/docs/health-checks.html # # :param str command: health check command (if protocol == 'COMMAND') # :param int grace_period_seconds: how long to ignore health check failures on initial task launch (before first healthy status) # :param int interval_seconds: how long to wait between health checks # :param int max_consecutive_failures: max number of consecutive failures before the task should be killed # :param str path: health check target path (if protocol == 'HTTP') # :param int port_index: target port as indexed in app's `ports` array # :param str protocol: health check protocol ('HTTP', 'TCP', or 'COMMAND') # :param int timeout_seconds: how long before a waiting health check is considered failed # :param bool ignore_http1xx: Ignore HTTP informational status codes 100 to 199. # :param dict kwargs: additional arguments for forward compatibility # """ # # def __init__(self, command=None, grace_period_seconds=None, interval_seconds=None, max_consecutive_failures=None, # path=None, port_index=None, protocol=None, timeout_seconds=None, ignore_http1xx=None, **kwargs): # # if command is None: # self.command = None # elif isinstance(command, str): # self.command = { # "value": command # } # elif type(command) is dict and 'value' in command: # log.warn('Deprecated: Using command as dict instead of string is deprecated') # self.command = { # "value": command['value'] # } # else: # raise ValueError(f'Invalid command format: {command}') # # self.grace_period_seconds = grace_period_seconds # self.interval_seconds = interval_seconds # self.max_consecutive_failures = max_consecutive_failures # self.path = path # self.port_index = port_index # self.protocol = protocol # self.timeout_seconds = timeout_seconds # self.ignore_http1xx = ignore_http1xx # # additional not previously known healthcheck attributes # for k, v in kwargs.items(): # setattr(self, k, v) # # Path: marathon/models/task.py # class MarathonIpAddress(MarathonObject): # """ # """ # def __init__(self, ip_address=None, protocol=None): # self.ip_address = ip_address # self.protocol = protocol # # Path: marathon/models/deployment.py # class MarathonDeploymentPlan(MarathonObject): # # def __init__(self, original=None, target=None, # steps=None, id=None, version=None): # self.original = MarathonDeploymentOriginalState.from_json(original) # self.target = MarathonDeploymentTargetState.from_json(target) # self.steps = [MarathonDeploymentStep.from_json(x) for x in steps] # self.id = id # self.version = version # # Path: marathon/exceptions.py # class MarathonError(Exception): # pass . Output only the next line.
'health_check': MarathonHealthCheck,
Next line prediction: <|code_start|>""" This module is used to translate Events from Marathon's EventBus system. See: * https://mesosphere.github.io/marathon/docs/event-bus.html * https://github.com/mesosphere/marathon/blob/master/src/main/scala/mesosphere/marathon/core/event/Events.scala """ class MarathonEvent(MarathonObject): """ The MarathonEvent base class handles the translation of Event objects sent by the Marathon server into library MarathonObjects. """ KNOWN_ATTRIBUTES = [] attribute_name_to_marathon_object = { # Allows embedding of MarathonObjects inside events. 'health_check': MarathonHealthCheck, 'plan': MarathonDeploymentPlan, <|code_end|> . Use current file imports: (from marathon.models.base import MarathonObject from marathon.models.app import MarathonHealthCheck from marathon.models.task import MarathonIpAddress from marathon.models.deployment import MarathonDeploymentPlan from marathon.exceptions import MarathonError) and context including class names, function names, or small code snippets from other files: # Path: marathon/models/base.py # class MarathonObject: # """Base Marathon object.""" # # def __repr__(self): # return "{clazz}::{obj}".format(clazz=self.__class__.__name__, obj=self.to_json(minimal=False)) # # def __eq__(self, other): # try: # return self.__dict__ == other.__dict__ # except Exception: # return False # # def __hash__(self): # # Technically this class shouldn't be hashable because it often # # contains mutable fields, but in practice this class is used more # # like a record or namedtuple. # return hash(self.to_json()) # # def json_repr(self, minimal=False): # """Construct a JSON-friendly representation of the object. # # :param bool minimal: Construct a minimal representation of the object (ignore nulls and empty collections) # # :rtype: dict # """ # if minimal: # return {to_camel_case(k): v for k, v in vars(self).items() if (v or v is False or v == 0)} # else: # return {to_camel_case(k): v for k, v in vars(self).items()} # # @classmethod # def from_json(cls, attributes): # """Construct an object from a parsed response. # # :param dict attributes: object attributes from parsed response # """ # return cls(**{to_snake_case(k): v for k, v in attributes.items()}) # # def to_json(self, minimal=True): # """Encode an object as a JSON string. # # :param bool minimal: Construct a minimal representation of the object (ignore nulls and empty collections) # # :rtype: str # """ # if minimal: # return json.dumps(self.json_repr(minimal=True), cls=MarathonMinimalJsonEncoder, sort_keys=True) # else: # return json.dumps(self.json_repr(), cls=MarathonJsonEncoder, sort_keys=True) # # Path: marathon/models/app.py # class MarathonHealthCheck(MarathonObject): # # """Marathon health check. # # See https://mesosphere.github.io/marathon/docs/health-checks.html # # :param str command: health check command (if protocol == 'COMMAND') # :param int grace_period_seconds: how long to ignore health check failures on initial task launch (before first healthy status) # :param int interval_seconds: how long to wait between health checks # :param int max_consecutive_failures: max number of consecutive failures before the task should be killed # :param str path: health check target path (if protocol == 'HTTP') # :param int port_index: target port as indexed in app's `ports` array # :param str protocol: health check protocol ('HTTP', 'TCP', or 'COMMAND') # :param int timeout_seconds: how long before a waiting health check is considered failed # :param bool ignore_http1xx: Ignore HTTP informational status codes 100 to 199. # :param dict kwargs: additional arguments for forward compatibility # """ # # def __init__(self, command=None, grace_period_seconds=None, interval_seconds=None, max_consecutive_failures=None, # path=None, port_index=None, protocol=None, timeout_seconds=None, ignore_http1xx=None, **kwargs): # # if command is None: # self.command = None # elif isinstance(command, str): # self.command = { # "value": command # } # elif type(command) is dict and 'value' in command: # log.warn('Deprecated: Using command as dict instead of string is deprecated') # self.command = { # "value": command['value'] # } # else: # raise ValueError(f'Invalid command format: {command}') # # self.grace_period_seconds = grace_period_seconds # self.interval_seconds = interval_seconds # self.max_consecutive_failures = max_consecutive_failures # self.path = path # self.port_index = port_index # self.protocol = protocol # self.timeout_seconds = timeout_seconds # self.ignore_http1xx = ignore_http1xx # # additional not previously known healthcheck attributes # for k, v in kwargs.items(): # setattr(self, k, v) # # Path: marathon/models/task.py # class MarathonIpAddress(MarathonObject): # """ # """ # def __init__(self, ip_address=None, protocol=None): # self.ip_address = ip_address # self.protocol = protocol # # Path: marathon/models/deployment.py # class MarathonDeploymentPlan(MarathonObject): # # def __init__(self, original=None, target=None, # steps=None, id=None, version=None): # self.original = MarathonDeploymentOriginalState.from_json(original) # self.target = MarathonDeploymentTargetState.from_json(target) # self.steps = [MarathonDeploymentStep.from_json(x) for x in steps] # self.id = id # self.version = version # # Path: marathon/exceptions.py # class MarathonError(Exception): # pass . Output only the next line.
'ip_address': MarathonIpAddress,
Based on the snippet: <|code_start|>""" This module is used to translate Events from Marathon's EventBus system. See: * https://mesosphere.github.io/marathon/docs/event-bus.html * https://github.com/mesosphere/marathon/blob/master/src/main/scala/mesosphere/marathon/core/event/Events.scala """ class MarathonEvent(MarathonObject): """ The MarathonEvent base class handles the translation of Event objects sent by the Marathon server into library MarathonObjects. """ KNOWN_ATTRIBUTES = [] attribute_name_to_marathon_object = { # Allows embedding of MarathonObjects inside events. 'health_check': MarathonHealthCheck, <|code_end|> , predict the immediate next line with the help of imports: from marathon.models.base import MarathonObject from marathon.models.app import MarathonHealthCheck from marathon.models.task import MarathonIpAddress from marathon.models.deployment import MarathonDeploymentPlan from marathon.exceptions import MarathonError and context (classes, functions, sometimes code) from other files: # Path: marathon/models/base.py # class MarathonObject: # """Base Marathon object.""" # # def __repr__(self): # return "{clazz}::{obj}".format(clazz=self.__class__.__name__, obj=self.to_json(minimal=False)) # # def __eq__(self, other): # try: # return self.__dict__ == other.__dict__ # except Exception: # return False # # def __hash__(self): # # Technically this class shouldn't be hashable because it often # # contains mutable fields, but in practice this class is used more # # like a record or namedtuple. # return hash(self.to_json()) # # def json_repr(self, minimal=False): # """Construct a JSON-friendly representation of the object. # # :param bool minimal: Construct a minimal representation of the object (ignore nulls and empty collections) # # :rtype: dict # """ # if minimal: # return {to_camel_case(k): v for k, v in vars(self).items() if (v or v is False or v == 0)} # else: # return {to_camel_case(k): v for k, v in vars(self).items()} # # @classmethod # def from_json(cls, attributes): # """Construct an object from a parsed response. # # :param dict attributes: object attributes from parsed response # """ # return cls(**{to_snake_case(k): v for k, v in attributes.items()}) # # def to_json(self, minimal=True): # """Encode an object as a JSON string. # # :param bool minimal: Construct a minimal representation of the object (ignore nulls and empty collections) # # :rtype: str # """ # if minimal: # return json.dumps(self.json_repr(minimal=True), cls=MarathonMinimalJsonEncoder, sort_keys=True) # else: # return json.dumps(self.json_repr(), cls=MarathonJsonEncoder, sort_keys=True) # # Path: marathon/models/app.py # class MarathonHealthCheck(MarathonObject): # # """Marathon health check. # # See https://mesosphere.github.io/marathon/docs/health-checks.html # # :param str command: health check command (if protocol == 'COMMAND') # :param int grace_period_seconds: how long to ignore health check failures on initial task launch (before first healthy status) # :param int interval_seconds: how long to wait between health checks # :param int max_consecutive_failures: max number of consecutive failures before the task should be killed # :param str path: health check target path (if protocol == 'HTTP') # :param int port_index: target port as indexed in app's `ports` array # :param str protocol: health check protocol ('HTTP', 'TCP', or 'COMMAND') # :param int timeout_seconds: how long before a waiting health check is considered failed # :param bool ignore_http1xx: Ignore HTTP informational status codes 100 to 199. # :param dict kwargs: additional arguments for forward compatibility # """ # # def __init__(self, command=None, grace_period_seconds=None, interval_seconds=None, max_consecutive_failures=None, # path=None, port_index=None, protocol=None, timeout_seconds=None, ignore_http1xx=None, **kwargs): # # if command is None: # self.command = None # elif isinstance(command, str): # self.command = { # "value": command # } # elif type(command) is dict and 'value' in command: # log.warn('Deprecated: Using command as dict instead of string is deprecated') # self.command = { # "value": command['value'] # } # else: # raise ValueError(f'Invalid command format: {command}') # # self.grace_period_seconds = grace_period_seconds # self.interval_seconds = interval_seconds # self.max_consecutive_failures = max_consecutive_failures # self.path = path # self.port_index = port_index # self.protocol = protocol # self.timeout_seconds = timeout_seconds # self.ignore_http1xx = ignore_http1xx # # additional not previously known healthcheck attributes # for k, v in kwargs.items(): # setattr(self, k, v) # # Path: marathon/models/task.py # class MarathonIpAddress(MarathonObject): # """ # """ # def __init__(self, ip_address=None, protocol=None): # self.ip_address = ip_address # self.protocol = protocol # # Path: marathon/models/deployment.py # class MarathonDeploymentPlan(MarathonObject): # # def __init__(self, original=None, target=None, # steps=None, id=None, version=None): # self.original = MarathonDeploymentOriginalState.from_json(original) # self.target = MarathonDeploymentTargetState.from_json(target) # self.steps = [MarathonDeploymentStep.from_json(x) for x in steps] # self.id = id # self.version = version # # Path: marathon/exceptions.py # class MarathonError(Exception): # pass . Output only the next line.
'plan': MarathonDeploymentPlan,
Continue the code snippet: <|code_start|> :param str version: version id :param str affected_pods: list of strings """ def __init__(self, affected_apps=None, current_actions=None, current_step=None, id=None, steps=None, total_steps=None, version=None, affected_pods=None): self.affected_apps = affected_apps self.current_actions = [ a if isinstance( a, MarathonDeploymentAction) else MarathonDeploymentAction.from_json(a) for a in (current_actions or []) ] self.current_step = current_step self.id = id self.steps = [self.parse_deployment_step(step) for step in (steps or [])] self.total_steps = total_steps self.version = version self.affected_pods = affected_pods def parse_deployment_step(self, step): if step.__class__ == dict: # This is what Marathon 1.0.0 returns: steps return MarathonDeploymentStep().from_json(step) elif step.__class__ == list: # This is Marathon < 1.0.0 style, a list of actions return [s if isinstance(s, MarathonDeploymentAction) else MarathonDeploymentAction.from_json(s) for s in step] else: return step <|code_end|> . Use current file imports: from .base import MarathonObject, MarathonResource, assert_valid_path and context (classes, functions, or code) from other files: # Path: marathon/models/base.py # class MarathonObject: # """Base Marathon object.""" # # def __repr__(self): # return "{clazz}::{obj}".format(clazz=self.__class__.__name__, obj=self.to_json(minimal=False)) # # def __eq__(self, other): # try: # return self.__dict__ == other.__dict__ # except Exception: # return False # # def __hash__(self): # # Technically this class shouldn't be hashable because it often # # contains mutable fields, but in practice this class is used more # # like a record or namedtuple. # return hash(self.to_json()) # # def json_repr(self, minimal=False): # """Construct a JSON-friendly representation of the object. # # :param bool minimal: Construct a minimal representation of the object (ignore nulls and empty collections) # # :rtype: dict # """ # if minimal: # return {to_camel_case(k): v for k, v in vars(self).items() if (v or v is False or v == 0)} # else: # return {to_camel_case(k): v for k, v in vars(self).items()} # # @classmethod # def from_json(cls, attributes): # """Construct an object from a parsed response. # # :param dict attributes: object attributes from parsed response # """ # return cls(**{to_snake_case(k): v for k, v in attributes.items()}) # # def to_json(self, minimal=True): # """Encode an object as a JSON string. # # :param bool minimal: Construct a minimal representation of the object (ignore nulls and empty collections) # # :rtype: str # """ # if minimal: # return json.dumps(self.json_repr(minimal=True), cls=MarathonMinimalJsonEncoder, sort_keys=True) # else: # return json.dumps(self.json_repr(), cls=MarathonJsonEncoder, sort_keys=True) # # class MarathonResource(MarathonObject): # # """Base Marathon resource.""" # # def __repr__(self): # if 'id' in list(vars(self).keys()): # return f"{self.__class__.__name__}::{self.id}" # else: # return "{clazz}::{obj}".format(clazz=self.__class__.__name__, obj=self.to_json()) # # def __eq__(self, other): # try: # return self.__dict__ == other.__dict__ # except Exception: # return False # # def __hash__(self): # # Technically this class shouldn't be hashable because it often # # contains mutable fields, but in practice this class is used more # # like a record or namedtuple. # return hash(self.to_json()) # # def __str__(self): # return f"{self.__class__.__name__}::" + str(self.__dict__) # # def assert_valid_path(path): # """Checks if a path is a correct format that Marathon expects. Raises ValueError if not valid. # # :param str path: The app id. # # :rtype: str # """ # if path is None: # return # # As seen in: # # https://github.com/mesosphere/marathon/blob/0c11661ca2f259f8a903d114ef79023649a6f04b/src/main/scala/mesosphere/marathon/state/PathId.scala#L71 # for id in filter(None, path.strip('/').split('/')): # if not ID_PATTERN.match(id): # raise ValueError( # 'invalid path (allowed: lowercase letters, digits, hyphen, "/", ".", ".."): %r' % path) # return path . Output only the next line.
class MarathonDeploymentAction(MarathonObject):
Using the snippet: <|code_start|> self.steps = [self.parse_deployment_step(step) for step in (steps or [])] self.total_steps = total_steps self.version = version self.affected_pods = affected_pods def parse_deployment_step(self, step): if step.__class__ == dict: # This is what Marathon 1.0.0 returns: steps return MarathonDeploymentStep().from_json(step) elif step.__class__ == list: # This is Marathon < 1.0.0 style, a list of actions return [s if isinstance(s, MarathonDeploymentAction) else MarathonDeploymentAction.from_json(s) for s in step] else: return step class MarathonDeploymentAction(MarathonObject): """Marathon Application resource. See: https://mesosphere.github.io/marathon/docs/rest-api.html#deployments :param str action: action :param str app: app id :param str apps: app id (see https://github.com/mesosphere/marathon/pull/802) :param type readiness_check_results: Undocumented """ def __init__(self, action=None, app=None, apps=None, type=None, readiness_check_results=None, pod=None): self.action = action <|code_end|> , determine the next line of code. You have imports: from .base import MarathonObject, MarathonResource, assert_valid_path and context (class names, function names, or code) available: # Path: marathon/models/base.py # class MarathonObject: # """Base Marathon object.""" # # def __repr__(self): # return "{clazz}::{obj}".format(clazz=self.__class__.__name__, obj=self.to_json(minimal=False)) # # def __eq__(self, other): # try: # return self.__dict__ == other.__dict__ # except Exception: # return False # # def __hash__(self): # # Technically this class shouldn't be hashable because it often # # contains mutable fields, but in practice this class is used more # # like a record or namedtuple. # return hash(self.to_json()) # # def json_repr(self, minimal=False): # """Construct a JSON-friendly representation of the object. # # :param bool minimal: Construct a minimal representation of the object (ignore nulls and empty collections) # # :rtype: dict # """ # if minimal: # return {to_camel_case(k): v for k, v in vars(self).items() if (v or v is False or v == 0)} # else: # return {to_camel_case(k): v for k, v in vars(self).items()} # # @classmethod # def from_json(cls, attributes): # """Construct an object from a parsed response. # # :param dict attributes: object attributes from parsed response # """ # return cls(**{to_snake_case(k): v for k, v in attributes.items()}) # # def to_json(self, minimal=True): # """Encode an object as a JSON string. # # :param bool minimal: Construct a minimal representation of the object (ignore nulls and empty collections) # # :rtype: str # """ # if minimal: # return json.dumps(self.json_repr(minimal=True), cls=MarathonMinimalJsonEncoder, sort_keys=True) # else: # return json.dumps(self.json_repr(), cls=MarathonJsonEncoder, sort_keys=True) # # class MarathonResource(MarathonObject): # # """Base Marathon resource.""" # # def __repr__(self): # if 'id' in list(vars(self).keys()): # return f"{self.__class__.__name__}::{self.id}" # else: # return "{clazz}::{obj}".format(clazz=self.__class__.__name__, obj=self.to_json()) # # def __eq__(self, other): # try: # return self.__dict__ == other.__dict__ # except Exception: # return False # # def __hash__(self): # # Technically this class shouldn't be hashable because it often # # contains mutable fields, but in practice this class is used more # # like a record or namedtuple. # return hash(self.to_json()) # # def __str__(self): # return f"{self.__class__.__name__}::" + str(self.__dict__) # # def assert_valid_path(path): # """Checks if a path is a correct format that Marathon expects. Raises ValueError if not valid. # # :param str path: The app id. # # :rtype: str # """ # if path is None: # return # # As seen in: # # https://github.com/mesosphere/marathon/blob/0c11661ca2f259f8a903d114ef79023649a6f04b/src/main/scala/mesosphere/marathon/state/PathId.scala#L71 # for id in filter(None, path.strip('/').split('/')): # if not ID_PATTERN.match(id): # raise ValueError( # 'invalid path (allowed: lowercase letters, digits, hyphen, "/", ".", ".."): %r' % path) # return path . Output only the next line.
self.app = assert_valid_path(app)
Given the code snippet: <|code_start|> class MarathonEventTest(unittest.TestCase): def test_event_factory(self): self.assertEqual( <|code_end|> , generate the next line using the imports in this file: from marathon.models.events import EventFactory, MarathonStatusUpdateEvent from marathon.models.task import MarathonIpAddress import unittest and context (functions, classes, or occasionally code) from other files: # Path: marathon/models/events.py # class EventFactory: # # """ # Handle an event emitted from the Marathon EventBus # See: https://mesosphere.github.io/marathon/docs/event-bus.html # """ # # def __init__(self): # pass # # event_to_class = { # 'api_post_event': MarathonApiPostEvent, # 'status_update_event': MarathonStatusUpdateEvent, # 'framework_message_event': MarathonFrameworkMessageEvent, # 'subscribe_event': MarathonSubscribeEvent, # 'unsubscribe_event': MarathonUnsubscribeEvent, # 'add_health_check_event': MarathonAddHealthCheckEvent, # 'remove_health_check_event': MarathonRemoveHealthCheckEvent, # 'failed_health_check_event': MarathonFailedHealthCheckEvent, # 'health_status_changed_event': MarathonHealthStatusChangedEvent, # 'unhealthy_task_kill_event': MarathonUnhealthyTaskKillEvent, # 'group_change_success': MarathonGroupChangeSuccess, # 'group_change_failed': MarathonGroupChangeFailed, # 'deployment_success': MarathonDeploymentSuccess, # 'deployment_failed': MarathonDeploymentFailed, # 'deployment_info': MarathonDeploymentInfo, # 'deployment_step_success': MarathonDeploymentStepSuccess, # 'deployment_step_failure': MarathonDeploymentStepFailure, # 'event_stream_attached': MarathonEventStreamAttached, # 'event_stream_detached': MarathonEventStreamDetached, # 'app_terminated_event': MarathonAppTerminatedEvent, # 'instance_changed_event': MarathonInstanceChangedEvent, # 'unknown_instance_terminated_event': MarathonUnknownInstanceTerminated, # 'unhealthy_instance_kill_event': MarathonUnhealthyInstanceKillEvent, # 'instance_health_changed_event': MarathonInstanceHealthChangedEvent, # 'pod_created_event': MarathonPodCreatedEvent, # 'pod_updated_event': MarathonPodUpdatedEvent, # 'pod_deleted_event': MarathonPodDeletedEvent, # } # # class_to_event = {v: k for k, v in event_to_class.items()} # # def process(self, event): # event_type = event['eventType'] # if event_type in self.event_to_class: # clazz = self.event_to_class[event_type] # return clazz.from_json(event) # else: # raise MarathonError(f'Unknown event_type: {event_type}, data: {event}') # # class MarathonStatusUpdateEvent(MarathonEvent): # KNOWN_ATTRIBUTES = [ # 'slave_id', 'task_id', 'task_status', 'app_id', 'host', 'ports', 'version', 'message', 'ip_addresses'] # # Path: marathon/models/task.py # class MarathonIpAddress(MarathonObject): # """ # """ # def __init__(self, ip_address=None, protocol=None): # self.ip_address = ip_address # self.protocol = protocol . Output only the next line.
set(EventFactory.event_to_class.keys()),
Given snippet: <|code_start|> class MarathonEventTest(unittest.TestCase): def test_event_factory(self): self.assertEqual( set(EventFactory.event_to_class.keys()), set(EventFactory.class_to_event.values()), ) def test_marathon_event(self): """Test that we can process at least one kind of event.""" payload = { "eventType": "status_update_event", "slaveId": "slave-01", "taskId": "task-01", "taskStatus": "TASK_RUNNING", "message": "Some message", "appId": "/foo/bar", "host": "host-01", "ipAddresses": [ {"ip_address": "127.0.0.1", "protocol": "tcp"}, {"ip_address": "127.0.0.1", "protocol": "udp"}, ], "ports": [0, 1], "version": "1234", "timestamp": 12345, } factory = EventFactory() event = factory.process(payload) <|code_end|> , continue by predicting the next line. Consider current file imports: from marathon.models.events import EventFactory, MarathonStatusUpdateEvent from marathon.models.task import MarathonIpAddress import unittest and context: # Path: marathon/models/events.py # class EventFactory: # # """ # Handle an event emitted from the Marathon EventBus # See: https://mesosphere.github.io/marathon/docs/event-bus.html # """ # # def __init__(self): # pass # # event_to_class = { # 'api_post_event': MarathonApiPostEvent, # 'status_update_event': MarathonStatusUpdateEvent, # 'framework_message_event': MarathonFrameworkMessageEvent, # 'subscribe_event': MarathonSubscribeEvent, # 'unsubscribe_event': MarathonUnsubscribeEvent, # 'add_health_check_event': MarathonAddHealthCheckEvent, # 'remove_health_check_event': MarathonRemoveHealthCheckEvent, # 'failed_health_check_event': MarathonFailedHealthCheckEvent, # 'health_status_changed_event': MarathonHealthStatusChangedEvent, # 'unhealthy_task_kill_event': MarathonUnhealthyTaskKillEvent, # 'group_change_success': MarathonGroupChangeSuccess, # 'group_change_failed': MarathonGroupChangeFailed, # 'deployment_success': MarathonDeploymentSuccess, # 'deployment_failed': MarathonDeploymentFailed, # 'deployment_info': MarathonDeploymentInfo, # 'deployment_step_success': MarathonDeploymentStepSuccess, # 'deployment_step_failure': MarathonDeploymentStepFailure, # 'event_stream_attached': MarathonEventStreamAttached, # 'event_stream_detached': MarathonEventStreamDetached, # 'app_terminated_event': MarathonAppTerminatedEvent, # 'instance_changed_event': MarathonInstanceChangedEvent, # 'unknown_instance_terminated_event': MarathonUnknownInstanceTerminated, # 'unhealthy_instance_kill_event': MarathonUnhealthyInstanceKillEvent, # 'instance_health_changed_event': MarathonInstanceHealthChangedEvent, # 'pod_created_event': MarathonPodCreatedEvent, # 'pod_updated_event': MarathonPodUpdatedEvent, # 'pod_deleted_event': MarathonPodDeletedEvent, # } # # class_to_event = {v: k for k, v in event_to_class.items()} # # def process(self, event): # event_type = event['eventType'] # if event_type in self.event_to_class: # clazz = self.event_to_class[event_type] # return clazz.from_json(event) # else: # raise MarathonError(f'Unknown event_type: {event_type}, data: {event}') # # class MarathonStatusUpdateEvent(MarathonEvent): # KNOWN_ATTRIBUTES = [ # 'slave_id', 'task_id', 'task_status', 'app_id', 'host', 'ports', 'version', 'message', 'ip_addresses'] # # Path: marathon/models/task.py # class MarathonIpAddress(MarathonObject): # """ # """ # def __init__(self, ip_address=None, protocol=None): # self.ip_address = ip_address # self.protocol = protocol which might include code, classes, or functions. Output only the next line.
expected_event = MarathonStatusUpdateEvent(
Using the snippet: <|code_start|> "slaveId": "slave-01", "taskId": "task-01", "taskStatus": "TASK_RUNNING", "message": "Some message", "appId": "/foo/bar", "host": "host-01", "ipAddresses": [ {"ip_address": "127.0.0.1", "protocol": "tcp"}, {"ip_address": "127.0.0.1", "protocol": "udp"}, ], "ports": [0, 1], "version": "1234", "timestamp": 12345, } factory = EventFactory() event = factory.process(payload) expected_event = MarathonStatusUpdateEvent( event_type="status_update_event", timestamp=12345, slave_id="slave-01", task_id="task-01", task_status="TASK_RUNNING", message="Some message", app_id="/foo/bar", host="host-01", ports=[0, 1], version="1234", ) expected_event.ip_addresses = [ <|code_end|> , determine the next line of code. You have imports: from marathon.models.events import EventFactory, MarathonStatusUpdateEvent from marathon.models.task import MarathonIpAddress import unittest and context (class names, function names, or code) available: # Path: marathon/models/events.py # class EventFactory: # # """ # Handle an event emitted from the Marathon EventBus # See: https://mesosphere.github.io/marathon/docs/event-bus.html # """ # # def __init__(self): # pass # # event_to_class = { # 'api_post_event': MarathonApiPostEvent, # 'status_update_event': MarathonStatusUpdateEvent, # 'framework_message_event': MarathonFrameworkMessageEvent, # 'subscribe_event': MarathonSubscribeEvent, # 'unsubscribe_event': MarathonUnsubscribeEvent, # 'add_health_check_event': MarathonAddHealthCheckEvent, # 'remove_health_check_event': MarathonRemoveHealthCheckEvent, # 'failed_health_check_event': MarathonFailedHealthCheckEvent, # 'health_status_changed_event': MarathonHealthStatusChangedEvent, # 'unhealthy_task_kill_event': MarathonUnhealthyTaskKillEvent, # 'group_change_success': MarathonGroupChangeSuccess, # 'group_change_failed': MarathonGroupChangeFailed, # 'deployment_success': MarathonDeploymentSuccess, # 'deployment_failed': MarathonDeploymentFailed, # 'deployment_info': MarathonDeploymentInfo, # 'deployment_step_success': MarathonDeploymentStepSuccess, # 'deployment_step_failure': MarathonDeploymentStepFailure, # 'event_stream_attached': MarathonEventStreamAttached, # 'event_stream_detached': MarathonEventStreamDetached, # 'app_terminated_event': MarathonAppTerminatedEvent, # 'instance_changed_event': MarathonInstanceChangedEvent, # 'unknown_instance_terminated_event': MarathonUnknownInstanceTerminated, # 'unhealthy_instance_kill_event': MarathonUnhealthyInstanceKillEvent, # 'instance_health_changed_event': MarathonInstanceHealthChangedEvent, # 'pod_created_event': MarathonPodCreatedEvent, # 'pod_updated_event': MarathonPodUpdatedEvent, # 'pod_deleted_event': MarathonPodDeletedEvent, # } # # class_to_event = {v: k for k, v in event_to_class.items()} # # def process(self, event): # event_type = event['eventType'] # if event_type in self.event_to_class: # clazz = self.event_to_class[event_type] # return clazz.from_json(event) # else: # raise MarathonError(f'Unknown event_type: {event_type}, data: {event}') # # class MarathonStatusUpdateEvent(MarathonEvent): # KNOWN_ATTRIBUTES = [ # 'slave_id', 'task_id', 'task_status', 'app_id', 'host', 'ports', 'version', 'message', 'ip_addresses'] # # Path: marathon/models/task.py # class MarathonIpAddress(MarathonObject): # """ # """ # def __init__(self, ip_address=None, protocol=None): # self.ip_address = ip_address # self.protocol = protocol . Output only the next line.
MarathonIpAddress(ip_address="127.0.0.1", protocol="tcp"),
Based on the snippet: <|code_start|> class MarathonObjectTest(unittest.TestCase): def test_hashable(self): """ Regression test for issue #203 MarathonObject defined __eq__ but not __hash__, meaning that in in Python2.7 MarathonObjects are hashable, but in Python3 they're not, This test ensures that we are hashable in all versions of python """ <|code_end|> , predict the immediate next line with the help of imports: from marathon.models.base import MarathonObject from marathon.models.base import MarathonResource import unittest and context (classes, functions, sometimes code) from other files: # Path: marathon/models/base.py # class MarathonObject: # """Base Marathon object.""" # # def __repr__(self): # return "{clazz}::{obj}".format(clazz=self.__class__.__name__, obj=self.to_json(minimal=False)) # # def __eq__(self, other): # try: # return self.__dict__ == other.__dict__ # except Exception: # return False # # def __hash__(self): # # Technically this class shouldn't be hashable because it often # # contains mutable fields, but in practice this class is used more # # like a record or namedtuple. # return hash(self.to_json()) # # def json_repr(self, minimal=False): # """Construct a JSON-friendly representation of the object. # # :param bool minimal: Construct a minimal representation of the object (ignore nulls and empty collections) # # :rtype: dict # """ # if minimal: # return {to_camel_case(k): v for k, v in vars(self).items() if (v or v is False or v == 0)} # else: # return {to_camel_case(k): v for k, v in vars(self).items()} # # @classmethod # def from_json(cls, attributes): # """Construct an object from a parsed response. # # :param dict attributes: object attributes from parsed response # """ # return cls(**{to_snake_case(k): v for k, v in attributes.items()}) # # def to_json(self, minimal=True): # """Encode an object as a JSON string. # # :param bool minimal: Construct a minimal representation of the object (ignore nulls and empty collections) # # :rtype: str # """ # if minimal: # return json.dumps(self.json_repr(minimal=True), cls=MarathonMinimalJsonEncoder, sort_keys=True) # else: # return json.dumps(self.json_repr(), cls=MarathonJsonEncoder, sort_keys=True) # # Path: marathon/models/base.py # class MarathonResource(MarathonObject): # # """Base Marathon resource.""" # # def __repr__(self): # if 'id' in list(vars(self).keys()): # return f"{self.__class__.__name__}::{self.id}" # else: # return "{clazz}::{obj}".format(clazz=self.__class__.__name__, obj=self.to_json()) # # def __eq__(self, other): # try: # return self.__dict__ == other.__dict__ # except Exception: # return False # # def __hash__(self): # # Technically this class shouldn't be hashable because it often # # contains mutable fields, but in practice this class is used more # # like a record or namedtuple. # return hash(self.to_json()) # # def __str__(self): # return f"{self.__class__.__name__}::" + str(self.__dict__) . Output only the next line.
obj = MarathonObject()
Here is a snippet: <|code_start|> class MarathonObjectTest(unittest.TestCase): def test_hashable(self): """ Regression test for issue #203 MarathonObject defined __eq__ but not __hash__, meaning that in in Python2.7 MarathonObjects are hashable, but in Python3 they're not, This test ensures that we are hashable in all versions of python """ obj = MarathonObject() collection = {} collection[obj] = True assert collection[obj] class MarathonResourceHashable(unittest.TestCase): def test_hashable(self): """ Regression test for issue #203 MarathonResource defined __eq__ but not __hash__, meaning that in in Python2.7 MarathonResources are hashable, but in Python3 they're not This test ensures that we are hashable in all versions of python """ <|code_end|> . Write the next line using the current file imports: from marathon.models.base import MarathonObject from marathon.models.base import MarathonResource import unittest and context from other files: # Path: marathon/models/base.py # class MarathonObject: # """Base Marathon object.""" # # def __repr__(self): # return "{clazz}::{obj}".format(clazz=self.__class__.__name__, obj=self.to_json(minimal=False)) # # def __eq__(self, other): # try: # return self.__dict__ == other.__dict__ # except Exception: # return False # # def __hash__(self): # # Technically this class shouldn't be hashable because it often # # contains mutable fields, but in practice this class is used more # # like a record or namedtuple. # return hash(self.to_json()) # # def json_repr(self, minimal=False): # """Construct a JSON-friendly representation of the object. # # :param bool minimal: Construct a minimal representation of the object (ignore nulls and empty collections) # # :rtype: dict # """ # if minimal: # return {to_camel_case(k): v for k, v in vars(self).items() if (v or v is False or v == 0)} # else: # return {to_camel_case(k): v for k, v in vars(self).items()} # # @classmethod # def from_json(cls, attributes): # """Construct an object from a parsed response. # # :param dict attributes: object attributes from parsed response # """ # return cls(**{to_snake_case(k): v for k, v in attributes.items()}) # # def to_json(self, minimal=True): # """Encode an object as a JSON string. # # :param bool minimal: Construct a minimal representation of the object (ignore nulls and empty collections) # # :rtype: str # """ # if minimal: # return json.dumps(self.json_repr(minimal=True), cls=MarathonMinimalJsonEncoder, sort_keys=True) # else: # return json.dumps(self.json_repr(), cls=MarathonJsonEncoder, sort_keys=True) # # Path: marathon/models/base.py # class MarathonResource(MarathonObject): # # """Base Marathon resource.""" # # def __repr__(self): # if 'id' in list(vars(self).keys()): # return f"{self.__class__.__name__}::{self.id}" # else: # return "{clazz}::{obj}".format(clazz=self.__class__.__name__, obj=self.to_json()) # # def __eq__(self, other): # try: # return self.__dict__ == other.__dict__ # except Exception: # return False # # def __hash__(self): # # Technically this class shouldn't be hashable because it often # # contains mutable fields, but in practice this class is used more # # like a record or namedtuple. # return hash(self.to_json()) # # def __str__(self): # return f"{self.__class__.__name__}::" + str(self.__dict__) , which may include functions, classes, or code. Output only the next line.
obj = MarathonResource()
Predict the next line after this snippet: <|code_start|> def _apply_on_pairs(f): # this strategy is used to have the assertion stack trace # point to the right pair of strings in case of test failure f('foo', 'foo') f('foo42', 'foo42') f('fooBar', 'foo_bar') f('f0o42Bar', 'f0o42_bar') f('fooBarBaz', 'foo_bar_baz') f('ignoreHttp1xx', 'ignore_http1xx') f('whereAmI', 'where_am_i') f('iSee', 'i_see') f('doISee', 'do_i_see') def test_to_camel_case(): def test(camel, snake): <|code_end|> using the current file's imports: from datetime import datetime, timezone from marathon.util import to_camel_case, to_snake_case, to_datetime and any relevant context from other files: # Path: marathon/util.py # def to_camel_case(snake_str): # words = snake_str.split('_') # return words[0] + ''.join(w.capitalize() for w in words[1:]) # # def to_snake_case(camel_str): # s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', camel_str) # return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() # # def to_datetime(timestamp): # if (timestamp is None or isinstance(timestamp, datetime.datetime)): # return timestamp # else: # for fmt in DATETIME_FORMATS: # try: # return datetime.datetime.strptime(timestamp, fmt).replace(tzinfo=datetime.timezone.utc) # except ValueError: # pass # raise ValueError(f'Unrecognized datetime format: {timestamp}') . Output only the next line.
assert to_camel_case(snake) == camel
Next line prediction: <|code_start|> def _apply_on_pairs(f): # this strategy is used to have the assertion stack trace # point to the right pair of strings in case of test failure f('foo', 'foo') f('foo42', 'foo42') f('fooBar', 'foo_bar') f('f0o42Bar', 'f0o42_bar') f('fooBarBaz', 'foo_bar_baz') f('ignoreHttp1xx', 'ignore_http1xx') f('whereAmI', 'where_am_i') f('iSee', 'i_see') f('doISee', 'do_i_see') def test_to_camel_case(): def test(camel, snake): assert to_camel_case(snake) == camel _apply_on_pairs(test) def test_to_snake_case(): def test(camel, snake): <|code_end|> . Use current file imports: (from datetime import datetime, timezone from marathon.util import to_camel_case, to_snake_case, to_datetime) and context including class names, function names, or small code snippets from other files: # Path: marathon/util.py # def to_camel_case(snake_str): # words = snake_str.split('_') # return words[0] + ''.join(w.capitalize() for w in words[1:]) # # def to_snake_case(camel_str): # s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', camel_str) # return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() # # def to_datetime(timestamp): # if (timestamp is None or isinstance(timestamp, datetime.datetime)): # return timestamp # else: # for fmt in DATETIME_FORMATS: # try: # return datetime.datetime.strptime(timestamp, fmt).replace(tzinfo=datetime.timezone.utc) # except ValueError: # pass # raise ValueError(f'Unrecognized datetime format: {timestamp}') . Output only the next line.
assert to_snake_case(camel) == snake
Continue the code snippet: <|code_start|> def _apply_on_pairs(f): # this strategy is used to have the assertion stack trace # point to the right pair of strings in case of test failure f('foo', 'foo') f('foo42', 'foo42') f('fooBar', 'foo_bar') f('f0o42Bar', 'f0o42_bar') f('fooBarBaz', 'foo_bar_baz') f('ignoreHttp1xx', 'ignore_http1xx') f('whereAmI', 'where_am_i') f('iSee', 'i_see') f('doISee', 'do_i_see') def test_to_camel_case(): def test(camel, snake): assert to_camel_case(snake) == camel _apply_on_pairs(test) def test_to_snake_case(): def test(camel, snake): assert to_snake_case(camel) == snake _apply_on_pairs(test) def test_version_info_datetime(): <|code_end|> . Use current file imports: from datetime import datetime, timezone from marathon.util import to_camel_case, to_snake_case, to_datetime and context (classes, functions, or code) from other files: # Path: marathon/util.py # def to_camel_case(snake_str): # words = snake_str.split('_') # return words[0] + ''.join(w.capitalize() for w in words[1:]) # # def to_snake_case(camel_str): # s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', camel_str) # return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() # # def to_datetime(timestamp): # if (timestamp is None or isinstance(timestamp, datetime.datetime)): # return timestamp # else: # for fmt in DATETIME_FORMATS: # try: # return datetime.datetime.strptime(timestamp, fmt).replace(tzinfo=datetime.timezone.utc) # except ValueError: # pass # raise ValueError(f'Unrecognized datetime format: {timestamp}') . Output only the next line.
assert to_datetime("2017-09-28T00:31:55Z") == datetime(2017, 9, 28, 0, 31, 55, tzinfo=timezone.utc)
Next line prediction: <|code_start|> class MarathonObject: """Base Marathon object.""" def __repr__(self): return "{clazz}::{obj}".format(clazz=self.__class__.__name__, obj=self.to_json(minimal=False)) def __eq__(self, other): try: return self.__dict__ == other.__dict__ except Exception: return False def __hash__(self): # Technically this class shouldn't be hashable because it often # contains mutable fields, but in practice this class is used more # like a record or namedtuple. return hash(self.to_json()) def json_repr(self, minimal=False): """Construct a JSON-friendly representation of the object. :param bool minimal: Construct a minimal representation of the object (ignore nulls and empty collections) :rtype: dict """ if minimal: <|code_end|> . Use current file imports: (import json import re from marathon.util import to_camel_case, to_snake_case, MarathonJsonEncoder, MarathonMinimalJsonEncoder) and context including class names, function names, or small code snippets from other files: # Path: marathon/util.py # def to_camel_case(snake_str): # words = snake_str.split('_') # return words[0] + ''.join(w.capitalize() for w in words[1:]) # # def to_snake_case(camel_str): # s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', camel_str) # return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() # # class MarathonJsonEncoder(json.JSONEncoder): # # """Custom JSON encoder for Marathon object serialization.""" # # def default(self, obj): # if hasattr(obj, 'json_repr'): # return self.default(obj.json_repr()) # # if isinstance(obj, datetime.datetime): # return obj.strftime('%Y-%m-%dT%H:%M:%S.%fZ') # # if isinstance(obj, collections.Iterable) and not isinstance(obj, str): # try: # return {k: self.default(v) for k, v in obj.items()} # except AttributeError: # return [self.default(e) for e in obj] # # return obj # # class MarathonMinimalJsonEncoder(json.JSONEncoder): # # """Custom JSON encoder for Marathon object serialization.""" # # def default(self, obj): # if hasattr(obj, 'json_repr'): # return self.default(obj.json_repr(minimal=True)) # # if isinstance(obj, datetime.datetime): # return obj.strftime('%Y-%m-%dT%H:%M:%S.%fZ') # # if isinstance(obj, collections.Iterable) and not isinstance(obj, str): # try: # return {k: self.default(v) for k, v in obj.items() if (v or v in (False, 0))} # except AttributeError: # return [self.default(e) for e in obj if (e or e in (False, 0))] # # return obj . Output only the next line.
return {to_camel_case(k): v for k, v in vars(self).items() if (v or v is False or v == 0)}
Given snippet: <|code_start|> def __eq__(self, other): try: return self.__dict__ == other.__dict__ except Exception: return False def __hash__(self): # Technically this class shouldn't be hashable because it often # contains mutable fields, but in practice this class is used more # like a record or namedtuple. return hash(self.to_json()) def json_repr(self, minimal=False): """Construct a JSON-friendly representation of the object. :param bool minimal: Construct a minimal representation of the object (ignore nulls and empty collections) :rtype: dict """ if minimal: return {to_camel_case(k): v for k, v in vars(self).items() if (v or v is False or v == 0)} else: return {to_camel_case(k): v for k, v in vars(self).items()} @classmethod def from_json(cls, attributes): """Construct an object from a parsed response. :param dict attributes: object attributes from parsed response """ <|code_end|> , continue by predicting the next line. Consider current file imports: import json import re from marathon.util import to_camel_case, to_snake_case, MarathonJsonEncoder, MarathonMinimalJsonEncoder and context: # Path: marathon/util.py # def to_camel_case(snake_str): # words = snake_str.split('_') # return words[0] + ''.join(w.capitalize() for w in words[1:]) # # def to_snake_case(camel_str): # s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', camel_str) # return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() # # class MarathonJsonEncoder(json.JSONEncoder): # # """Custom JSON encoder for Marathon object serialization.""" # # def default(self, obj): # if hasattr(obj, 'json_repr'): # return self.default(obj.json_repr()) # # if isinstance(obj, datetime.datetime): # return obj.strftime('%Y-%m-%dT%H:%M:%S.%fZ') # # if isinstance(obj, collections.Iterable) and not isinstance(obj, str): # try: # return {k: self.default(v) for k, v in obj.items()} # except AttributeError: # return [self.default(e) for e in obj] # # return obj # # class MarathonMinimalJsonEncoder(json.JSONEncoder): # # """Custom JSON encoder for Marathon object serialization.""" # # def default(self, obj): # if hasattr(obj, 'json_repr'): # return self.default(obj.json_repr(minimal=True)) # # if isinstance(obj, datetime.datetime): # return obj.strftime('%Y-%m-%dT%H:%M:%S.%fZ') # # if isinstance(obj, collections.Iterable) and not isinstance(obj, str): # try: # return {k: self.default(v) for k, v in obj.items() if (v or v in (False, 0))} # except AttributeError: # return [self.default(e) for e in obj if (e or e in (False, 0))] # # return obj which might include code, classes, or functions. Output only the next line.
return cls(**{to_snake_case(k): v for k, v in attributes.items()})
Next line prediction: <|code_start|> def json_repr(self, minimal=False): """Construct a JSON-friendly representation of the object. :param bool minimal: Construct a minimal representation of the object (ignore nulls and empty collections) :rtype: dict """ if minimal: return {to_camel_case(k): v for k, v in vars(self).items() if (v or v is False or v == 0)} else: return {to_camel_case(k): v for k, v in vars(self).items()} @classmethod def from_json(cls, attributes): """Construct an object from a parsed response. :param dict attributes: object attributes from parsed response """ return cls(**{to_snake_case(k): v for k, v in attributes.items()}) def to_json(self, minimal=True): """Encode an object as a JSON string. :param bool minimal: Construct a minimal representation of the object (ignore nulls and empty collections) :rtype: str """ if minimal: return json.dumps(self.json_repr(minimal=True), cls=MarathonMinimalJsonEncoder, sort_keys=True) else: <|code_end|> . Use current file imports: (import json import re from marathon.util import to_camel_case, to_snake_case, MarathonJsonEncoder, MarathonMinimalJsonEncoder) and context including class names, function names, or small code snippets from other files: # Path: marathon/util.py # def to_camel_case(snake_str): # words = snake_str.split('_') # return words[0] + ''.join(w.capitalize() for w in words[1:]) # # def to_snake_case(camel_str): # s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', camel_str) # return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() # # class MarathonJsonEncoder(json.JSONEncoder): # # """Custom JSON encoder for Marathon object serialization.""" # # def default(self, obj): # if hasattr(obj, 'json_repr'): # return self.default(obj.json_repr()) # # if isinstance(obj, datetime.datetime): # return obj.strftime('%Y-%m-%dT%H:%M:%S.%fZ') # # if isinstance(obj, collections.Iterable) and not isinstance(obj, str): # try: # return {k: self.default(v) for k, v in obj.items()} # except AttributeError: # return [self.default(e) for e in obj] # # return obj # # class MarathonMinimalJsonEncoder(json.JSONEncoder): # # """Custom JSON encoder for Marathon object serialization.""" # # def default(self, obj): # if hasattr(obj, 'json_repr'): # return self.default(obj.json_repr(minimal=True)) # # if isinstance(obj, datetime.datetime): # return obj.strftime('%Y-%m-%dT%H:%M:%S.%fZ') # # if isinstance(obj, collections.Iterable) and not isinstance(obj, str): # try: # return {k: self.default(v) for k, v in obj.items() if (v or v in (False, 0))} # except AttributeError: # return [self.default(e) for e in obj if (e or e in (False, 0))] # # return obj . Output only the next line.
return json.dumps(self.json_repr(), cls=MarathonJsonEncoder, sort_keys=True)
Continue the code snippet: <|code_start|> return hash(self.to_json()) def json_repr(self, minimal=False): """Construct a JSON-friendly representation of the object. :param bool minimal: Construct a minimal representation of the object (ignore nulls and empty collections) :rtype: dict """ if minimal: return {to_camel_case(k): v for k, v in vars(self).items() if (v or v is False or v == 0)} else: return {to_camel_case(k): v for k, v in vars(self).items()} @classmethod def from_json(cls, attributes): """Construct an object from a parsed response. :param dict attributes: object attributes from parsed response """ return cls(**{to_snake_case(k): v for k, v in attributes.items()}) def to_json(self, minimal=True): """Encode an object as a JSON string. :param bool minimal: Construct a minimal representation of the object (ignore nulls and empty collections) :rtype: str """ if minimal: <|code_end|> . Use current file imports: import json import re from marathon.util import to_camel_case, to_snake_case, MarathonJsonEncoder, MarathonMinimalJsonEncoder and context (classes, functions, or code) from other files: # Path: marathon/util.py # def to_camel_case(snake_str): # words = snake_str.split('_') # return words[0] + ''.join(w.capitalize() for w in words[1:]) # # def to_snake_case(camel_str): # s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', camel_str) # return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() # # class MarathonJsonEncoder(json.JSONEncoder): # # """Custom JSON encoder for Marathon object serialization.""" # # def default(self, obj): # if hasattr(obj, 'json_repr'): # return self.default(obj.json_repr()) # # if isinstance(obj, datetime.datetime): # return obj.strftime('%Y-%m-%dT%H:%M:%S.%fZ') # # if isinstance(obj, collections.Iterable) and not isinstance(obj, str): # try: # return {k: self.default(v) for k, v in obj.items()} # except AttributeError: # return [self.default(e) for e in obj] # # return obj # # class MarathonMinimalJsonEncoder(json.JSONEncoder): # # """Custom JSON encoder for Marathon object serialization.""" # # def default(self, obj): # if hasattr(obj, 'json_repr'): # return self.default(obj.json_repr(minimal=True)) # # if isinstance(obj, datetime.datetime): # return obj.strftime('%Y-%m-%dT%H:%M:%S.%fZ') # # if isinstance(obj, collections.Iterable) and not isinstance(obj, str): # try: # return {k: self.default(v) for k, v in obj.items() if (v or v in (False, 0))} # except AttributeError: # return [self.default(e) for e in obj if (e or e in (False, 0))] # # return obj . Output only the next line.
return json.dumps(self.json_repr(minimal=True), cls=MarathonMinimalJsonEncoder, sort_keys=True)
Given snippet: <|code_start|> def test_400_error(): fake_response = requests.Response() fake_message = "Invalid JSON" fake_details = [{"path": "/taskKillGracePeriodSeconds", "errors": ["error.expected.jsnumber"]}] fake_response._content = json.dumps({"message": fake_message, "details": fake_details}).encode() fake_response.status_code = 400 fake_response.headers['Content-Type'] = 'application/json' <|code_end|> , continue by predicting the next line. Consider current file imports: import json import requests from marathon.exceptions import MarathonHttpError, InternalServerError and context: # Path: marathon/exceptions.py # class MarathonHttpError(MarathonError): # # def __init__(self, response): # """ # :param :class:`requests.Response` response: HTTP response # """ # self.error_message = response.reason or '' # if response.content and 'application/json' in response.headers.get('content-type', ''): # content = response.json() # self.error_message = content.get('message', self.error_message) # self.error_details = content.get('details') # self.status_code = response.status_code # super().__init__(self.__str__()) # # def __repr__(self): # return 'MarathonHttpError: HTTP %s returned with message, "%s"' % \ # (self.status_code, self.error_message) # # def __str__(self): # return self.__repr__() # # class InternalServerError(MarathonHttpError): # pass which might include code, classes, or functions. Output only the next line.
exc = MarathonHttpError(fake_response)
Based on the snippet: <|code_start|> def test_400_error(): fake_response = requests.Response() fake_message = "Invalid JSON" fake_details = [{"path": "/taskKillGracePeriodSeconds", "errors": ["error.expected.jsnumber"]}] fake_response._content = json.dumps({"message": fake_message, "details": fake_details}).encode() fake_response.status_code = 400 fake_response.headers['Content-Type'] = 'application/json' exc = MarathonHttpError(fake_response) assert exc.status_code == 400 assert exc.error_message == fake_message assert exc.error_details == fake_details def test_503_error(): fake_response = requests.Response() fake_response._content = """<head> <meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-1"/> <title>Error 503 </title> </head> <body> <h2>HTTP ERROR: 503</h2> </body> </html>""" fake_response.reason = "reason" fake_response.status_code = 503 <|code_end|> , predict the immediate next line with the help of imports: import json import requests from marathon.exceptions import MarathonHttpError, InternalServerError and context (classes, functions, sometimes code) from other files: # Path: marathon/exceptions.py # class MarathonHttpError(MarathonError): # # def __init__(self, response): # """ # :param :class:`requests.Response` response: HTTP response # """ # self.error_message = response.reason or '' # if response.content and 'application/json' in response.headers.get('content-type', ''): # content = response.json() # self.error_message = content.get('message', self.error_message) # self.error_details = content.get('details') # self.status_code = response.status_code # super().__init__(self.__str__()) # # def __repr__(self): # return 'MarathonHttpError: HTTP %s returned with message, "%s"' % \ # (self.status_code, self.error_message) # # def __str__(self): # return self.__repr__() # # class InternalServerError(MarathonHttpError): # pass . Output only the next line.
exc = InternalServerError(fake_response)
Continue the code snippet: <|code_start|> def __init__(self, app_id=None, health_check_results=None, host=None, id=None, ports=None, service_ports=None, slave_id=None, staged_at=None, started_at=None, version=None, ip_addresses=[], state=None, local_volumes=None, region=None, zone=None, role=None): self.app_id = app_id self.health_check_results = health_check_results or [] self.health_check_results = [ hcr if isinstance( hcr, MarathonHealthCheckResult) else MarathonHealthCheckResult().from_json(hcr) for hcr in (health_check_results or []) if any(health_check_results) ] self.host = host self.id = id self.ports = ports or [] self.service_ports = service_ports or [] self.slave_id = slave_id self.staged_at = to_datetime(staged_at) self.started_at = to_datetime(started_at) self.state = state self.version = version self.ip_addresses = [ ipaddr if isinstance( ip_addresses, MarathonIpAddress) else MarathonIpAddress().from_json(ipaddr) for ipaddr in (ip_addresses or [])] self.local_volumes = local_volumes or [] self.region = region self.zone = zone self.role = role <|code_end|> . Use current file imports: from .base import MarathonResource, MarathonObject from ..util import to_datetime and context (classes, functions, or code) from other files: # Path: marathon/models/base.py # class MarathonResource(MarathonObject): # # """Base Marathon resource.""" # # def __repr__(self): # if 'id' in list(vars(self).keys()): # return f"{self.__class__.__name__}::{self.id}" # else: # return "{clazz}::{obj}".format(clazz=self.__class__.__name__, obj=self.to_json()) # # def __eq__(self, other): # try: # return self.__dict__ == other.__dict__ # except Exception: # return False # # def __hash__(self): # # Technically this class shouldn't be hashable because it often # # contains mutable fields, but in practice this class is used more # # like a record or namedtuple. # return hash(self.to_json()) # # def __str__(self): # return f"{self.__class__.__name__}::" + str(self.__dict__) # # class MarathonObject: # """Base Marathon object.""" # # def __repr__(self): # return "{clazz}::{obj}".format(clazz=self.__class__.__name__, obj=self.to_json(minimal=False)) # # def __eq__(self, other): # try: # return self.__dict__ == other.__dict__ # except Exception: # return False # # def __hash__(self): # # Technically this class shouldn't be hashable because it often # # contains mutable fields, but in practice this class is used more # # like a record or namedtuple. # return hash(self.to_json()) # # def json_repr(self, minimal=False): # """Construct a JSON-friendly representation of the object. # # :param bool minimal: Construct a minimal representation of the object (ignore nulls and empty collections) # # :rtype: dict # """ # if minimal: # return {to_camel_case(k): v for k, v in vars(self).items() if (v or v is False or v == 0)} # else: # return {to_camel_case(k): v for k, v in vars(self).items()} # # @classmethod # def from_json(cls, attributes): # """Construct an object from a parsed response. # # :param dict attributes: object attributes from parsed response # """ # return cls(**{to_snake_case(k): v for k, v in attributes.items()}) # # def to_json(self, minimal=True): # """Encode an object as a JSON string. # # :param bool minimal: Construct a minimal representation of the object (ignore nulls and empty collections) # # :rtype: str # """ # if minimal: # return json.dumps(self.json_repr(minimal=True), cls=MarathonMinimalJsonEncoder, sort_keys=True) # else: # return json.dumps(self.json_repr(), cls=MarathonJsonEncoder, sort_keys=True) # # Path: marathon/util.py # def to_datetime(timestamp): # if (timestamp is None or isinstance(timestamp, datetime.datetime)): # return timestamp # else: # for fmt in DATETIME_FORMATS: # try: # return datetime.datetime.strptime(timestamp, fmt).replace(tzinfo=datetime.timezone.utc) # except ValueError: # pass # raise ValueError(f'Unrecognized datetime format: {timestamp}') . Output only the next line.
class MarathonIpAddress(MarathonObject):
Given the following code snippet before the placeholder: <|code_start|> :param staged_at: when this task was staged :type staged_at: datetime or str :param started_at: when this task was started :type started_at: datetime or str :param str version: app version with which this task was started :type region: str :param region: fault domain region support in DCOS EE :type zone: str :param zone: fault domain zone support in DCOS EE :type role: str :param role: mesos role """ DATETIME_FORMAT = '%Y-%m-%dT%H:%M:%S.%fZ' def __init__(self, app_id=None, health_check_results=None, host=None, id=None, ports=None, service_ports=None, slave_id=None, staged_at=None, started_at=None, version=None, ip_addresses=[], state=None, local_volumes=None, region=None, zone=None, role=None): self.app_id = app_id self.health_check_results = health_check_results or [] self.health_check_results = [ hcr if isinstance( hcr, MarathonHealthCheckResult) else MarathonHealthCheckResult().from_json(hcr) for hcr in (health_check_results or []) if any(health_check_results) ] self.host = host self.id = id self.ports = ports or [] self.service_ports = service_ports or [] self.slave_id = slave_id <|code_end|> , predict the next line using imports from the current file: from .base import MarathonResource, MarathonObject from ..util import to_datetime and context including class names, function names, and sometimes code from other files: # Path: marathon/models/base.py # class MarathonResource(MarathonObject): # # """Base Marathon resource.""" # # def __repr__(self): # if 'id' in list(vars(self).keys()): # return f"{self.__class__.__name__}::{self.id}" # else: # return "{clazz}::{obj}".format(clazz=self.__class__.__name__, obj=self.to_json()) # # def __eq__(self, other): # try: # return self.__dict__ == other.__dict__ # except Exception: # return False # # def __hash__(self): # # Technically this class shouldn't be hashable because it often # # contains mutable fields, but in practice this class is used more # # like a record or namedtuple. # return hash(self.to_json()) # # def __str__(self): # return f"{self.__class__.__name__}::" + str(self.__dict__) # # class MarathonObject: # """Base Marathon object.""" # # def __repr__(self): # return "{clazz}::{obj}".format(clazz=self.__class__.__name__, obj=self.to_json(minimal=False)) # # def __eq__(self, other): # try: # return self.__dict__ == other.__dict__ # except Exception: # return False # # def __hash__(self): # # Technically this class shouldn't be hashable because it often # # contains mutable fields, but in practice this class is used more # # like a record or namedtuple. # return hash(self.to_json()) # # def json_repr(self, minimal=False): # """Construct a JSON-friendly representation of the object. # # :param bool minimal: Construct a minimal representation of the object (ignore nulls and empty collections) # # :rtype: dict # """ # if minimal: # return {to_camel_case(k): v for k, v in vars(self).items() if (v or v is False or v == 0)} # else: # return {to_camel_case(k): v for k, v in vars(self).items()} # # @classmethod # def from_json(cls, attributes): # """Construct an object from a parsed response. # # :param dict attributes: object attributes from parsed response # """ # return cls(**{to_snake_case(k): v for k, v in attributes.items()}) # # def to_json(self, minimal=True): # """Encode an object as a JSON string. # # :param bool minimal: Construct a minimal representation of the object (ignore nulls and empty collections) # # :rtype: str # """ # if minimal: # return json.dumps(self.json_repr(minimal=True), cls=MarathonMinimalJsonEncoder, sort_keys=True) # else: # return json.dumps(self.json_repr(), cls=MarathonJsonEncoder, sort_keys=True) # # Path: marathon/util.py # def to_datetime(timestamp): # if (timestamp is None or isinstance(timestamp, datetime.datetime)): # return timestamp # else: # for fmt in DATETIME_FORMATS: # try: # return datetime.datetime.strptime(timestamp, fmt).replace(tzinfo=datetime.timezone.utc) # except ValueError: # pass # raise ValueError(f'Unrecognized datetime format: {timestamp}') . Output only the next line.
self.staged_at = to_datetime(staged_at)
Predict the next line after this snippet: <|code_start|> class MarathonGroupTest(unittest.TestCase): def test_from_json_parses_root_group(self): data = { "id": "/", "groups": [ {"id": "/foo", "apps": []}, {"id": "/bla", "apps": []}, ], "apps": [] } <|code_end|> using the current file's imports: from marathon.models.group import MarathonGroup import unittest and any relevant context from other files: # Path: marathon/models/group.py # class MarathonGroup(MarathonResource): # # """Marathon group resource. # # See: https://mesosphere.github.io/marathon/docs/rest-api.html#groups # # :param apps: # :type apps: list[:class:`marathon.models.app.MarathonApp`] or list[dict] # :param list[str] dependencies: # :param groups: # :type groups: list[:class:`marathon.models.group.MarathonGroup`] or list[dict] # :param str id: # :param pods: # :type pods: list[:class:`marathon.models.pod.MarathonPod`] or list[dict] # :param str version: # """ # # def __init__(self, apps=None, dependencies=None, # groups=None, id=None, pods=None, version=None, enforce_role=None): # self.apps = [ # a if isinstance(a, MarathonApp) else MarathonApp().from_json(a) # for a in (apps or []) # ] # self.dependencies = dependencies or [] # self.groups = [ # g if isinstance(g, MarathonGroup) else MarathonGroup().from_json(g) # for g in (groups or []) # ] # self.pods = [] # # ToDo: Create class MarathonPod # # self.pods = [ # # p if isinstance(p, MarathonPod) else MarathonPod().from_json(p) # # for p in (pods or []) # # ] # self.id = id # self.version = version # self.enforce_role = enforce_role . Output only the next line.
group = MarathonGroup().from_json(data)
Predict the next line after this snippet: <|code_start|> class MarathonDeploymentTest(unittest.TestCase): def test_env_defaults_to_empty_dict(self): """ é testé """ deployment_json = { "id": "ID", "version": "2020-05-30T07:35:04.695Z", "affectedApps": ["/app"], "affectedPods": [], "steps": [{ "actions": [{ "action": "RestartApplication", "app": "/app" }] }], "currentActions": [{ "action": "RestartApplication", "app": "/app", "readinessCheckResults": [] }], "currentStep": 1, "totalSteps": 1 } <|code_end|> using the current file's imports: from marathon.models.deployment import MarathonDeployment import unittest and any relevant context from other files: # Path: marathon/models/deployment.py # class MarathonDeployment(MarathonResource): # # """Marathon Application resource. # # See: https://mesosphere.github.io/marathon/docs/rest-api.html#deployments # https://mesosphere.github.io/marathon/docs/generated/api.html#v2_deployments_get # # :param list[str] affected_apps: list of affected app ids # :param current_actions: current actions # :type current_actions: list[:class:`marathon.models.deployment.MarathonDeploymentAction`] or list[dict] # :param int current_step: current step # :param str id: deployment id # :param steps: deployment steps # :type steps: list[:class:`marathon.models.deployment.MarathonDeploymentAction`] or list[dict] # :param int total_steps: total number of steps # :param str version: version id # :param str affected_pods: list of strings # """ # # def __init__(self, affected_apps=None, current_actions=None, current_step=None, id=None, steps=None, # total_steps=None, version=None, affected_pods=None): # self.affected_apps = affected_apps # self.current_actions = [ # a if isinstance( # a, MarathonDeploymentAction) else MarathonDeploymentAction.from_json(a) # for a in (current_actions or []) # ] # self.current_step = current_step # self.id = id # self.steps = [self.parse_deployment_step(step) for step in (steps or [])] # self.total_steps = total_steps # self.version = version # self.affected_pods = affected_pods # # def parse_deployment_step(self, step): # if step.__class__ == dict: # # This is what Marathon 1.0.0 returns: steps # return MarathonDeploymentStep().from_json(step) # elif step.__class__ == list: # # This is Marathon < 1.0.0 style, a list of actions # return [s if isinstance(s, MarathonDeploymentAction) else MarathonDeploymentAction.from_json(s) for s in step] # else: # return step . Output only the next line.
deployment = MarathonDeployment.from_json(deployment_json)
Next line prediction: <|code_start|> class MarathonContainer(MarathonObject): """Marathon health check. See https://mesosphere.github.io/marathon/docs/native-docker.html :param docker: docker field (e.g., {"image": "mygroup/myimage"})' :type docker: :class:`marathon.models.container.MarathonDockerContainer` or dict :param str type: :param port_mappings: New in Marathon v1.5. container.docker.port_mappings moved here. :type port_mappings: list[:class:`marathon.models.container.MarathonContainerPortMapping`] or list[dict] :param volumes: :type volumes: list[:class:`marathon.models.container.MarathonContainerVolume`] or list[dict] """ TYPES = ['DOCKER', 'MESOS'] """Valid container types""" def __init__(self, docker=None, type='DOCKER', port_mappings=None, volumes=None): if type not in self.TYPES: <|code_end|> . Use current file imports: (from ..exceptions import InvalidChoiceError from .base import MarathonObject) and context including class names, function names, or small code snippets from other files: # Path: marathon/exceptions.py # class InvalidChoiceError(MarathonError): # # def __init__(self, param, value, options): # super().__init__( # 'Invalid choice "{value}" for param "{param}". Must be one of {options}'.format( # param=param, value=value, options=options # ) # ) # # Path: marathon/models/base.py # class MarathonObject: # """Base Marathon object.""" # # def __repr__(self): # return "{clazz}::{obj}".format(clazz=self.__class__.__name__, obj=self.to_json(minimal=False)) # # def __eq__(self, other): # try: # return self.__dict__ == other.__dict__ # except Exception: # return False # # def __hash__(self): # # Technically this class shouldn't be hashable because it often # # contains mutable fields, but in practice this class is used more # # like a record or namedtuple. # return hash(self.to_json()) # # def json_repr(self, minimal=False): # """Construct a JSON-friendly representation of the object. # # :param bool minimal: Construct a minimal representation of the object (ignore nulls and empty collections) # # :rtype: dict # """ # if minimal: # return {to_camel_case(k): v for k, v in vars(self).items() if (v or v is False or v == 0)} # else: # return {to_camel_case(k): v for k, v in vars(self).items()} # # @classmethod # def from_json(cls, attributes): # """Construct an object from a parsed response. # # :param dict attributes: object attributes from parsed response # """ # return cls(**{to_snake_case(k): v for k, v in attributes.items()}) # # def to_json(self, minimal=True): # """Encode an object as a JSON string. # # :param bool minimal: Construct a minimal representation of the object (ignore nulls and empty collections) # # :rtype: str # """ # if minimal: # return json.dumps(self.json_repr(minimal=True), cls=MarathonMinimalJsonEncoder, sort_keys=True) # else: # return json.dumps(self.json_repr(), cls=MarathonJsonEncoder, sort_keys=True) . Output only the next line.
raise InvalidChoiceError('type', type, self.TYPES)
Given the code snippet: <|code_start|> :type http_config: :class:`marathon.models.info.MarathonHttpConfig` or dict :param event_subscriber: :type event_subscriber: :class`marathon.models.info.MarathonEventSubscriber` or dict :param bool elected: :param str buildref: """ def __init__(self, event_subscriber=None, framework_id=None, http_config=None, leader=None, marathon_config=None, name=None, version=None, elected=None, zookeeper_config=None, buildref=None): if isinstance(event_subscriber, MarathonEventSubscriber): self.event_subscriber = event_subscriber elif event_subscriber is not None: self.event_subscriber = MarathonEventSubscriber().from_json( event_subscriber) else: self.event_subscriber = None self.framework_id = framework_id self.http_config = http_config if isinstance(http_config, MarathonHttpConfig) \ else MarathonHttpConfig().from_json(http_config) self.leader = leader self.marathon_config = marathon_config if isinstance(marathon_config, MarathonConfig) \ else MarathonConfig().from_json(marathon_config) self.name = name self.version = version self.elected = elected self.zookeeper_config = zookeeper_config if isinstance(zookeeper_config, MarathonZooKeeperConfig) \ else MarathonZooKeeperConfig().from_json(zookeeper_config) self.buildref = buildref <|code_end|> , generate the next line using the imports in this file: from .base import MarathonObject, MarathonResource and context (functions, classes, or occasionally code) from other files: # Path: marathon/models/base.py # class MarathonObject: # """Base Marathon object.""" # # def __repr__(self): # return "{clazz}::{obj}".format(clazz=self.__class__.__name__, obj=self.to_json(minimal=False)) # # def __eq__(self, other): # try: # return self.__dict__ == other.__dict__ # except Exception: # return False # # def __hash__(self): # # Technically this class shouldn't be hashable because it often # # contains mutable fields, but in practice this class is used more # # like a record or namedtuple. # return hash(self.to_json()) # # def json_repr(self, minimal=False): # """Construct a JSON-friendly representation of the object. # # :param bool minimal: Construct a minimal representation of the object (ignore nulls and empty collections) # # :rtype: dict # """ # if minimal: # return {to_camel_case(k): v for k, v in vars(self).items() if (v or v is False or v == 0)} # else: # return {to_camel_case(k): v for k, v in vars(self).items()} # # @classmethod # def from_json(cls, attributes): # """Construct an object from a parsed response. # # :param dict attributes: object attributes from parsed response # """ # return cls(**{to_snake_case(k): v for k, v in attributes.items()}) # # def to_json(self, minimal=True): # """Encode an object as a JSON string. # # :param bool minimal: Construct a minimal representation of the object (ignore nulls and empty collections) # # :rtype: str # """ # if minimal: # return json.dumps(self.json_repr(minimal=True), cls=MarathonMinimalJsonEncoder, sort_keys=True) # else: # return json.dumps(self.json_repr(), cls=MarathonJsonEncoder, sort_keys=True) # # class MarathonResource(MarathonObject): # # """Base Marathon resource.""" # # def __repr__(self): # if 'id' in list(vars(self).keys()): # return f"{self.__class__.__name__}::{self.id}" # else: # return "{clazz}::{obj}".format(clazz=self.__class__.__name__, obj=self.to_json()) # # def __eq__(self, other): # try: # return self.__dict__ == other.__dict__ # except Exception: # return False # # def __hash__(self): # # Technically this class shouldn't be hashable because it often # # contains mutable fields, but in practice this class is used more # # like a record or namedtuple. # return hash(self.to_json()) # # def __str__(self): # return f"{self.__class__.__name__}::" + str(self.__dict__) . Output only the next line.
class MarathonConfig(MarathonObject):
Predict the next line after this snippet: <|code_start|> if atomic_species is not None: new_atomic_species = set(dataset.get('atomicSpecies', {})) new_atomic_species.update(atomic_species) if atomic_species is not None: updates.setdefault('$set', {})['atomicSpecies'] = list(new_atomic_species) self.ensure_mdb_id(dataset, new_atomic_species, updates) if public is not None: updates.setdefault('$set', {})['public'] = public # Trigger event if this dataset is being approved ( being made public ) if public and not dataset.get('public', False): events.trigger('mdb.dataset.approved', { 'dataset': dataset, 'approver': user }) updates.setdefault('$set', {})['released'] = datetime.datetime.utcnow() if validation is not None: updates.setdefault('$set', {})['validation'] = validation if updates: updates.setdefault('$set', {})['updated'] = datetime.datetime.utcnow() super(Dataset, self).update(query, update=updates, multi=False) return self.load(dataset['_id'], user=user, level=AccessType.READ) return dataset def _normalize_element(self, element): # Try looking up element try: <|code_end|> using the current file's imports: import re import datetime from bson.objectid import ObjectId, InvalidId from girder.models.model_base import AccessControlledModel from girder.constants import AccessType from girder.models.model_base import ValidationException from girder.models.group import Group from girder.models.item import Item from girder.models.file import File from girder import events from girder.plugins.materialsdatabank.models.slug import Slug, SlugUpdateException from girder.plugins.materialsdatabank.models.reconstruction import Reconstruction as ReconstructionModel from girder.plugins.materialsdatabank.models.structure import Structure as StructureModel from girder.plugins.materialsdatabank.models.projection import Projection as ProjectionModel from ..constants import ELEMENT_SYMBOLS_LOWER, ELEMENT_SYMBOLS and any relevant context from other files: # Path: server/materialsdatabank/server/constants.py # ELEMENT_SYMBOLS_LOWER = [x.lower() for x in ELEMENT_SYMBOLS] # # ELEMENT_SYMBOLS = [ # 'Xx', 'H', 'He', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', # 'Ne', 'Na', 'Mg', 'Al', 'Si', 'P', 'S', 'Cl', 'Ar', 'K', # 'Ca', 'Sc', 'Ti', 'V', 'Cr', 'Mn', 'Fe', 'Co', 'Ni', 'Cu', # 'Zn', 'Ga', 'Ge', 'As', 'Se', 'Br', 'Kr', 'Rb', 'Sr', 'Y', # 'Zr', 'Nb', 'Mo', 'Tc', 'Ru', 'Rh', 'Pd', 'Ag', 'Cd', 'In', # 'Sn', 'Sb', 'Te', 'I', 'Xe', 'Cs', 'Ba', 'La', 'Ce', 'Pr', # 'Nd', 'Pm', 'Sm', 'Eu', 'Gd', 'Tb', 'Dy', 'Ho', 'Er', 'Tm', # 'Yb', 'Lu', 'Hf', 'Ta', 'W', 'Re', 'Os', 'Ir', 'Pt', 'Au', # 'Hg', 'Tl', 'Pb', 'Bi', 'Po', 'At', 'Rn', 'Fr', 'Ra', 'Ac', # 'Th', 'Pa', 'U', 'Np', 'Pu', 'Am', 'Cm', 'Bk', 'Cf', 'Es', # 'Fm', 'Md', 'No', 'Lr', 'Rf', 'Db', 'Sg', 'Bh', 'Hs', 'Mt', # 'Ds', 'Rg', 'Cn', 'Uut', 'Uuq', 'Uup', 'Uuh', 'Uus', 'Uuo' # ] . Output only the next line.
atomic_number = ELEMENT_SYMBOLS_LOWER.index(element.lower())
Continue the code snippet: <|code_start|> for s in species: if len(s) <= _chars_left(): prefix.append(s) prefix += ['X'] * _chars_left() return ''.join(prefix) def _generate_mdb_id_postfix(self, prefix): # Search for existing datasets with this prefix regex = re.compile('^%s(\d{5})' % prefix) query = { 'mdbId': { '$regex': regex } } cursor = super(Dataset, self).find(query, fields=['mdbId']) postfix = 0 for d in cursor: match = regex.match(d['mdbId']) p = int(match.group(1)) if p > postfix: postfix = p postfix += 1 return str(postfix).zfill(5) def ensure_mdb_id(self, dataset, species, updates): <|code_end|> . Use current file imports: import re import datetime from bson.objectid import ObjectId, InvalidId from girder.models.model_base import AccessControlledModel from girder.constants import AccessType from girder.models.model_base import ValidationException from girder.models.group import Group from girder.models.item import Item from girder.models.file import File from girder import events from girder.plugins.materialsdatabank.models.slug import Slug, SlugUpdateException from girder.plugins.materialsdatabank.models.reconstruction import Reconstruction as ReconstructionModel from girder.plugins.materialsdatabank.models.structure import Structure as StructureModel from girder.plugins.materialsdatabank.models.projection import Projection as ProjectionModel from ..constants import ELEMENT_SYMBOLS_LOWER, ELEMENT_SYMBOLS and context (classes, functions, or code) from other files: # Path: server/materialsdatabank/server/constants.py # ELEMENT_SYMBOLS_LOWER = [x.lower() for x in ELEMENT_SYMBOLS] # # ELEMENT_SYMBOLS = [ # 'Xx', 'H', 'He', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', # 'Ne', 'Na', 'Mg', 'Al', 'Si', 'P', 'S', 'Cl', 'Ar', 'K', # 'Ca', 'Sc', 'Ti', 'V', 'Cr', 'Mn', 'Fe', 'Co', 'Ni', 'Cu', # 'Zn', 'Ga', 'Ge', 'As', 'Se', 'Br', 'Kr', 'Rb', 'Sr', 'Y', # 'Zr', 'Nb', 'Mo', 'Tc', 'Ru', 'Rh', 'Pd', 'Ag', 'Cd', 'In', # 'Sn', 'Sb', 'Te', 'I', 'Xe', 'Cs', 'Ba', 'La', 'Ce', 'Pr', # 'Nd', 'Pm', 'Sm', 'Eu', 'Gd', 'Tb', 'Dy', 'Ho', 'Er', 'Tm', # 'Yb', 'Lu', 'Hf', 'Ta', 'W', 'Re', 'Os', 'Ir', 'Pt', 'Au', # 'Hg', 'Tl', 'Pb', 'Bi', 'Po', 'At', 'Rn', 'Fr', 'Ra', 'Ac', # 'Th', 'Pa', 'U', 'Np', 'Pu', 'Am', 'Cm', 'Bk', 'Cf', 'Es', # 'Fm', 'Md', 'No', 'Lr', 'Rf', 'Db', 'Sg', 'Bh', 'Hs', 'Mt', # 'Ds', 'Rg', 'Cn', 'Uut', 'Uuq', 'Uup', 'Uuh', 'Uus', 'Uuo' # ] . Output only the next line.
species = [ELEMENT_SYMBOLS[n] for n in species]
Using the snippet: <|code_start|> elif "rdf" in bits[0]: return "rdf_" + bits[1] elif "model-qualifiers" in bits[0]: return "bqmodel_" + bits[1] elif "biology-qualifiers" in bits[0]: return "bqbiol_" + bits[1] else: return "%s:%s" % (bits[0], bits[1]) class LEMSXMLNode: def __init__(self, pyxmlnode): self.tag = get_nons_tag_from_node(pyxmlnode) self.ltag = self.tag.lower() self.attrib = dict() self.lattrib = dict() for k in pyxmlnode.attrib: self.attrib[k] = pyxmlnode.attrib[k] self.lattrib[k.lower()] = pyxmlnode.attrib[k] self.children = list() for pyxmlchild in pyxmlnode: self.children.append(LEMSXMLNode(pyxmlchild)) def __str__(self): return "LEMSXMLNode <{0} {1}>".format(self.tag, self.attrib) <|code_end|> , determine the next line of code. You have imports: import xml.etree.ElementTree as xe from lems.base.base import LEMSBase from lems.base.errors import ParseError from lems.model.fundamental import * from lems.model.component import * from lems.model.dynamics import * from lems.model.structure import * from lems.model.simulation import * from lems.base.util import make_id and context (class names, function names, or code) available: # Path: lems/base/base.py # class LEMSBase(object): # """ # Base object for PyLEMS. # """ # # def copy(self): # return copy.deepcopy(self) # # def toxml(self): # return "" # # Path: lems/base/errors.py # class ParseError(LEMSError): # """ # Exception class to signal errors found during parsing. # """ # # pass # # Path: lems/base/util.py # def make_id(): # global id_counter # id_counter = id_counter + 1 # return "__id_{0}__".format(id_counter) . Output only the next line.
class LEMSFileParser(LEMSBase):
Next line prediction: <|code_start|> if tag == "": t = node.ltag else: t = tag.lower() for child in node.children: self.xml_node_stack = [child] + self.xml_node_stack ctagl = child.ltag if ctagl in self.tag_parse_table and ctagl in self.valid_children[t]: # print("Processing known type: %s"%ctagl) self.tag_parse_table[ctagl](child) else: # print("Processing unknown type: %s"%ctagl) self.parse_component_by_typename(child, child.tag) self.xml_node_stack = self.xml_node_stack[1:] def parse(self, xmltext): """ Parse a string containing LEMS XML text. :param xmltext: String containing LEMS XML formatted text. :type xmltext: str """ xml = LEMSXMLNode(xe.XML(xmltext)) if xml.ltag != "lems" and xml.ltag != "neuroml": <|code_end|> . Use current file imports: (import xml.etree.ElementTree as xe from lems.base.base import LEMSBase from lems.base.errors import ParseError from lems.model.fundamental import * from lems.model.component import * from lems.model.dynamics import * from lems.model.structure import * from lems.model.simulation import * from lems.base.util import make_id) and context including class names, function names, or small code snippets from other files: # Path: lems/base/base.py # class LEMSBase(object): # """ # Base object for PyLEMS. # """ # # def copy(self): # return copy.deepcopy(self) # # def toxml(self): # return "" # # Path: lems/base/errors.py # class ParseError(LEMSError): # """ # Exception class to signal errors found during parsing. # """ # # pass # # Path: lems/base/util.py # def make_id(): # global id_counter # id_counter = id_counter + 1 # return "__id_{0}__".format(id_counter) . Output only the next line.
raise ParseError(
Predict the next line after this snippet: <|code_start|> component = Component(id_, type_) if self.current_component: component.set_parent_id(self.current_component.id) self.current_component.add_child(component) else: self.model.add_component(component) for key in node.attrib: if key.lower() not in ["id", "type"]: component.set_parameter(key, node.attrib[key]) old_component = self.current_component self.current_component = component self.process_nested_tags(node, "component") self.current_component = old_component def parse_component(self, node): """ Parses <Component> :param node: Node containing the <Component> element :type node: xml.etree.Element """ if "id" in node.lattrib: id_ = node.lattrib["id"] else: # self.raise_error('Component must have an id') <|code_end|> using the current file's imports: import xml.etree.ElementTree as xe from lems.base.base import LEMSBase from lems.base.errors import ParseError from lems.model.fundamental import * from lems.model.component import * from lems.model.dynamics import * from lems.model.structure import * from lems.model.simulation import * from lems.base.util import make_id and any relevant context from other files: # Path: lems/base/base.py # class LEMSBase(object): # """ # Base object for PyLEMS. # """ # # def copy(self): # return copy.deepcopy(self) # # def toxml(self): # return "" # # Path: lems/base/errors.py # class ParseError(LEMSError): # """ # Exception class to signal errors found during parsing. # """ # # pass # # Path: lems/base/util.py # def make_id(): # global id_counter # id_counter = id_counter + 1 # return "__id_{0}__".format(id_counter) . Output only the next line.
id_ = make_id()
Given the code snippet: <|code_start|>""" Simulation. :author: Gautham Ganapathy :organization: LEMS (https://github.com/organizations/LEMS) """ <|code_end|> , generate the next line using the imports in this file: from lems.base.base import LEMSBase from lems.base.errors import SimError import heapq and context (functions, classes, or occasionally code) from other files: # Path: lems/base/base.py # class LEMSBase(object): # """ # Base object for PyLEMS. # """ # # def copy(self): # return copy.deepcopy(self) # # def toxml(self): # return "" # # Path: lems/base/errors.py # class SimError(LEMSError): # """ # Exception class to signal errors in simulation. # """ # # pass . Output only the next line.
class Simulation(LEMSBase):
Based on the snippet: <|code_start|> debug = False def __init__(self): """ Constructor. """ self.runnables = {} """ Dictionary of runnable components in this simulation. :type: dict(string -> lems.sim.runnable.Runnable) """ self.run_queue = [] """ Priority of pairs of (time-to-next run, runnable). :type: list((Integer, lems.sim.runnable.Runnable)) """ self.event_queue = [] """ List of posted events. :type: list(lems.sim.sim.Event) """ def add_runnable(self, runnable): """ Adds a runnable component to the list of runnable components in this simulation. :param runnable: A runnable component :type runnable: lems.sim.runnable.Runnable """ if runnable.id in self.runnables: <|code_end|> , predict the immediate next line with the help of imports: from lems.base.base import LEMSBase from lems.base.errors import SimError import heapq and context (classes, functions, sometimes code) from other files: # Path: lems/base/base.py # class LEMSBase(object): # """ # Base object for PyLEMS. # """ # # def copy(self): # return copy.deepcopy(self) # # def toxml(self): # return "" # # Path: lems/base/errors.py # class SimError(LEMSError): # """ # Exception class to signal errors in simulation. # """ # # pass . Output only the next line.
raise SimError("Duplicate runnable component {0}".format(runnable.id))
Next line prediction: <|code_start|>""" Simulation specification classes. :author: Gautham Ganapathy :organization: LEMS (https://github.com/organizations/LEMS) """ <|code_end|> . Use current file imports: (from lems.base.base import LEMSBase from lems.base.errors import ModelError from lems.base.map import Map) and context including class names, function names, or small code snippets from other files: # Path: lems/base/base.py # class LEMSBase(object): # """ # Base object for PyLEMS. # """ # # def copy(self): # return copy.deepcopy(self) # # def toxml(self): # return "" # # Path: lems/base/errors.py # class ModelError(LEMSError): # """ # Exception class to signal errors in creating the model. # """ # # pass # # Path: lems/base/map.py # class Map(dict, LEMSBase): # """ # Map class. # # Same as dict, but iterates over values. # """ # # def __init__(self, *params, **key_params): # """ # Constructor. # """ # # dict.__init__(self, *params, **key_params) # # def __iter__(self): # """ # Returns an iterator. # """ # # return iter(self.values()) . Output only the next line.
class Run(LEMSBase):
Predict the next line after this snippet: <|code_start|> def add_event_writer(self, event_writer): """ Adds an event writer to this simulation section. :param event_writer: event writer to be added. :type event_writer: lems.model.simulation.EventWriter """ self.event_writers[event_writer.path] = event_writer def add(self, child): """ Adds a typed child object to the simulation spec. :param child: Child object to be added. """ if isinstance(child, Run): self.add_run(child) elif isinstance(child, Record): self.add_record(child) elif isinstance(child, EventRecord): self.add_event_record(child) elif isinstance(child, DataDisplay): self.add_data_display(child) elif isinstance(child, DataWriter): self.add_data_writer(child) elif isinstance(child, EventWriter): self.add_event_writer(child) else: <|code_end|> using the current file's imports: from lems.base.base import LEMSBase from lems.base.errors import ModelError from lems.base.map import Map and any relevant context from other files: # Path: lems/base/base.py # class LEMSBase(object): # """ # Base object for PyLEMS. # """ # # def copy(self): # return copy.deepcopy(self) # # def toxml(self): # return "" # # Path: lems/base/errors.py # class ModelError(LEMSError): # """ # Exception class to signal errors in creating the model. # """ # # pass # # Path: lems/base/map.py # class Map(dict, LEMSBase): # """ # Map class. # # Same as dict, but iterates over values. # """ # # def __init__(self, *params, **key_params): # """ # Constructor. # """ # # dict.__init__(self, *params, **key_params) # # def __iter__(self): # """ # Returns an iterator. # """ # # return iter(self.values()) . Output only the next line.
raise ModelError("Unsupported child element")
Given the following code snippet before the placeholder: <|code_start|> self.format = format """ Text parameter to be used for the format :type: string """ def toxml(self): """ Exports this object into a LEMS XML object """ return '<EventWriter path="{0}" fileName="{1}" format="{2}"/>'.format( self.path, self.file_name, self.format ) def __str__(self): return "EventWriter, path: {0}, fileName: {1}, format: {2}".format( self.path, self.file_name, self.format ) class Simulation(LEMSBase): """ Stores the simulation-related attributes of a component-type. """ def __init__(self): """ Constructor. """ <|code_end|> , predict the next line using imports from the current file: from lems.base.base import LEMSBase from lems.base.errors import ModelError from lems.base.map import Map and context including class names, function names, and sometimes code from other files: # Path: lems/base/base.py # class LEMSBase(object): # """ # Base object for PyLEMS. # """ # # def copy(self): # return copy.deepcopy(self) # # def toxml(self): # return "" # # Path: lems/base/errors.py # class ModelError(LEMSError): # """ # Exception class to signal errors in creating the model. # """ # # pass # # Path: lems/base/map.py # class Map(dict, LEMSBase): # """ # Map class. # # Same as dict, but iterates over values. # """ # # def __init__(self, *params, **key_params): # """ # Constructor. # """ # # dict.__init__(self, *params, **key_params) # # def __iter__(self): # """ # Returns an iterator. # """ # # return iter(self.values()) . Output only the next line.
self.runs = Map()
Continue the code snippet: <|code_start|>""" Dimension and Unit definitions in terms of the fundamental SI units. :author: Gautham Ganapathy :organization: LEMS (https://github.com/organizations/LEMS) """ <|code_end|> . Use current file imports: from lems.base.base import LEMSBase and context (classes, functions, or code) from other files: # Path: lems/base/base.py # class LEMSBase(object): # """ # Base object for PyLEMS. # """ # # def copy(self): # return copy.deepcopy(self) # # def toxml(self): # return "" . Output only the next line.
class Include(LEMSBase):
Here is a snippet: <|code_start|>""" Base class for runnable components. :author: Gautham Ganapathy :organization: LEMS (https://github.com/organizations/LEMS) """ # import math # class Ex1(Exception): # pass # def exp(x): # try: # return math.exp(x) # except Exception as e: # print('ERROR performing exp({0})'.format(x)) # raise Ex1() <|code_end|> . Write the next line using the current file imports: from lems.base.base import LEMSBase from lems.base.stack import Stack from lems.base.errors import SimBuildError from lems.sim.recording import Recording from math import * import ast import sys and context from other files: # Path: lems/base/base.py # class LEMSBase(object): # """ # Base object for PyLEMS. # """ # # def copy(self): # return copy.deepcopy(self) # # def toxml(self): # return "" # # Path: lems/base/stack.py # class Stack(LEMSBase): # """ # Basic stack implementation. # """ # # def __init__(self): # """ # Constructor. # """ # # self.stack = [] # """ List used to store the stack contents. # :type: list """ # # def push(self, val): # """ # Pushed a value onto the stack. # # :param val: Value to be pushed. # :type val: * # """ # # self.stack = [val] + self.stack # # def pop(self): # """ # Pops a value off the top of the stack. # # :return: Value popped off the stack. # :rtype: * # # :raises StackError: Raised when there is a stack underflow. # """ # # if self.stack: # val = self.stack[0] # self.stack = self.stack[1:] # return val # else: # raise StackError("Stack empty") # # def top(self): # """ # Returns the value off the top of the stack without popping. # # :return: Value on the top of the stack. # :rtype: * # # :raises StackError: Raised when there is a stack underflow. # """ # # if self.stack: # return self.stack[0] # else: # raise StackError("Stack empty") # # def is_empty(self): # """ # Checks if the stack is empty. # # :return: True if the stack is empty, otherwise False. # :rtype: Boolean # """ # # return self.stack == [] # # def __str__(self): # """ # Returns a string representation of the stack. # # @note: This assumes that the stack contents are capable of generating # string representations. # """ # # if len(self.stack) == 0: # s = "[]" # else: # s = "[" + str(self.stack[0]) # for i in range(1, len(self.stack)): # s += ", " + str(self.stack[i]) # s += "]" # return s # # def __repr__(self): # return self.__str__() # # Path: lems/base/errors.py # class SimBuildError(LEMSError): # """ # Exception class to signal errors in building the simulation. # """ # # pass # # Path: lems/sim/recording.py # class Recording(LEMSBase): # """ # Stores details of a variable recording across a single simulation run. # """ # # def __init__(self, variable, full_path, data_output, recorder): # self.variable = variable # # self.full_path = full_path # # self.data_output = data_output # # self.recorder = recorder # # self.values = [] # # def __str__(self): # return "Recording: {0} ({1}), {2}, size: {3}".format( # self.variable, self.full_path, self.recorder, len(self.values) # ) # # def __repr__(self): # return self.__str__() # # def add_value(self, time, value): # self.values.append((time, value)) , which may include functions, classes, or code. Output only the next line.
class Reflective(LEMSBase):
Predict the next line after this snippet: <|code_start|>class Regime: def __init__(self, name): self.name = name self.update_state_variables = None self.update_derived_variables = None self.run_startup_event_handlers = None self.run_preprocessing_event_handlers = None self.run_postprocessing_event_handlers = None self.update_kinetic_scheme = None class Runnable(Reflective): uid_count = 0 def __init__(self, id_, component, parent=None): Reflective.__init__(self) self.uid = Runnable.uid_count Runnable.uid_count += 1 self.id = id_ self.component = component self.parent = parent self.time_step = 0 self.time_completed = 0 self.time_total = 0 self.plastic = True <|code_end|> using the current file's imports: from lems.base.base import LEMSBase from lems.base.stack import Stack from lems.base.errors import SimBuildError from lems.sim.recording import Recording from math import * import ast import sys and any relevant context from other files: # Path: lems/base/base.py # class LEMSBase(object): # """ # Base object for PyLEMS. # """ # # def copy(self): # return copy.deepcopy(self) # # def toxml(self): # return "" # # Path: lems/base/stack.py # class Stack(LEMSBase): # """ # Basic stack implementation. # """ # # def __init__(self): # """ # Constructor. # """ # # self.stack = [] # """ List used to store the stack contents. # :type: list """ # # def push(self, val): # """ # Pushed a value onto the stack. # # :param val: Value to be pushed. # :type val: * # """ # # self.stack = [val] + self.stack # # def pop(self): # """ # Pops a value off the top of the stack. # # :return: Value popped off the stack. # :rtype: * # # :raises StackError: Raised when there is a stack underflow. # """ # # if self.stack: # val = self.stack[0] # self.stack = self.stack[1:] # return val # else: # raise StackError("Stack empty") # # def top(self): # """ # Returns the value off the top of the stack without popping. # # :return: Value on the top of the stack. # :rtype: * # # :raises StackError: Raised when there is a stack underflow. # """ # # if self.stack: # return self.stack[0] # else: # raise StackError("Stack empty") # # def is_empty(self): # """ # Checks if the stack is empty. # # :return: True if the stack is empty, otherwise False. # :rtype: Boolean # """ # # return self.stack == [] # # def __str__(self): # """ # Returns a string representation of the stack. # # @note: This assumes that the stack contents are capable of generating # string representations. # """ # # if len(self.stack) == 0: # s = "[]" # else: # s = "[" + str(self.stack[0]) # for i in range(1, len(self.stack)): # s += ", " + str(self.stack[i]) # s += "]" # return s # # def __repr__(self): # return self.__str__() # # Path: lems/base/errors.py # class SimBuildError(LEMSError): # """ # Exception class to signal errors in building the simulation. # """ # # pass # # Path: lems/sim/recording.py # class Recording(LEMSBase): # """ # Stores details of a variable recording across a single simulation run. # """ # # def __init__(self, variable, full_path, data_output, recorder): # self.variable = variable # # self.full_path = full_path # # self.data_output = data_output # # self.recorder = recorder # # self.values = [] # # def __str__(self): # return "Recording: {0} ({1}), {2}, size: {3}".format( # self.variable, self.full_path, self.recorder, len(self.values) # ) # # def __repr__(self): # return self.__str__() # # def add_value(self, time, value): # self.values.append((time, value)) . Output only the next line.
self.state_stack = Stack()
Predict the next line for this snippet: <|code_start|> def add_child_typeref(self, typename, runnable): self.__dict__[typename] = runnable def add_child_to_group(self, group_name, child): # print("add_child_to_group in %s; grp: %s; child: %s "%(self.id, group_name, child)) if group_name not in self.__dict__: # print sorted(self.__dict__.keys()) self.__dict__[group_name] = [] self.groups.append(group_name) # print sorted(self.__dict__.keys()) # print ".........." # print self.__dict__[group_name] # Force group_name attribute to be a list before we append to it. if type(self.__dict__[group_name]) is not list: self.__dict__[group_name] = [self.__dict__[group_name]] self.__dict__[group_name].append(child) child.parent = self def make_attachment(self, type_, name): self.attachments[type_] = name self.__dict__[name] = [] def add_attachment(self, runnable, container=None): for ctype in runnable.component.types: if ctype in self.attachments: name = self.attachments[ctype] if container is not None and container != name: continue if name not in self.__dict__: <|code_end|> with the help of current file imports: from lems.base.base import LEMSBase from lems.base.stack import Stack from lems.base.errors import SimBuildError from lems.sim.recording import Recording from math import * import ast import sys and context from other files: # Path: lems/base/base.py # class LEMSBase(object): # """ # Base object for PyLEMS. # """ # # def copy(self): # return copy.deepcopy(self) # # def toxml(self): # return "" # # Path: lems/base/stack.py # class Stack(LEMSBase): # """ # Basic stack implementation. # """ # # def __init__(self): # """ # Constructor. # """ # # self.stack = [] # """ List used to store the stack contents. # :type: list """ # # def push(self, val): # """ # Pushed a value onto the stack. # # :param val: Value to be pushed. # :type val: * # """ # # self.stack = [val] + self.stack # # def pop(self): # """ # Pops a value off the top of the stack. # # :return: Value popped off the stack. # :rtype: * # # :raises StackError: Raised when there is a stack underflow. # """ # # if self.stack: # val = self.stack[0] # self.stack = self.stack[1:] # return val # else: # raise StackError("Stack empty") # # def top(self): # """ # Returns the value off the top of the stack without popping. # # :return: Value on the top of the stack. # :rtype: * # # :raises StackError: Raised when there is a stack underflow. # """ # # if self.stack: # return self.stack[0] # else: # raise StackError("Stack empty") # # def is_empty(self): # """ # Checks if the stack is empty. # # :return: True if the stack is empty, otherwise False. # :rtype: Boolean # """ # # return self.stack == [] # # def __str__(self): # """ # Returns a string representation of the stack. # # @note: This assumes that the stack contents are capable of generating # string representations. # """ # # if len(self.stack) == 0: # s = "[]" # else: # s = "[" + str(self.stack[0]) # for i in range(1, len(self.stack)): # s += ", " + str(self.stack[i]) # s += "]" # return s # # def __repr__(self): # return self.__str__() # # Path: lems/base/errors.py # class SimBuildError(LEMSError): # """ # Exception class to signal errors in building the simulation. # """ # # pass # # Path: lems/sim/recording.py # class Recording(LEMSBase): # """ # Stores details of a variable recording across a single simulation run. # """ # # def __init__(self, variable, full_path, data_output, recorder): # self.variable = variable # # self.full_path = full_path # # self.data_output = data_output # # self.recorder = recorder # # self.values = [] # # def __str__(self): # return "Recording: {0} ({1}), {2}, size: {3}".format( # self.variable, self.full_path, self.recorder, len(self.values) # ) # # def __repr__(self): # return self.__str__() # # def add_value(self, time, value): # self.values.append((time, value)) , which may contain function names, class names, or code. Output only the next line.
raise SimBuildError(
Given the code snippet: <|code_start|> if child in self.children: childobj = self.children[child] if idx == -1: childobj.add_variable_recorder2( data_output, recorder, new_path, full_path ) else: childobj.array[idx].add_variable_recorder2( data_output, recorder, new_path, full_path ) elif child in self.component.children: cdef = self.component.children[child] childobj = None for cid in self.children: c = self.children[cid] if cdef.type in c.component.types: childobj = c if childobj: childobj.add_variable_recorder2(data_output, recorder, new_path) else: raise SimBuildError( "Unable to find the child '{0}' in " "'{1}'".format(child, self.id) ) else: raise SimBuildError( "Unable to find a child '{0}' in " "'{1}'".format(child, self.id) ) else: self.recorded_variables.append( <|code_end|> , generate the next line using the imports in this file: from lems.base.base import LEMSBase from lems.base.stack import Stack from lems.base.errors import SimBuildError from lems.sim.recording import Recording from math import * import ast import sys and context (functions, classes, or occasionally code) from other files: # Path: lems/base/base.py # class LEMSBase(object): # """ # Base object for PyLEMS. # """ # # def copy(self): # return copy.deepcopy(self) # # def toxml(self): # return "" # # Path: lems/base/stack.py # class Stack(LEMSBase): # """ # Basic stack implementation. # """ # # def __init__(self): # """ # Constructor. # """ # # self.stack = [] # """ List used to store the stack contents. # :type: list """ # # def push(self, val): # """ # Pushed a value onto the stack. # # :param val: Value to be pushed. # :type val: * # """ # # self.stack = [val] + self.stack # # def pop(self): # """ # Pops a value off the top of the stack. # # :return: Value popped off the stack. # :rtype: * # # :raises StackError: Raised when there is a stack underflow. # """ # # if self.stack: # val = self.stack[0] # self.stack = self.stack[1:] # return val # else: # raise StackError("Stack empty") # # def top(self): # """ # Returns the value off the top of the stack without popping. # # :return: Value on the top of the stack. # :rtype: * # # :raises StackError: Raised when there is a stack underflow. # """ # # if self.stack: # return self.stack[0] # else: # raise StackError("Stack empty") # # def is_empty(self): # """ # Checks if the stack is empty. # # :return: True if the stack is empty, otherwise False. # :rtype: Boolean # """ # # return self.stack == [] # # def __str__(self): # """ # Returns a string representation of the stack. # # @note: This assumes that the stack contents are capable of generating # string representations. # """ # # if len(self.stack) == 0: # s = "[]" # else: # s = "[" + str(self.stack[0]) # for i in range(1, len(self.stack)): # s += ", " + str(self.stack[i]) # s += "]" # return s # # def __repr__(self): # return self.__str__() # # Path: lems/base/errors.py # class SimBuildError(LEMSError): # """ # Exception class to signal errors in building the simulation. # """ # # pass # # Path: lems/sim/recording.py # class Recording(LEMSBase): # """ # Stores details of a variable recording across a single simulation run. # """ # # def __init__(self, variable, full_path, data_output, recorder): # self.variable = variable # # self.full_path = full_path # # self.data_output = data_output # # self.recorder = recorder # # self.values = [] # # def __str__(self): # return "Recording: {0} ({1}), {2}, size: {3}".format( # self.variable, self.full_path, self.recorder, len(self.values) # ) # # def __repr__(self): # return self.__str__() # # def add_value(self, time, value): # self.values.append((time, value)) . Output only the next line.
Recording(path, full_path, data_output, recorder)
Continue the code snippet: <|code_start|> model = lems.Model() model.add(lems.Dimension("voltage", m=1, l=3, t=-3, i=-1)) model.add(lems.Dimension("time", t=1)) model.add(lems.Dimension("capacitance", m=-1, l=-2, t=4, i=2)) model.add(lems.Unit("milliVolt", "mV", "voltage", -3)) model.add(lems.Unit("milliSecond", "ms", "time", -3)) model.add(lems.Unit("microFarad", "uF", "capacitance", -12)) iaf1 = lems.ComponentType("iaf1") model.add(iaf1) iaf1.add(lems.Parameter("threshold", "voltage")) iaf1.add(lems.Parameter("refractoryPeriod", "time")) iaf1.add(lems.Parameter("capacitance", "capacitance")) model.add(lems.Component("celltype_a", "iaf1")) fn = "/tmp/model.xml" model.export_to_file(fn) print("----------------------------------------------") print(open(fn, "r").read()) print("----------------------------------------------") print("Written generated LEMS to %s" % fn) <|code_end|> . Use current file imports: import lems.api as lems from lems.base.util import validate_lems and context (classes, functions, or code) from other files: # Path: lems/base/util.py # def validate_lems(file_name): # # from lxml import etree # # try: # from urllib2 import urlopen # Python 2 # except: # from urllib.request import urlopen # Python 3 # # schema_file = urlopen(__schema_location__) # xmlschema = etree.XMLSchema(etree.parse(schema_file)) # print("Validating {0} against {1}".format(file_name, schema_file.geturl())) # xmlschema.assertValid(etree.parse(file_name)) # print("It's valid!") . Output only the next line.
validate_lems(fn)
Given the following code snippet before the placeholder: <|code_start|>""" Map class. :author: Gautham Ganapathy :organization: LEMS (https://github.com/organizations/LEMS) """ <|code_end|> , predict the next line using imports from the current file: from lems.base.base import LEMSBase and context including class names, function names, and sometimes code from other files: # Path: lems/base/base.py # class LEMSBase(object): # """ # Base object for PyLEMS. # """ # # def copy(self): # return copy.deepcopy(self) # # def toxml(self): # return "" . Output only the next line.
class Map(dict, LEMSBase):
Using the snippet: <|code_start|> iaf1.add(lems.Parameter("threshold", "voltage")) iaf1.add(lems.Parameter("reset", "voltage")) iaf1.add(lems.Parameter("refractoryPeriod", "time")) iaf1.add(lems.Parameter("capacitance", "capacitance")) iaf1.add(lems.Exposure("vexp", "voltage")) dp = lems.DerivedParameter("range", "threshold - reset", "voltage") iaf1.add(dp) iaf1.dynamics.add(lems.StateVariable("v", "voltage", "vexp")) iaf1.dynamics.add(lems.DerivedVariable("v2", dimension="voltage", value="v*2")) cdv = lems.ConditionalDerivedVariable("v_abs", "voltage") cdv.add(lems.Case("v .geq. 0", "v")) cdv.add(lems.Case("v .lt. 0", "-1*v")) iaf1.dynamics.add(cdv) model.add(lems.Component("celltype_a", iaf1.name)) model.add(lems.Component("celltype_b", iaf1.name, threshold="20mV")) fn = "/tmp/model.xml" model.export_to_file(fn) print("----------------------------------------------") print(open(fn, "r").read()) print("----------------------------------------------") print("Written generated LEMS to %s" % fn) <|code_end|> , determine the next line of code. You have imports: import lems.api as lems from lems.base.util import validate_lems and context (class names, function names, or code) available: # Path: lems/base/util.py # def validate_lems(file_name): # # from lxml import etree # # try: # from urllib2 import urlopen # Python 2 # except: # from urllib.request import urlopen # Python 3 # # schema_file = urlopen(__schema_location__) # xmlschema = etree.XMLSchema(etree.parse(schema_file)) # print("Validating {0} against {1}".format(file_name, schema_file.geturl())) # xmlschema.assertValid(etree.parse(file_name)) # print("It's valid!") . Output only the next line.
validate_lems(fn)
Given the code snippet: <|code_start|> """<Lems> <!-- regression test data for https://github.com/LEMS/pylems/issues/20 --> <Target component="sim1"/> <Include file="Simulation.xml"/> <Include file="Cells.xml"/> <Include file="{}"/> <Simulation id="sim1" length="100ms" step="0.1ms" target="cell1"> <!-- (x|y)(min|max) don't appear to do anything with PyLEMS, but error if not included... --> <OutputFile path="." fileName="reg_20.dat"> <OutputColumn quantity="v" /> </OutputFile> </Simulation> </Lems> """.format( nml_file.name ) ) xml_file = tempfile.NamedTemporaryFile(mode="w+b") xml_file.write(str.encode(reg_20_xml)) xml_file.flush() # TODO: replace this with pynml's extract LEMS files function when that has # been merged and released. We won't need to carry a copy of the coretypes # then. coretype_files_dir = ( os.path.dirname(os.path.abspath(__file__)) + "/NeuroML2CoreTypes" ) <|code_end|> , generate the next line using the imports in this file: import unittest import os import textwrap import tempfile import typing from lems.run import run as lems_run and context (functions, classes, or occasionally code) from other files: # Path: lems/run.py # def run(file_path, include_dirs=[], dlems=False, nogui=False): # """ # Function for running from a script or shell. # """ # import argparse # # args = argparse.Namespace() # args.lems_file = file_path # args.I = include_dirs # args.dlems = dlems # args.nogui = nogui # main(args=args) . Output only the next line.
lems_run(xml_file.name, include_dirs=[coretype_files_dir])
Given the following code snippet before the placeholder: <|code_start|> iaf1.add(lems.Parameter("threshold", "voltage")) iaf1.add(lems.Parameter("reset", "voltage")) iaf1.add(lems.Parameter("refractoryPeriod", "time")) iaf1.add(lems.Parameter("capacitance", "capacitance")) iaf1.add(lems.Exposure("vexp", "voltage")) dp = lems.DerivedParameter("range", "threshold - reset", "voltage") iaf1.add(dp) iaf1.dynamics.add(lems.StateVariable("v", "voltage", "vexp")) iaf1.dynamics.add(lems.DerivedVariable("v2", dimension="voltage", value="v*2")) cdv = lems.ConditionalDerivedVariable("v_abs", "voltage") cdv.add(lems.Case("v .geq. 0", "v")) cdv.add(lems.Case("v .lt. 0", "-1*v")) iaf1.dynamics.add(cdv) model.add(lems.Component("celltype_a", iaf1.name)) model.add(lems.Component("celltype_b", iaf1.name, threshold="20mV")) fn = "/tmp/model.xml" model.export_to_file(fn) print("----------------------------------------------") print(open(fn, "r").read()) print("----------------------------------------------") print("Written generated LEMS to %s" % fn) <|code_end|> , predict the next line using imports from the current file: import lems.api as lems from lems.base.util import validate_lems and context including class names, function names, and sometimes code from other files: # Path: lems/base/util.py # def validate_lems(file_name): # # from lxml import etree # # try: # from urllib2 import urlopen # Python 2 # except: # from urllib.request import urlopen # Python 3 # # schema_file = urlopen(__schema_location__) # xmlschema = etree.XMLSchema(etree.parse(schema_file)) # print("Validating {0} against {1}".format(file_name, schema_file.geturl())) # xmlschema.assertValid(etree.parse(file_name)) # print("It's valid!") . Output only the next line.
validate_lems(fn)
Based on the snippet: <|code_start|>""" Stack class. :author: Gautham Ganapathy :organization: LEMS (https://github.com/organizations/LEMS) """ <|code_end|> , predict the immediate next line with the help of imports: from lems.base.base import LEMSBase from lems.base.errors import StackError and context (classes, functions, sometimes code) from other files: # Path: lems/base/base.py # class LEMSBase(object): # """ # Base object for PyLEMS. # """ # # def copy(self): # return copy.deepcopy(self) # # def toxml(self): # return "" # # Path: lems/base/errors.py # class StackError(LEMSError): # """ # Exception class to signal errors in the Stack class. # """ # # pass . Output only the next line.
class Stack(LEMSBase):
Using the snippet: <|code_start|> self.stack = [] """ List used to store the stack contents. :type: list """ def push(self, val): """ Pushed a value onto the stack. :param val: Value to be pushed. :type val: * """ self.stack = [val] + self.stack def pop(self): """ Pops a value off the top of the stack. :return: Value popped off the stack. :rtype: * :raises StackError: Raised when there is a stack underflow. """ if self.stack: val = self.stack[0] self.stack = self.stack[1:] return val else: <|code_end|> , determine the next line of code. You have imports: from lems.base.base import LEMSBase from lems.base.errors import StackError and context (class names, function names, or code) available: # Path: lems/base/base.py # class LEMSBase(object): # """ # Base object for PyLEMS. # """ # # def copy(self): # return copy.deepcopy(self) # # def toxml(self): # return "" # # Path: lems/base/errors.py # class StackError(LEMSError): # """ # Exception class to signal errors in the Stack class. # """ # # pass . Output only the next line.
raise StackError("Stack empty")
Predict the next line after this snippet: <|code_start|>""" Recording class(es). :author: Gautham Ganapathy :organization: LEMS (https://github.com/organizations/LEMS) """ <|code_end|> using the current file's imports: from lems.base.base import LEMSBase and any relevant context from other files: # Path: lems/base/base.py # class LEMSBase(object): # """ # Base object for PyLEMS. # """ # # def copy(self): # return copy.deepcopy(self) # # def toxml(self): # return "" . Output only the next line.
class Recording(LEMSBase):
Given snippet: <|code_start|>""" Expression parser :author: Gautham Ganapathy :organization: LEMS (https://github.com/organizations/LEMS) """ known_functions = [ "exp", "log", "sqrt", "sin", "cos", "tan", "sinh", "cosh", "tanh", "abs", "ceil", "factorial", "random", "H", ] <|code_end|> , continue by predicting the next line. Consider current file imports: from lems.base.base import LEMSBase from lems.base.stack import Stack and context: # Path: lems/base/base.py # class LEMSBase(object): # """ # Base object for PyLEMS. # """ # # def copy(self): # return copy.deepcopy(self) # # def toxml(self): # return "" # # Path: lems/base/stack.py # class Stack(LEMSBase): # """ # Basic stack implementation. # """ # # def __init__(self): # """ # Constructor. # """ # # self.stack = [] # """ List used to store the stack contents. # :type: list """ # # def push(self, val): # """ # Pushed a value onto the stack. # # :param val: Value to be pushed. # :type val: * # """ # # self.stack = [val] + self.stack # # def pop(self): # """ # Pops a value off the top of the stack. # # :return: Value popped off the stack. # :rtype: * # # :raises StackError: Raised when there is a stack underflow. # """ # # if self.stack: # val = self.stack[0] # self.stack = self.stack[1:] # return val # else: # raise StackError("Stack empty") # # def top(self): # """ # Returns the value off the top of the stack without popping. # # :return: Value on the top of the stack. # :rtype: * # # :raises StackError: Raised when there is a stack underflow. # """ # # if self.stack: # return self.stack[0] # else: # raise StackError("Stack empty") # # def is_empty(self): # """ # Checks if the stack is empty. # # :return: True if the stack is empty, otherwise False. # :rtype: Boolean # """ # # return self.stack == [] # # def __str__(self): # """ # Returns a string representation of the stack. # # @note: This assumes that the stack contents are capable of generating # string representations. # """ # # if len(self.stack) == 0: # s = "[]" # else: # s = "[" + str(self.stack[0]) # for i in range(1, len(self.stack)): # s += ", " + str(self.stack[i]) # s += "]" # return s # # def __repr__(self): # return self.__str__() which might include code, classes, or functions. Output only the next line.
class ExprNode(LEMSBase):
Given the code snippet: <|code_start|> print( "4> op stack: %s, val stack: %s, node stack: %s" % (self.op_stack, self.val_stack, self.node_stack) ) if self.debug: print("<<<<< Depth: %s, returning: %s" % (ExprParser.depth, ret)) ExprParser.depth = ExprParser.depth - 1 if self.debug: print("") return ret def parse(self): """ Tokenizes and parses an arithmetic expression into a parse tree. :return: Returns a token string. :rtype: lems.parser.expr.ExprNode """ # print("Parsing: %s"%self.parse_string) self.tokenize() if self.debug: print("Tokens found: %s" % self.token_list) try: parse_tree = self.parse2() except Exception as e: raise e return parse_tree def parse2(self): <|code_end|> , generate the next line using the imports in this file: from lems.base.base import LEMSBase from lems.base.stack import Stack and context (functions, classes, or occasionally code) from other files: # Path: lems/base/base.py # class LEMSBase(object): # """ # Base object for PyLEMS. # """ # # def copy(self): # return copy.deepcopy(self) # # def toxml(self): # return "" # # Path: lems/base/stack.py # class Stack(LEMSBase): # """ # Basic stack implementation. # """ # # def __init__(self): # """ # Constructor. # """ # # self.stack = [] # """ List used to store the stack contents. # :type: list """ # # def push(self, val): # """ # Pushed a value onto the stack. # # :param val: Value to be pushed. # :type val: * # """ # # self.stack = [val] + self.stack # # def pop(self): # """ # Pops a value off the top of the stack. # # :return: Value popped off the stack. # :rtype: * # # :raises StackError: Raised when there is a stack underflow. # """ # # if self.stack: # val = self.stack[0] # self.stack = self.stack[1:] # return val # else: # raise StackError("Stack empty") # # def top(self): # """ # Returns the value off the top of the stack without popping. # # :return: Value on the top of the stack. # :rtype: * # # :raises StackError: Raised when there is a stack underflow. # """ # # if self.stack: # return self.stack[0] # else: # raise StackError("Stack empty") # # def is_empty(self): # """ # Checks if the stack is empty. # # :return: True if the stack is empty, otherwise False. # :rtype: Boolean # """ # # return self.stack == [] # # def __str__(self): # """ # Returns a string representation of the stack. # # @note: This assumes that the stack contents are capable of generating # string representations. # """ # # if len(self.stack) == 0: # s = "[]" # else: # s = "[" + str(self.stack[0]) # for i in range(1, len(self.stack)): # s += ", " + str(self.stack[i]) # s += "]" # return s # # def __repr__(self): # return self.__str__() . Output only the next line.
self.op_stack = Stack()
Based on the snippet: <|code_start|>""" Structural properties of component types. :author: Gautham Ganapathy :organization: LEMS (https://github.com/organizations/LEMS) """ <|code_end|> , predict the immediate next line with the help of imports: from lems.base.base import LEMSBase from lems.base.map import Map from lems.base.errors import ModelError and context (classes, functions, sometimes code) from other files: # Path: lems/base/base.py # class LEMSBase(object): # """ # Base object for PyLEMS. # """ # # def copy(self): # return copy.deepcopy(self) # # def toxml(self): # return "" # # Path: lems/base/map.py # class Map(dict, LEMSBase): # """ # Map class. # # Same as dict, but iterates over values. # """ # # def __init__(self, *params, **key_params): # """ # Constructor. # """ # # dict.__init__(self, *params, **key_params) # # def __iter__(self): # """ # Returns an iterator. # """ # # return iter(self.values()) # # Path: lems/base/errors.py # class ModelError(LEMSError): # """ # Exception class to signal errors in creating the model. # """ # # pass . Output only the next line.
class With(LEMSBase):
Given the following code snippet before the placeholder: <|code_start|> self.event_connections.append(ec) def toxml(self): """ Exports this object into a LEMS XML object """ chxmlstr = "" for event_connection in self.event_connections: chxmlstr += event_connection.toxml() for for_each in self.for_eachs: chxmlstr += for_each.toxml() return '<ForEach instances="{0}" as="{1}">{2}</ForEach>'.format( self.instances, self.as_, chxmlstr ) class Structure(LEMSBase): """ Stores structural properties of a component type. """ def __init__(self): """ Constructor. """ <|code_end|> , predict the next line using imports from the current file: from lems.base.base import LEMSBase from lems.base.map import Map from lems.base.errors import ModelError and context including class names, function names, and sometimes code from other files: # Path: lems/base/base.py # class LEMSBase(object): # """ # Base object for PyLEMS. # """ # # def copy(self): # return copy.deepcopy(self) # # def toxml(self): # return "" # # Path: lems/base/map.py # class Map(dict, LEMSBase): # """ # Map class. # # Same as dict, but iterates over values. # """ # # def __init__(self, *params, **key_params): # """ # Constructor. # """ # # dict.__init__(self, *params, **key_params) # # def __iter__(self): # """ # Returns an iterator. # """ # # return iter(self.values()) # # Path: lems/base/errors.py # class ModelError(LEMSError): # """ # Exception class to signal errors in creating the model. # """ # # pass . Output only the next line.
self.withs = Map()
Continue the code snippet: <|code_start|> self.assignments = [] """ List of assignments included in MultiInstantiate. :type: list(Assign) """ def __eq__(self, o): if self.component: flag = self.component == o.component and self.number == o.number else: flag = self.component_type == o.component_type and self.number == o.number return flag def add_assign(self, assign): """ Adds an Assign to the structure. :param assign: Assign structure. :type assign: lems.model.structure.Assign """ self.assignments.append(assign) def add(self, child): """ Adds a typed child object to the structure object. :param child: Child object to be added. """ if isinstance(child, Assign): self.add_assign(child) else: <|code_end|> . Use current file imports: from lems.base.base import LEMSBase from lems.base.map import Map from lems.base.errors import ModelError and context (classes, functions, or code) from other files: # Path: lems/base/base.py # class LEMSBase(object): # """ # Base object for PyLEMS. # """ # # def copy(self): # return copy.deepcopy(self) # # def toxml(self): # return "" # # Path: lems/base/map.py # class Map(dict, LEMSBase): # """ # Map class. # # Same as dict, but iterates over values. # """ # # def __init__(self, *params, **key_params): # """ # Constructor. # """ # # dict.__init__(self, *params, **key_params) # # def __iter__(self): # """ # Returns an iterator. # """ # # return iter(self.values()) # # Path: lems/base/errors.py # class ModelError(LEMSError): # """ # Exception class to signal errors in creating the model. # """ # # pass . Output only the next line.
raise ModelError("Unsupported child element")
Given the following code snippet before the placeholder: <|code_start|> DIRECTORIES = [ 'build', 'buildtools', 'mojo', # TODO(kjellander): Remove, see webrtc:5629. 'native_client', 'net', 'testing', 'third_party/binutils', 'third_party/drmemory', 'third_party/instrumented_libraries', 'third_party/libjpeg', 'third_party/libjpeg_turbo', 'third_party/llvm-build', 'third_party/lss', 'third_party/proguard', 'third_party/tcmalloc', 'third_party/yasm', 'third_party/WebKit', # TODO(kjellander): Remove, see webrtc:5629. 'tools/clang', 'tools/gn', 'tools/gyp', 'tools/memory', 'tools/python', 'tools/swarming_client', 'tools/valgrind', 'tools/vim', 'tools/win', ] <|code_end|> , predict the next line using imports from the current file: import ctypes import errno import logging import optparse import os import shelve import shutil import subprocess import sys import textwrap from sync_chromium import get_target_os_list and context including class names, function names, and sometimes code from other files: # Path: sync_chromium.py # def get_target_os_list(): # return ','.join(_parse_gclient_dict().get('target_os', [])) . Output only the next line.
target_os = get_target_os_list()
Here is a snippet: <|code_start|> class EventAdmin(admin.ModelAdmin): list_display = ['title', 'start', 'end', 'slug'] date_hierarchy = 'start' list_filter = ('source',) class SourceAdmin(admin.ModelAdmin): list_display = ['name', 'url', 'is_active'] list_filter = ['is_active'] <|code_end|> . Write the next line using the current file imports: from django.contrib import admin from .models import Event, Source and context from other files: # Path: django_de/events/models.py # class Event(models.Model): # uid = models.CharField(_('UID'), unique=True, max_length=255) # # title = models.CharField(_('Title'), max_length=255) # slug = models.SlugField(verbose_name=_('Slug'), blank=True) # description = models.TextField(_('Description'), blank=True) # location = models.TextField(_('Location'), blank=True) # # start = models.DateTimeField(_('Start')) # end = models.DateTimeField(_('End')) # # url = models.CharField(_('URL'), max_length=255, blank=True) # geolocation = models.CharField(_('GEO Location'), max_length=32, blank=True) # # source = models.ForeignKey('Source', verbose_name=_('Source'), blank=True, null=True) # # def __unicode__(self): # return self.title # # def save(self, *args, **kwargs): # if not self.pk and not self.slug: # self.slug = slugify(self.title[:30]) # # return super(Event, self).save(*args, **kwargs) # # def clean(self): # if self.start > self.end: # raise ValidationError(_('Start date after end date.')) # # class Meta: # verbose_name = _('Event') # verbose_name_plural = _('Events') # ordering = ('start', 'end', 'title') # # class Source(models.Model): # name = models.CharField(_('Name'), max_length=32) # url = models.CharField(_('URL'), max_length=255) # is_active = models.BooleanField(_('Is active?'), default=True) # # def __unicode__(self): # return self.name # # class Meta: # verbose_name = _('Source') # verbose_name_plural = _('Source') , which may include functions, classes, or code. Output only the next line.
admin.site.register(Event, EventAdmin)
Predict the next line after this snippet: <|code_start|> class EventAdmin(admin.ModelAdmin): list_display = ['title', 'start', 'end', 'slug'] date_hierarchy = 'start' list_filter = ('source',) class SourceAdmin(admin.ModelAdmin): list_display = ['name', 'url', 'is_active'] list_filter = ['is_active'] admin.site.register(Event, EventAdmin) <|code_end|> using the current file's imports: from django.contrib import admin from .models import Event, Source and any relevant context from other files: # Path: django_de/events/models.py # class Event(models.Model): # uid = models.CharField(_('UID'), unique=True, max_length=255) # # title = models.CharField(_('Title'), max_length=255) # slug = models.SlugField(verbose_name=_('Slug'), blank=True) # description = models.TextField(_('Description'), blank=True) # location = models.TextField(_('Location'), blank=True) # # start = models.DateTimeField(_('Start')) # end = models.DateTimeField(_('End')) # # url = models.CharField(_('URL'), max_length=255, blank=True) # geolocation = models.CharField(_('GEO Location'), max_length=32, blank=True) # # source = models.ForeignKey('Source', verbose_name=_('Source'), blank=True, null=True) # # def __unicode__(self): # return self.title # # def save(self, *args, **kwargs): # if not self.pk and not self.slug: # self.slug = slugify(self.title[:30]) # # return super(Event, self).save(*args, **kwargs) # # def clean(self): # if self.start > self.end: # raise ValidationError(_('Start date after end date.')) # # class Meta: # verbose_name = _('Event') # verbose_name_plural = _('Events') # ordering = ('start', 'end', 'title') # # class Source(models.Model): # name = models.CharField(_('Name'), max_length=32) # url = models.CharField(_('URL'), max_length=255) # is_active = models.BooleanField(_('Is active?'), default=True) # # def __unicode__(self): # return self.name # # class Meta: # verbose_name = _('Source') # verbose_name_plural = _('Source') . Output only the next line.
admin.site.register(Source, SourceAdmin)
Based on the snippet: <|code_start|> item = models.NewsItem() item.title = ('123456789 123456789 123456789 123456789 123456789 ' '123456789 123456789 123456789 123456789 123456789 ' '123456789 123456789 123456789 123456789') self.assertEquals(item.as_twitter_message(), item.title) item.body = "123" item.author = self.user item.pk = 1 expected = ('123456789 123456789 123456789 123456789 123456789 ' '123456789 123456789 123456789 123456789 123456789 ' '123456789 12... http://example.com/n/1/') self.assertEquals(expected, item.as_twitter_message()) def testToExport(self): a = models.NewsItem(title='a', author=self.user) b = models.NewsItem(title='b', author=self.user) a.save() b.save() self.assertEquals(2, len(models.NewsItem.objects.to_export())) b.twitter_id = '123' b.save() self.assertEquals(1, len(models.NewsItem.objects.to_export())) class NewsItemUrlTests(TestCase): def test_twitter_url(self): item = models.NewsItem() item.twitter_id = 123 self.assertEquals('http://twitter.com/djangode/status/123', <|code_end|> , predict the immediate next line with the help of imports: from django.contrib.auth.models import User from django.test import TestCase from . import models from .templatetags import news_tags and context (classes, functions, sometimes code) from other files: # Path: django_de/news/templatetags/news_tags.py # class ShowNewsToken(template.Node): # def __init__(self, num, tmpl): # def render(self, context): # def do_show_news(parser, token): # def news_url(newsitem): . Output only the next line.
news_tags.news_url(item))
Predict the next line for this snippet: <|code_start|> urlpatterns = patterns('', url(r'^(?:(?P<year>\d{4})/(?:(?P<month>\d{2})/(?:(?P<day>\d{2})/)?)?)?$', news_list, name='news_list'), # url(r'^(?:(?P<year>\d{4})/)?$', news_list, # name='news_list'), <|code_end|> with the help of current file imports: from django.conf.urls import url, patterns from .views import news_list, news_detail and context from other files: # Path: django_de/news/views.py # def news_list(request, year=None, month=None, day=None): # """ # A simple index view that can be restricted to a certain year, year+month or # year+month+day. # """ # query = models.NewsItem.objects # filter_ = Q() # if year is not None: # filter_ &= Q(pub_date__year=int(year)) # if month is not None: # filter_ &= Q(pub_date__month=int(month)) # if day is not None: # filter_ &= Q(pub_date__day=int(day)) # if filter_ is not None: # query = query.filter(filter_) # # return render(request, 'news/list.html', { # 'object_list': query, # 'months': models.NewsItem.objects.dates('pub_date', 'month', # order='DESC'), # }) # # def news_detail(request, pk, slug=None): # """ # Presents a single newsitem. # """ # item = get_object_or_404(models.NewsItem.objects, pk=pk) # # return render(request, 'news/detail.html', { # 'object': item, # }) , which may contain function names, class names, or code. Output only the next line.
url(r'^(?P<slug>.*)-(?P<pk>.*)/$', news_detail, name='news_detail'),
Here is a snippet: <|code_start|>""" zeusproject.testsuite.tests ~~~~~~~~~~~~~~~~~~~~~~ Who tests the tests? :copyright: (c) 2016 by the Lab804 Team. :license: BSD, see LICENSE for more details. """ @pytest.mark.test_module class TestModule(): """Testing Module.""" project_f = os.path.join(os.getcwd(), "tests/ex") print(project_f) <|code_end|> . Write the next line using the current file imports: import os import pytest from zeusproject import commands and context from other files: # Path: zeusproject/commands.py # class CreateFolderException(Exception): # class DuplicateModuleException(Exception): # class DuplicateException(Exception): # class RenameFolder(Exception): # class StructProject: # class Module(StructProject): # class Template(StructProject): # class Project(StructProject): # def __init__(self, name_project, author, domain): # def _clean_name(self, name): # def _adjust_domain(self, domain): # def copy_struct(self): # def random(size=32): # def rename_folder(src, dst): # def write(self, dst, templatef, context, templatefld=None): # def __init__(self, name_project, author, domain): # def ger_std_modules(self): # def _get_modules(self): # def ger_custom(self, name): # def update_app(self, custom_name): # def __init__(self, name_project, author, domain): # def ger_custom(self, name): # def __init__(self, name_project, author, domain): # def _extensions(self): # def _config(self): # def _app(self): # def _manage(self): # def _license(self): # def _readme(self): # def _fabfile(self): # def _uwsgi(self): # def _uwsgi_log_folder(self): # def _config_files(self): # def generate(self): # def get_arguments(): , which may include functions, classes, or code. Output only the next line.
module = commands.Module(name_project=project_f,
Using the snippet: <|code_start|>np.random.seed(1) ## observation points ##################################################################### pos_geo = np.array([[-83.74,42.28,0.0], [-83.08,42.33,0.0], [-83.33,41.94,0.0]]) Nx = len(pos_geo) bm = make_basemap(pos_geo[:,0],pos_geo[:,1]) pos_cart = np.array(bm(pos_geo[:,0],pos_geo[:,1])).T dx = pos_cart[:,0] - pos_cart[0,0] dy = pos_cart[:,1] - pos_cart[0,1] dispdx = np.array([[0.0,1e-6,0.0]]).repeat(Nx,axis=0) dispdy = np.array([[0.0,0.0,0.0]]).repeat(Nx,axis=0) disp = dispdx*dx[:,None] + dispdy*dy[:,None] u,v,z = disp.T dudx,dvdx,dzdx = dispdx.T dudy,dvdy,dzdy = dispdy.T # make disp. time dependent <|code_end|> , determine the next line of code. You have imports: import numpy as np import matplotlib.pyplot as plt from pygeons.mjd import mjd from pygeons.io.io import text_from_dict from pygeons.basemap import make_basemap and context (class names, function names, or code) available: # Path: pygeons/mjd.py # @_memoize # def mjd(s,fmt): # ''' # Converts a date string into Modified Julian Date (MJD) # # Parameters # ---------- # s : string # Date string # # fmt : string # Format string indicating how to parse *s* # # Returns # ------- # out : int # Modified Julian Date # # ''' # d = datetime.strptime(s,fmt) # out = (d - _REFERENCE_DATETIME).days # return out # # Path: pygeons/io/io.py # def _remove_extension(f): # def _unit_string(space_exponent,time_exponent): # def _common_context(data_list): # def pygeons_merge(input_files,output_stem=None): # def pygeons_crop(input_file,start_date=None,stop_date=None, # min_lat=-np.inf,max_lat=np.inf, # min_lon=-np.inf,max_lon=np.inf, # stations=None,output_stem=None): # def pygeons_toh5(input_text_file,file_type='csv',output_stem=None): # def pygeons_totext(input_file,output_stem=None): # def pygeons_info(input_file): # # Path: pygeons/basemap.py # def make_basemap(lon,lat,resolution=None): # ''' # Creates a transverse mercator projection which is centered about the # given positions. # # Modifying this function should be sufficient to change the way that # all map projections are generated in PyGeoNS # ''' # lon = np.asarray(lon) # lat = np.asarray(lat) # n = lon.shape[0] # # the buffer should be the average shortest distance between # # points... but this is good enough # lon_buff = max(0.1,lon.ptp()/np.sqrt(n)) # lat_buff = max(0.1,lat.ptp()/np.sqrt(n)) # llcrnrlon = min(lon) - lon_buff # llcrnrlat = min(lat) - lat_buff # urcrnrlon = max(lon) + lon_buff # urcrnrlat = max(lat) + lat_buff # lon_0 = (llcrnrlon + urcrnrlon)/2.0 # lat_0 = (llcrnrlat + urcrnrlat)/2.0 # return Basemap(projection='tmerc', # resolution=resolution, # lon_0 = lon_0, # lat_0 = lat_0, # llcrnrlon = llcrnrlon, # llcrnrlat = llcrnrlat, # urcrnrlon = urcrnrlon, # urcrnrlat = urcrnrlat) . Output only the next line.
start_time = mjd('2015-07-01','%Y-%m-%d')
Using the snippet: <|code_start|>dzdxdt = dzdx[None,:]*b[:,None] dudydt = dudy[None,:]*b[:,None] dvdydt = dvdy[None,:]*b[:,None] dzdydt = dzdy[None,:]*b[:,None] # add noise su = 0.0005*np.ones((Nt,Nx)) sv = 0.0005*np.ones((Nt,Nx)) sz = 0.0005*np.ones((Nt,Nx)) u += np.random.normal(0.0,su) v += np.random.normal(0.0,sv) z += np.random.normal(0.0,sz) # time evolution ### write synthetic data ##################################################################### data = {} data['id'] = np.array(['A%03d' % i for i in range(Nx)]) data['longitude'] = pos_geo[:,0] data['latitude'] = pos_geo[:,1] data['time'] = times data['east'] = u data['north'] = v data['vertical'] = z data['east_std_dev'] = su data['north_std_dev'] = sv data['vertical_std_dev'] = sz data['time_exponent'] = 0 data['space_exponent'] = 1 <|code_end|> , determine the next line of code. You have imports: import numpy as np import matplotlib.pyplot as plt from pygeons.mjd import mjd from pygeons.io.io import text_from_dict from pygeons.basemap import make_basemap and context (class names, function names, or code) available: # Path: pygeons/mjd.py # @_memoize # def mjd(s,fmt): # ''' # Converts a date string into Modified Julian Date (MJD) # # Parameters # ---------- # s : string # Date string # # fmt : string # Format string indicating how to parse *s* # # Returns # ------- # out : int # Modified Julian Date # # ''' # d = datetime.strptime(s,fmt) # out = (d - _REFERENCE_DATETIME).days # return out # # Path: pygeons/io/io.py # def _remove_extension(f): # def _unit_string(space_exponent,time_exponent): # def _common_context(data_list): # def pygeons_merge(input_files,output_stem=None): # def pygeons_crop(input_file,start_date=None,stop_date=None, # min_lat=-np.inf,max_lat=np.inf, # min_lon=-np.inf,max_lon=np.inf, # stations=None,output_stem=None): # def pygeons_toh5(input_text_file,file_type='csv',output_stem=None): # def pygeons_totext(input_file,output_stem=None): # def pygeons_info(input_file): # # Path: pygeons/basemap.py # def make_basemap(lon,lat,resolution=None): # ''' # Creates a transverse mercator projection which is centered about the # given positions. # # Modifying this function should be sufficient to change the way that # all map projections are generated in PyGeoNS # ''' # lon = np.asarray(lon) # lat = np.asarray(lat) # n = lon.shape[0] # # the buffer should be the average shortest distance between # # points... but this is good enough # lon_buff = max(0.1,lon.ptp()/np.sqrt(n)) # lat_buff = max(0.1,lat.ptp()/np.sqrt(n)) # llcrnrlon = min(lon) - lon_buff # llcrnrlat = min(lat) - lat_buff # urcrnrlon = max(lon) + lon_buff # urcrnrlat = max(lat) + lat_buff # lon_0 = (llcrnrlon + urcrnrlon)/2.0 # lat_0 = (llcrnrlat + urcrnrlat)/2.0 # return Basemap(projection='tmerc', # resolution=resolution, # lon_0 = lon_0, # lat_0 = lat_0, # llcrnrlon = llcrnrlon, # llcrnrlat = llcrnrlat, # urcrnrlon = urcrnrlon, # urcrnrlat = urcrnrlat) . Output only the next line.
text_from_dict('data.csv',data)
Given the code snippet: <|code_start|>np.random.seed(1) ## observation points ##################################################################### pos_geo = np.array([[-83.74,42.28,0.0], [-83.08,42.33,0.0], [-83.33,41.94,0.0]]) Nx = len(pos_geo) <|code_end|> , generate the next line using the imports in this file: import numpy as np import matplotlib.pyplot as plt from pygeons.mjd import mjd from pygeons.io.io import text_from_dict from pygeons.basemap import make_basemap and context (functions, classes, or occasionally code) from other files: # Path: pygeons/mjd.py # @_memoize # def mjd(s,fmt): # ''' # Converts a date string into Modified Julian Date (MJD) # # Parameters # ---------- # s : string # Date string # # fmt : string # Format string indicating how to parse *s* # # Returns # ------- # out : int # Modified Julian Date # # ''' # d = datetime.strptime(s,fmt) # out = (d - _REFERENCE_DATETIME).days # return out # # Path: pygeons/io/io.py # def _remove_extension(f): # def _unit_string(space_exponent,time_exponent): # def _common_context(data_list): # def pygeons_merge(input_files,output_stem=None): # def pygeons_crop(input_file,start_date=None,stop_date=None, # min_lat=-np.inf,max_lat=np.inf, # min_lon=-np.inf,max_lon=np.inf, # stations=None,output_stem=None): # def pygeons_toh5(input_text_file,file_type='csv',output_stem=None): # def pygeons_totext(input_file,output_stem=None): # def pygeons_info(input_file): # # Path: pygeons/basemap.py # def make_basemap(lon,lat,resolution=None): # ''' # Creates a transverse mercator projection which is centered about the # given positions. # # Modifying this function should be sufficient to change the way that # all map projections are generated in PyGeoNS # ''' # lon = np.asarray(lon) # lat = np.asarray(lat) # n = lon.shape[0] # # the buffer should be the average shortest distance between # # points... but this is good enough # lon_buff = max(0.1,lon.ptp()/np.sqrt(n)) # lat_buff = max(0.1,lat.ptp()/np.sqrt(n)) # llcrnrlon = min(lon) - lon_buff # llcrnrlat = min(lat) - lat_buff # urcrnrlon = max(lon) + lon_buff # urcrnrlat = max(lat) + lat_buff # lon_0 = (llcrnrlon + urcrnrlon)/2.0 # lat_0 = (llcrnrlat + urcrnrlat)/2.0 # return Basemap(projection='tmerc', # resolution=resolution, # lon_0 = lon_0, # lat_0 = lat_0, # llcrnrlon = llcrnrlon, # llcrnrlat = llcrnrlat, # urcrnrlon = urcrnrlon, # urcrnrlat = urcrnrlat) . Output only the next line.
bm = make_basemap(pos_geo[:,0],pos_geo[:,1])
Next line prediction: <|code_start|> def check_unique_stations(data): ''' makes sure each station id is unique ''' unique_ids = list(set(data['id'])) if len(data['id']) != len(unique_ids): # there are duplicate stations, now find them duplicates = [] for i in unique_ids: if sum(data['id'] == i) > 1: duplicates += [i] duplicates = ', '.join(duplicates) raise DataError( 'Dataset contains the following duplicate station IDs : %s ' % duplicates) def check_unique_dates(data): ''' makes sure each date is unique ''' unique_days = list(set(data['time'])) if len(data['time']) != len(unique_days): # there are duplicate dates, now find them duplicates = [] for i in unique_days: if sum(data['time'] == i) > 1: <|code_end|> . Use current file imports: (import numpy as np import logging from pygeons.mjd import mjd_inv) and context including class names, function names, or small code snippets from other files: # Path: pygeons/mjd.py # @_memoize # def mjd_inv(m,fmt): # ''' # Converts Modified Julian Date (MJD) to a date string # # Parameters # ---------- # m : int # Modified Julian Date # # fmt : string # format string indicating how to form *out* # # Returns # ------- # out : str # Date string # # ''' # m = int(m) # d = _REFERENCE_DATETIME + timedelta(m) # out = d.strftime(fmt) # return out . Output only the next line.
duplicates += [mjd_inv(i,'%Y-%m-%d')]
Given the code snippet: <|code_start|># This script generates the synthetic data file data.csv np.random.seed(1) def make_data(pos,times): ''' 1 microstrain per year = 3 * 10^-9 strain per day ''' ms = 2.737e-9 x,y = pos.T _,xg = np.meshgrid(times,x,indexing='ij') tg,yg = np.meshgrid(times,y,indexing='ij') u = 0.0*ms*tg*xg + 0.0*ms*tg*yg v = 0.0*ms*tg*xg + 3.0*ms*tg*yg z = 0.0*tg u = u - u[0,:] v = v - v[0,:] z = z - z[0,:] return u,v,z lon = np.array([-83.3,-82.75,-85.26,-83.36]) lat = np.array([42.31,42.91,45.20,42.92]) id = np.array(['STA1','STA2','STA3','STA4']) <|code_end|> , generate the next line using the imports in this file: import numpy as np from pygeons.basemap import make_basemap from pygeons.mjd import mjd from pygeons.io.convert import text_from_dict and context (functions, classes, or occasionally code) from other files: # Path: pygeons/basemap.py # def make_basemap(lon,lat,resolution=None): # ''' # Creates a transverse mercator projection which is centered about the # given positions. # # Modifying this function should be sufficient to change the way that # all map projections are generated in PyGeoNS # ''' # lon = np.asarray(lon) # lat = np.asarray(lat) # n = lon.shape[0] # # the buffer should be the average shortest distance between # # points... but this is good enough # lon_buff = max(0.1,lon.ptp()/np.sqrt(n)) # lat_buff = max(0.1,lat.ptp()/np.sqrt(n)) # llcrnrlon = min(lon) - lon_buff # llcrnrlat = min(lat) - lat_buff # urcrnrlon = max(lon) + lon_buff # urcrnrlat = max(lat) + lat_buff # lon_0 = (llcrnrlon + urcrnrlon)/2.0 # lat_0 = (llcrnrlat + urcrnrlat)/2.0 # return Basemap(projection='tmerc', # resolution=resolution, # lon_0 = lon_0, # lat_0 = lat_0, # llcrnrlon = llcrnrlon, # llcrnrlat = llcrnrlat, # urcrnrlon = urcrnrlon, # urcrnrlat = urcrnrlat) # # Path: pygeons/mjd.py # @_memoize # def mjd(s,fmt): # ''' # Converts a date string into Modified Julian Date (MJD) # # Parameters # ---------- # s : string # Date string # # fmt : string # Format string indicating how to parse *s* # # Returns # ------- # out : int # Modified Julian Date # # ''' # d = datetime.strptime(s,fmt) # out = (d - _REFERENCE_DATETIME).days # return out # # Path: pygeons/io/convert.py # def text_from_dict(outfile,data): # ''' # Writes a text file from a data dictionary. The text file contains a # csv string for each station separated by "***". # # Parameters # ---------- # outfile : string # Name of the output text file # # data : dict # Data dictionary # # ''' # check_data(data) # Nx = len(data['id']) # strs = [] # for i in range(Nx): # # create a subdictionary for each station # dict_i = {} # mask = (np.isinf(data['north_std_dev'][:,i]) & # np.isinf(data['east_std_dev'][:,i]) & # np.isinf(data['vertical_std_dev'][:,i])) # # do not write data for this station if the station has no data # if np.all(mask): # continue # # dict_i['id'] = data['id'][i] # dict_i['longitude'] = data['longitude'][i] # dict_i['latitude'] = data['latitude'][i] # dict_i['time'] = data['time'][~mask] # dict_i['east'] = data['east'][~mask,i] # dict_i['north'] = data['north'][~mask,i] # dict_i['vertical'] = data['vertical'][~mask,i] # dict_i['east_std_dev'] = data['east_std_dev'][~mask,i] # dict_i['north_std_dev'] = data['north_std_dev'][~mask,i] # dict_i['vertical_std_dev'] = data['vertical_std_dev'][~mask,i] # dict_i['time_exponent'] = data['time_exponent'] # dict_i['space_exponent'] = data['space_exponent'] # strs += [_write_csv(dict_i)] # # out = '***\n'.join(strs) # fout = open(outfile,'w') # fout.write(out) # fout.close() # return . Output only the next line.
bm = make_basemap(lon,lat)
Predict the next line after this snippet: <|code_start|># This script generates the synthetic data file data.csv np.random.seed(1) def make_data(pos,times): ''' 1 microstrain per year = 3 * 10^-9 strain per day ''' ms = 2.737e-9 x,y = pos.T _,xg = np.meshgrid(times,x,indexing='ij') tg,yg = np.meshgrid(times,y,indexing='ij') u = 0.0*ms*tg*xg + 0.0*ms*tg*yg v = 0.0*ms*tg*xg + 3.0*ms*tg*yg z = 0.0*tg u = u - u[0,:] v = v - v[0,:] z = z - z[0,:] return u,v,z lon = np.array([-83.3,-82.75,-85.26,-83.36]) lat = np.array([42.31,42.91,45.20,42.92]) id = np.array(['STA1','STA2','STA3','STA4']) bm = make_basemap(lon,lat) x,y = bm(lon,lat) xy = np.array([x,y]).T <|code_end|> using the current file's imports: import numpy as np from pygeons.basemap import make_basemap from pygeons.mjd import mjd from pygeons.io.convert import text_from_dict and any relevant context from other files: # Path: pygeons/basemap.py # def make_basemap(lon,lat,resolution=None): # ''' # Creates a transverse mercator projection which is centered about the # given positions. # # Modifying this function should be sufficient to change the way that # all map projections are generated in PyGeoNS # ''' # lon = np.asarray(lon) # lat = np.asarray(lat) # n = lon.shape[0] # # the buffer should be the average shortest distance between # # points... but this is good enough # lon_buff = max(0.1,lon.ptp()/np.sqrt(n)) # lat_buff = max(0.1,lat.ptp()/np.sqrt(n)) # llcrnrlon = min(lon) - lon_buff # llcrnrlat = min(lat) - lat_buff # urcrnrlon = max(lon) + lon_buff # urcrnrlat = max(lat) + lat_buff # lon_0 = (llcrnrlon + urcrnrlon)/2.0 # lat_0 = (llcrnrlat + urcrnrlat)/2.0 # return Basemap(projection='tmerc', # resolution=resolution, # lon_0 = lon_0, # lat_0 = lat_0, # llcrnrlon = llcrnrlon, # llcrnrlat = llcrnrlat, # urcrnrlon = urcrnrlon, # urcrnrlat = urcrnrlat) # # Path: pygeons/mjd.py # @_memoize # def mjd(s,fmt): # ''' # Converts a date string into Modified Julian Date (MJD) # # Parameters # ---------- # s : string # Date string # # fmt : string # Format string indicating how to parse *s* # # Returns # ------- # out : int # Modified Julian Date # # ''' # d = datetime.strptime(s,fmt) # out = (d - _REFERENCE_DATETIME).days # return out # # Path: pygeons/io/convert.py # def text_from_dict(outfile,data): # ''' # Writes a text file from a data dictionary. The text file contains a # csv string for each station separated by "***". # # Parameters # ---------- # outfile : string # Name of the output text file # # data : dict # Data dictionary # # ''' # check_data(data) # Nx = len(data['id']) # strs = [] # for i in range(Nx): # # create a subdictionary for each station # dict_i = {} # mask = (np.isinf(data['north_std_dev'][:,i]) & # np.isinf(data['east_std_dev'][:,i]) & # np.isinf(data['vertical_std_dev'][:,i])) # # do not write data for this station if the station has no data # if np.all(mask): # continue # # dict_i['id'] = data['id'][i] # dict_i['longitude'] = data['longitude'][i] # dict_i['latitude'] = data['latitude'][i] # dict_i['time'] = data['time'][~mask] # dict_i['east'] = data['east'][~mask,i] # dict_i['north'] = data['north'][~mask,i] # dict_i['vertical'] = data['vertical'][~mask,i] # dict_i['east_std_dev'] = data['east_std_dev'][~mask,i] # dict_i['north_std_dev'] = data['north_std_dev'][~mask,i] # dict_i['vertical_std_dev'] = data['vertical_std_dev'][~mask,i] # dict_i['time_exponent'] = data['time_exponent'] # dict_i['space_exponent'] = data['space_exponent'] # strs += [_write_csv(dict_i)] # # out = '***\n'.join(strs) # fout = open(outfile,'w') # fout.write(out) # fout.close() # return . Output only the next line.
start_date = mjd('2000-01-01','%Y-%m-%d')
Continue the code snippet: <|code_start|>lon = np.array([-83.3,-82.75,-85.26,-83.36]) lat = np.array([42.31,42.91,45.20,42.92]) id = np.array(['STA1','STA2','STA3','STA4']) bm = make_basemap(lon,lat) x,y = bm(lon,lat) xy = np.array([x,y]).T start_date = mjd('2000-01-01','%Y-%m-%d') stop_date = mjd('2000-02-01','%Y-%m-%d') times = np.arange(start_date,stop_date+1) u,v,z = make_data(xy,times) su = 0.001*np.ones_like(u) sv = 0.001*np.ones_like(v) sz = 0.001*np.ones_like(z) u += np.random.normal(0.0,su) v += np.random.normal(0.0,sv) z += np.random.normal(0.0,sz) data = {} data['id'] = id data['longitude'] = lon data['latitude'] = lat data['time'] = times data['east'] = u data['north'] = v data['vertical'] = z data['east_std_dev'] = su data['north_std_dev'] = sv data['vertical_std_dev'] = sv data['time_exponent'] = 0 data['space_exponent'] = 1 <|code_end|> . Use current file imports: import numpy as np from pygeons.basemap import make_basemap from pygeons.mjd import mjd from pygeons.io.convert import text_from_dict and context (classes, functions, or code) from other files: # Path: pygeons/basemap.py # def make_basemap(lon,lat,resolution=None): # ''' # Creates a transverse mercator projection which is centered about the # given positions. # # Modifying this function should be sufficient to change the way that # all map projections are generated in PyGeoNS # ''' # lon = np.asarray(lon) # lat = np.asarray(lat) # n = lon.shape[0] # # the buffer should be the average shortest distance between # # points... but this is good enough # lon_buff = max(0.1,lon.ptp()/np.sqrt(n)) # lat_buff = max(0.1,lat.ptp()/np.sqrt(n)) # llcrnrlon = min(lon) - lon_buff # llcrnrlat = min(lat) - lat_buff # urcrnrlon = max(lon) + lon_buff # urcrnrlat = max(lat) + lat_buff # lon_0 = (llcrnrlon + urcrnrlon)/2.0 # lat_0 = (llcrnrlat + urcrnrlat)/2.0 # return Basemap(projection='tmerc', # resolution=resolution, # lon_0 = lon_0, # lat_0 = lat_0, # llcrnrlon = llcrnrlon, # llcrnrlat = llcrnrlat, # urcrnrlon = urcrnrlon, # urcrnrlat = urcrnrlat) # # Path: pygeons/mjd.py # @_memoize # def mjd(s,fmt): # ''' # Converts a date string into Modified Julian Date (MJD) # # Parameters # ---------- # s : string # Date string # # fmt : string # Format string indicating how to parse *s* # # Returns # ------- # out : int # Modified Julian Date # # ''' # d = datetime.strptime(s,fmt) # out = (d - _REFERENCE_DATETIME).days # return out # # Path: pygeons/io/convert.py # def text_from_dict(outfile,data): # ''' # Writes a text file from a data dictionary. The text file contains a # csv string for each station separated by "***". # # Parameters # ---------- # outfile : string # Name of the output text file # # data : dict # Data dictionary # # ''' # check_data(data) # Nx = len(data['id']) # strs = [] # for i in range(Nx): # # create a subdictionary for each station # dict_i = {} # mask = (np.isinf(data['north_std_dev'][:,i]) & # np.isinf(data['east_std_dev'][:,i]) & # np.isinf(data['vertical_std_dev'][:,i])) # # do not write data for this station if the station has no data # if np.all(mask): # continue # # dict_i['id'] = data['id'][i] # dict_i['longitude'] = data['longitude'][i] # dict_i['latitude'] = data['latitude'][i] # dict_i['time'] = data['time'][~mask] # dict_i['east'] = data['east'][~mask,i] # dict_i['north'] = data['north'][~mask,i] # dict_i['vertical'] = data['vertical'][~mask,i] # dict_i['east_std_dev'] = data['east_std_dev'][~mask,i] # dict_i['north_std_dev'] = data['north_std_dev'][~mask,i] # dict_i['vertical_std_dev'] = data['vertical_std_dev'][~mask,i] # dict_i['time_exponent'] = data['time_exponent'] # dict_i['space_exponent'] = data['space_exponent'] # strs += [_write_csv(dict_i)] # # out = '***\n'.join(strs) # fout = open(outfile,'w') # fout.write(out) # fout.close() # return . Output only the next line.
text_from_dict('data.csv',data)
Given snippet: <|code_start|> # CALL THIS AFTER *_init_image* # if len(self.data_sets) < 2: self.scatter = None return sm = ScalarMappable(norm=self.cbar.norm,cmap=self.cbar.get_cmap()) # use scatter points to show z for second data set colors = sm.to_rgba(self.data_sets[1][self.tidx,:,2]) self.scatter = self.map_ax.scatter(self.x[:,0],self.x[:,1], c=colors,s=self.scatter_size, zorder=2,edgecolor=self.colors[1]) def _update_scatter(self): # Updates the scatter points for changes in *tidx* or *xidx*. This # just changes the face color # # CALL THIS AFTER *_update_image* # if len(self.data_sets) < 2: return sm = ScalarMappable(norm=self.cbar.norm,cmap=self.cbar.get_cmap()) colors = sm.to_rgba(self.data_sets[1][self.tidx,:,2]) self.scatter.set_facecolors(colors) def _init_quiver(self): # Initially plots the horizontal deformation vectors and a key self.quiver = [] for si in range(len(self.data_sets)): <|code_end|> , continue by predicting the next line. Consider current file imports: import matplotlib.pyplot as plt import numpy as np import logging import sys import scipy.interpolate from pygeons.plot.quiver import Quiver from matplotlib.cm import ScalarMappable from matplotlib.colors import ListedColormap from code import InteractiveConsole from scipy.spatial import cKDTree from textwrap import wrap from PyQt4.QtCore import pyqtRemoveInputHook, pyqtRestoreInputHook from PyQt5.QtCore import pyqtRemoveInputHook, pyqtRestoreInputHook and context: # Path: pygeons/plot/quiver.py # class Quiver(_Quiver): # def __init__(self,ax,*args,**kwargs): # if 'sigma' in kwargs: # scale_units = kwargs.get('scale_units','xy') # kwargs['scale_units'] = scale_units # if kwargs['scale_units'] != 'xy': # raise ValueError('scale units must be "xy" when sigma is given') # # angles = kwargs.get('angles','xy') # kwargs['angles'] = angles # if kwargs['angles'] != 'xy': # raise ValueError('angles must be "xy" when sigma is given') # # sigma = kwargs.pop('sigma',None) # # ellipse_kwargs = kwargs.pop('ellipse_kwargs',{}) # if 'offsets' in ellipse_kwargs: # raise ValueError('cannot specify ellipse offsets') # if 'units' in ellipse_kwargs: # raise ValueError('cannot specify ellipse units') # # self.ellipse_kwargs = {'edgecolors':'k', # 'facecolors':'none', # 'linewidths':1.0} # self.ellipse_kwargs.update(ellipse_kwargs) # # self.ellipsoids = None # # _Quiver.__init__(self,ax,*args,**kwargs) # # if sigma is not None: # if self.scale is None: # self.scale = _estimate_scale(self.X,self.Y,self.U,self.V) # # su,sv,rho = sigma[0],sigma[1],sigma[2] # self._update_ellipsoids(su,sv,rho) # # # def _update_ellipsoids(self,su,sv,rho): # self.scale_units = 'xy' # self.angles = 'xy' # tips_x = self.X + self.U/self.scale # tips_y = self.Y + self.V/self.scale # tips = np.array([tips_x,tips_y]).transpose() # a,b,angle = compute_abphi(su,sv,rho) # width = 2.0*a/self.scale # height = 2.0*b/self.scale # if self.ellipsoids is not None: # self.ellipsoids.remove() # # # do not draw ellipses which are too small # too_small = 0.001 # length = np.sqrt((self.U/self.scale)**2 + (self.V/self.scale)**2) # with warnings.catch_warnings(): # # do not print out zero division warning # warnings.simplefilter("ignore") # is_not_too_small = ((np.nan_to_num(width/length) > too_small) | # (np.nan_to_num(height/length) > too_small)) # # width = width[is_not_too_small] # height = height[is_not_too_small] # angle = angle[is_not_too_small] # tips = tips[is_not_too_small] # # # dont add ellipses if there are no ellipses to add # if any(is_not_too_small): # self.ellipsoids = EllipseCollection(width,height,angle, # units=self.scale_units, # offsets = tips, # transOffset=self.ax.transData, # **self.ellipse_kwargs) # # self.ax.add_collection(self.ellipsoids) # # else: # self.ellipsoids = None # # def set_UVC(self,u,v,C=None,sigma=None): # if C is None: # _Quiver.set_UVC(self,u,v) # else: # _Quiver.set_UVC(self,u,v,C) # # if sigma is not None: # su,sv,rho = sigma[0],sigma[1],sigma[2] # self._update_ellipsoids(su,sv,rho) # # def remove(self): # # remove the quiver and ellipsoid collection # _Quiver.remove(self) # if self.ellipsoids is not None: # self.ellipsoids.remove() which might include code, classes, or functions. Output only the next line.
q = Quiver(self.map_ax,self.x[:,0],self.x[:,1],
Continue the code snippet: <|code_start|>def mat32(sigma,cls): ''' Matern covariance function with nu=3/2 ''' return gauss.gpiso(rbf.basis.mat32,(0.0,sigma**2,cls),dim=2) def mat52(sigma,cls): ''' Matern space covariance function with nu=5/2 ''' return gauss.gpiso(rbf.basis.mat52,(0.0,sigma**2,cls),dim=2) def wen32(sigma,cls): ''' Wendland space covariance function ''' return gauss.gpiso(rbf.basis.wen32,(0.0,sigma**2,cls),dim=2) def spwen32(sigma,cls): ''' Sparse Wendland space covariance function ''' return gauss.gpiso(rbf.basis.spwen32,(0.0,sigma**2,cls),dim=2) # 3D GaussianProcess constructors ##################################################################### <|code_end|> . Use current file imports: import rbf.basis import rbf.poly from rbf import gauss from pygeons.main.gptools import set_units,kernel_product from pygeons.main import gpstation and context (classes, functions, or code) from other files: # Path: pygeons/main/gptools.py # def set_units(units): # ''' # Wrapper for Gaussian process constructors which sets the # hyperparameter units. When a wrapped constructor is called, the # hyperparameters are converted to be in terms of *m* and *day*. The # constructor is also given the key word argument *convert*, which can # be set to False if no conversion is desired. # ''' # def decorator(fin): # def fout(*args,**kwargs): # convert = kwargs.pop('convert',True) # if convert: # args = [a*conv(u,time='day',space='m') for a,u in zip(args,units)] # # return fin(*args) # # fout.units = units # fout.nargs = get_arg_count(fin) # fout.__doc__ = fin.__doc__ # fout.__name__ = fin.__name__ # if fout.nargs != len(fout.units): # raise ValueError( # 'the number of arguments must be equal to the number of unit ' # 'specifications') # # return fout # # return decorator # # def kernel_product(gp1,gp2): # ''' # Returns a GaussianProcess with zero mean and covariance that is the # product of the two inputs. The first GP must be 1D and the second # must be 2D. # ''' # def mean(x,diff): # return np.zeros(x.shape[0]) # # def covariance(x1,x2,diff1,diff2): # cov1 = gp1._covariance(x1[:,[0]],x2[:,[0]], # diff1[[0]],diff2[[0]]) # cov2 = gp2._covariance(x1[:,[1,2]],x2[:,[1,2]], # diff1[[1,2]],diff2[[1,2]]) # # There are two conditions to consider: (1) cov1 and cov2 are # # dense, and (2) at least one of the matrices is sparse. If (1) # # then use *np.multiply* for element-wise multiplication. If (2) # # then use the *multiply* method of the sparse matrix. # if (not sp.issparse(cov1)) & (not sp.issparse(cov2)): # # both are dense. The output will be a dense array # out = np.multiply(cov1,cov2) # # else: # # at least one is sparse. THe output will be a sparse array # if sp.issparse(cov1): # out = cov1.multiply(cov2).tocsc() # else: # # cov2 is sparse # out = cov2.multiply(cov1).tocsc() # # return out # # return GaussianProcess(mean,covariance,dim=3) # # Path: pygeons/main/gpstation.py # def const(): # def basis(x,diff): # def linear(): # def basis(x,diff): # def per(): # def basis(x): # def step(t0): # def basis(x,diff): # def mat32(sigma,cts): # def mat52(sigma,cts): # def wen11(sigma,cts): # def wen12(sigma,cts): # def wen30(sigma,cts): # def spwen11(sigma,cts): # def spwen12(sigma,cts): # def spwen30(sigma,cts): # def se(sigma,cts): # def exp(sigma,cts): # def fogm(sigma,w): # def bm(sigma,t0): # def mean(x): # def cov(x1,x2): # def ibm(sigma,t0): # def mean(x,diff): # def cov(x1,x2,diff1,diff2): # CONSTRUCTORS = {'const':const, # 'linear':linear, # 'per':per, # 'step':step, # 'bm':bm, # 'ibm':ibm, # 'fogm':fogm, # 'mat32':mat32, # 'mat52':mat52, # 'wen11':wen11, # 'wen12':wen12, # 'wen30':wen30, # 'spwen11':spwen11, # 'spwen12':spwen12, # 'spwen30':spwen30, # 'se':se, # 'exp':exp} . Output only the next line.
@set_units(['mm','yr','km'])
Continue the code snippet: <|code_start|> def wen32(sigma,cls): ''' Wendland space covariance function ''' return gauss.gpiso(rbf.basis.wen32,(0.0,sigma**2,cls),dim=2) def spwen32(sigma,cls): ''' Sparse Wendland space covariance function ''' return gauss.gpiso(rbf.basis.spwen32,(0.0,sigma**2,cls),dim=2) # 3D GaussianProcess constructors ##################################################################### @set_units(['mm','yr','km']) def se_se(sigma,cts,cls): ''' Squared exponential for temporal and spatial covariance. Parameters ---------- sigma [mm] : Standard deviation of displacements cts [yr] : Characteristic time-scale cls [km] : Characteristic length-scale ''' tgp = gpstation.se(sigma,cts,convert=False) sgp = se(1.0,cls) <|code_end|> . Use current file imports: import rbf.basis import rbf.poly from rbf import gauss from pygeons.main.gptools import set_units,kernel_product from pygeons.main import gpstation and context (classes, functions, or code) from other files: # Path: pygeons/main/gptools.py # def set_units(units): # ''' # Wrapper for Gaussian process constructors which sets the # hyperparameter units. When a wrapped constructor is called, the # hyperparameters are converted to be in terms of *m* and *day*. The # constructor is also given the key word argument *convert*, which can # be set to False if no conversion is desired. # ''' # def decorator(fin): # def fout(*args,**kwargs): # convert = kwargs.pop('convert',True) # if convert: # args = [a*conv(u,time='day',space='m') for a,u in zip(args,units)] # # return fin(*args) # # fout.units = units # fout.nargs = get_arg_count(fin) # fout.__doc__ = fin.__doc__ # fout.__name__ = fin.__name__ # if fout.nargs != len(fout.units): # raise ValueError( # 'the number of arguments must be equal to the number of unit ' # 'specifications') # # return fout # # return decorator # # def kernel_product(gp1,gp2): # ''' # Returns a GaussianProcess with zero mean and covariance that is the # product of the two inputs. The first GP must be 1D and the second # must be 2D. # ''' # def mean(x,diff): # return np.zeros(x.shape[0]) # # def covariance(x1,x2,diff1,diff2): # cov1 = gp1._covariance(x1[:,[0]],x2[:,[0]], # diff1[[0]],diff2[[0]]) # cov2 = gp2._covariance(x1[:,[1,2]],x2[:,[1,2]], # diff1[[1,2]],diff2[[1,2]]) # # There are two conditions to consider: (1) cov1 and cov2 are # # dense, and (2) at least one of the matrices is sparse. If (1) # # then use *np.multiply* for element-wise multiplication. If (2) # # then use the *multiply* method of the sparse matrix. # if (not sp.issparse(cov1)) & (not sp.issparse(cov2)): # # both are dense. The output will be a dense array # out = np.multiply(cov1,cov2) # # else: # # at least one is sparse. THe output will be a sparse array # if sp.issparse(cov1): # out = cov1.multiply(cov2).tocsc() # else: # # cov2 is sparse # out = cov2.multiply(cov1).tocsc() # # return out # # return GaussianProcess(mean,covariance,dim=3) # # Path: pygeons/main/gpstation.py # def const(): # def basis(x,diff): # def linear(): # def basis(x,diff): # def per(): # def basis(x): # def step(t0): # def basis(x,diff): # def mat32(sigma,cts): # def mat52(sigma,cts): # def wen11(sigma,cts): # def wen12(sigma,cts): # def wen30(sigma,cts): # def spwen11(sigma,cts): # def spwen12(sigma,cts): # def spwen30(sigma,cts): # def se(sigma,cts): # def exp(sigma,cts): # def fogm(sigma,w): # def bm(sigma,t0): # def mean(x): # def cov(x1,x2): # def ibm(sigma,t0): # def mean(x,diff): # def cov(x1,x2,diff1,diff2): # CONSTRUCTORS = {'const':const, # 'linear':linear, # 'per':per, # 'step':step, # 'bm':bm, # 'ibm':ibm, # 'fogm':fogm, # 'mat32':mat32, # 'mat52':mat52, # 'wen11':wen11, # 'wen12':wen12, # 'wen30':wen30, # 'spwen11':spwen11, # 'spwen12':spwen12, # 'spwen30':spwen30, # 'se':se, # 'exp':exp} . Output only the next line.
return kernel_product(tgp,sgp)
Given the code snippet: <|code_start|> return gauss.gpiso(rbf.basis.mat52,(0.0,sigma**2,cls),dim=2) def wen32(sigma,cls): ''' Wendland space covariance function ''' return gauss.gpiso(rbf.basis.wen32,(0.0,sigma**2,cls),dim=2) def spwen32(sigma,cls): ''' Sparse Wendland space covariance function ''' return gauss.gpiso(rbf.basis.spwen32,(0.0,sigma**2,cls),dim=2) # 3D GaussianProcess constructors ##################################################################### @set_units(['mm','yr','km']) def se_se(sigma,cts,cls): ''' Squared exponential for temporal and spatial covariance. Parameters ---------- sigma [mm] : Standard deviation of displacements cts [yr] : Characteristic time-scale cls [km] : Characteristic length-scale ''' <|code_end|> , generate the next line using the imports in this file: import rbf.basis import rbf.poly from rbf import gauss from pygeons.main.gptools import set_units,kernel_product from pygeons.main import gpstation and context (functions, classes, or occasionally code) from other files: # Path: pygeons/main/gptools.py # def set_units(units): # ''' # Wrapper for Gaussian process constructors which sets the # hyperparameter units. When a wrapped constructor is called, the # hyperparameters are converted to be in terms of *m* and *day*. The # constructor is also given the key word argument *convert*, which can # be set to False if no conversion is desired. # ''' # def decorator(fin): # def fout(*args,**kwargs): # convert = kwargs.pop('convert',True) # if convert: # args = [a*conv(u,time='day',space='m') for a,u in zip(args,units)] # # return fin(*args) # # fout.units = units # fout.nargs = get_arg_count(fin) # fout.__doc__ = fin.__doc__ # fout.__name__ = fin.__name__ # if fout.nargs != len(fout.units): # raise ValueError( # 'the number of arguments must be equal to the number of unit ' # 'specifications') # # return fout # # return decorator # # def kernel_product(gp1,gp2): # ''' # Returns a GaussianProcess with zero mean and covariance that is the # product of the two inputs. The first GP must be 1D and the second # must be 2D. # ''' # def mean(x,diff): # return np.zeros(x.shape[0]) # # def covariance(x1,x2,diff1,diff2): # cov1 = gp1._covariance(x1[:,[0]],x2[:,[0]], # diff1[[0]],diff2[[0]]) # cov2 = gp2._covariance(x1[:,[1,2]],x2[:,[1,2]], # diff1[[1,2]],diff2[[1,2]]) # # There are two conditions to consider: (1) cov1 and cov2 are # # dense, and (2) at least one of the matrices is sparse. If (1) # # then use *np.multiply* for element-wise multiplication. If (2) # # then use the *multiply* method of the sparse matrix. # if (not sp.issparse(cov1)) & (not sp.issparse(cov2)): # # both are dense. The output will be a dense array # out = np.multiply(cov1,cov2) # # else: # # at least one is sparse. THe output will be a sparse array # if sp.issparse(cov1): # out = cov1.multiply(cov2).tocsc() # else: # # cov2 is sparse # out = cov2.multiply(cov1).tocsc() # # return out # # return GaussianProcess(mean,covariance,dim=3) # # Path: pygeons/main/gpstation.py # def const(): # def basis(x,diff): # def linear(): # def basis(x,diff): # def per(): # def basis(x): # def step(t0): # def basis(x,diff): # def mat32(sigma,cts): # def mat52(sigma,cts): # def wen11(sigma,cts): # def wen12(sigma,cts): # def wen30(sigma,cts): # def spwen11(sigma,cts): # def spwen12(sigma,cts): # def spwen30(sigma,cts): # def se(sigma,cts): # def exp(sigma,cts): # def fogm(sigma,w): # def bm(sigma,t0): # def mean(x): # def cov(x1,x2): # def ibm(sigma,t0): # def mean(x,diff): # def cov(x1,x2,diff1,diff2): # CONSTRUCTORS = {'const':const, # 'linear':linear, # 'per':per, # 'step':step, # 'bm':bm, # 'ibm':ibm, # 'fogm':fogm, # 'mat32':mat32, # 'mat52':mat52, # 'wen11':wen11, # 'wen12':wen12, # 'wen30':wen30, # 'spwen11':spwen11, # 'spwen12':spwen12, # 'spwen30':spwen30, # 'se':se, # 'exp':exp} . Output only the next line.
tgp = gpstation.se(sigma,cts,convert=False)
Next line prediction: <|code_start|> # matrix dense out = np.zeros((N1,N2)) out[rows,cols] = data else: # otherwise make it csc sparse out = sp.csc_matrix((data,(rows,cols)),(N1,N2),dtype=float) if N1 > chunk_size: logger.debug( 'Building covariance matrix (chunk size = %s) : 100.0%% ' 'complete' % chunk_size) return out return cov_out def set_units(units): ''' Wrapper for Gaussian process constructors which sets the hyperparameter units. When a wrapped constructor is called, the hyperparameters are converted to be in terms of *m* and *day*. The constructor is also given the key word argument *convert*, which can be set to False if no conversion is desired. ''' def decorator(fin): def fout(*args,**kwargs): convert = kwargs.pop('convert',True) if convert: <|code_end|> . Use current file imports: (import numpy as np import scipy.sparse as sp import logging from rbf.utils import get_arg_count from rbf.gauss import (GaussianProcess, _zero_mean, _zero_covariance, _empty_basis) from pygeons.units import unit_conversion as conv) and context including class names, function names, or small code snippets from other files: # Path: pygeons/units.py # def unit_conversion(units,time='day',space='m'): # ''' # Returns a factors that converts data with units of *units* (e.g. # km/hr) to units that are in terms of *time* and *space*. # # Example # ------- # >>> unit_conversion('mm/yr',time='day',space='m') # 2.73785078713e-06 # # ''' # # replace carets with two asterisks # units = units.replace('^','**') # # converts to m # to_m = {'mm':1e-3, # 'cm':1e-2, # 'm':1e0, # 'km':1e3} # # converts to seconds # to_s = {'s':1.0, # 'min':60.0, # 'hr':60.0*60.0, # 'day':24.0*60.0*60.0, # 'mjd':24.0*60.0*60.0, # 'yr':365.25*24.0*60.0*60.0} # # converts to user-specified space units and time units # conv = dict([(k,v/to_m[space]) for k,v in to_m.iteritems()] + # [(k,v/to_s[time]) for k,v in to_s.iteritems()]) # out = eval(units,conv) # return out . Output only the next line.
args = [a*conv(u,time='day',space='m') for a,u in zip(args,units)]
Using the snippet: <|code_start|>''' Module for converting between hdf5 files, text files and data dictionaries. ''' logger = logging.getLogger(__name__) ## Write files from DataDict instances ##################################################################### def _write_csv(data): ''' Write data for a single station to a csv file ''' time = data['time'] out = '4-character id, %s\n' % data['id'] <|code_end|> , determine the next line of code. You have imports: import numpy as np import logging import h5py from pygeons.mjd import mjd_inv from pygeons.io.datacheck import check_data from pygeons.io.parser import PARSER_DICT and context (class names, function names, or code) available: # Path: pygeons/mjd.py # @_memoize # def mjd_inv(m,fmt): # ''' # Converts Modified Julian Date (MJD) to a date string # # Parameters # ---------- # m : int # Modified Julian Date # # fmt : string # format string indicating how to form *out* # # Returns # ------- # out : str # Date string # # ''' # m = int(m) # d = _REFERENCE_DATETIME + timedelta(m) # out = d.strftime(fmt) # return out # # Path: pygeons/io/datacheck.py # def check_data(data): # ''' # Runs all data consistency check # ''' # logger.debug('Checking data consistency ... ') # check_entries(data) # check_shapes(data) # check_positive_uncertainties(data) # check_missing_data(data) # check_unique_stations(data) # check_unique_dates(data) # logger.debug('OK') # # Path: pygeons/io/parser.py # PARSER_DICT = {'csv':parse_csv, # 'pbocsv':parse_pbocsv, # 'tdecsv':parse_tdecsv, # 'pbopos':parse_pbopos} . Output only the next line.
out += 'begin date, %s\n' % mjd_inv(time[0],'%Y-%m-%d')
Continue the code snippet: <|code_start|> out += 'latitude, %s N\n' % data['latitude'] out += ('units, meters**%s days**%s\n' % (data['space_exponent'],data['time_exponent'])) out += ('date, north, east, vertical, north std. deviation, ' 'east std. deviation, vertical std. deviation\n') # convert displacements and uncertainties to strings for i in range(len(data['time'])): date_str = mjd_inv(time[i],'%Y-%m-%d') out += ('%s, %e, %e, %e, %e, %e, %e\n' % (date_str,data['north'][i],data['east'][i], data['vertical'][i],data['north_std_dev'][i], data['east_std_dev'][i],data['vertical_std_dev'][i])) return out def text_from_dict(outfile,data): ''' Writes a text file from a data dictionary. The text file contains a csv string for each station separated by "***". Parameters ---------- outfile : string Name of the output text file data : dict Data dictionary ''' <|code_end|> . Use current file imports: import numpy as np import logging import h5py from pygeons.mjd import mjd_inv from pygeons.io.datacheck import check_data from pygeons.io.parser import PARSER_DICT and context (classes, functions, or code) from other files: # Path: pygeons/mjd.py # @_memoize # def mjd_inv(m,fmt): # ''' # Converts Modified Julian Date (MJD) to a date string # # Parameters # ---------- # m : int # Modified Julian Date # # fmt : string # format string indicating how to form *out* # # Returns # ------- # out : str # Date string # # ''' # m = int(m) # d = _REFERENCE_DATETIME + timedelta(m) # out = d.strftime(fmt) # return out # # Path: pygeons/io/datacheck.py # def check_data(data): # ''' # Runs all data consistency check # ''' # logger.debug('Checking data consistency ... ') # check_entries(data) # check_shapes(data) # check_positive_uncertainties(data) # check_missing_data(data) # check_unique_stations(data) # check_unique_dates(data) # logger.debug('OK') # # Path: pygeons/io/parser.py # PARSER_DICT = {'csv':parse_csv, # 'pbocsv':parse_pbocsv, # 'tdecsv':parse_tdecsv, # 'pbopos':parse_pbopos} . Output only the next line.
check_data(data)
Next line prediction: <|code_start|> fout.close() return ## Load DataDict instances from files ##################################################################### def dict_from_text(infile,parser='csv'): ''' Loads a data dictionary from a text file. Parameters ---------- infile : str Input file name parser : str String indicating which parser to use. Can be either "csv", "pbocsv", "tdecsv", or "pbopos". Returns ------- out : dict Data dictionary ''' buff = open(infile,'r') strs = buff.read().split('***') buff.close() # dictionaries of data for each station <|code_end|> . Use current file imports: (import numpy as np import logging import h5py from pygeons.mjd import mjd_inv from pygeons.io.datacheck import check_data from pygeons.io.parser import PARSER_DICT) and context including class names, function names, or small code snippets from other files: # Path: pygeons/mjd.py # @_memoize # def mjd_inv(m,fmt): # ''' # Converts Modified Julian Date (MJD) to a date string # # Parameters # ---------- # m : int # Modified Julian Date # # fmt : string # format string indicating how to form *out* # # Returns # ------- # out : str # Date string # # ''' # m = int(m) # d = _REFERENCE_DATETIME + timedelta(m) # out = d.strftime(fmt) # return out # # Path: pygeons/io/datacheck.py # def check_data(data): # ''' # Runs all data consistency check # ''' # logger.debug('Checking data consistency ... ') # check_entries(data) # check_shapes(data) # check_positive_uncertainties(data) # check_missing_data(data) # check_unique_stations(data) # check_unique_dates(data) # logger.debug('OK') # # Path: pygeons/io/parser.py # PARSER_DICT = {'csv':parse_csv, # 'pbocsv':parse_pbocsv, # 'tdecsv':parse_tdecsv, # 'pbopos':parse_pbopos} . Output only the next line.
dicts = [PARSER_DICT[parser](s) for s in strs]
Given the following code snippet before the placeholder: <|code_start|> # split by delimiter lst = line.split(delim) # find the index containing field for i,j in enumerate(lst): if field in j: field_idx = i break # entry after the one containing field if (field_idx + 1) >= len(lst): raise ValueError( 'No value associated with the field "%s". Make sure the ' 'correct delimiter is being used' % field) out = lst[field_idx + 1] # remove white space out = out.strip() return out def parse_csv(file_str): ''' Reads data from a single PyGeoNS csv file ''' fmt = '%Y-%m-%d' delim = ',' def date_conv(date_str): # return a float, rather than an integer, to be consistent with # the other data types <|code_end|> , predict the next line using imports from the current file: import numpy as np import logging from pygeons.mjd import mjd and context including class names, function names, and sometimes code from other files: # Path: pygeons/mjd.py # @_memoize # def mjd(s,fmt): # ''' # Converts a date string into Modified Julian Date (MJD) # # Parameters # ---------- # s : string # Date string # # fmt : string # Format string indicating how to parse *s* # # Returns # ------- # out : int # Modified Julian Date # # ''' # d = datetime.strptime(s,fmt) # out = (d - _REFERENCE_DATETIME).days # return out . Output only the next line.
return float(mjd(date_str,fmt))
Here is a snippet: <|code_start|> def remove_id(response, obj): obj.pop(response.model.pk_field.name) return obj class FormatedApp(ApiApp): def __init__(self, *args, **kwargs): super(FormatedApp, self).__init__(*args, **kwargs) self.view.formaters.append(remove_id) class TestApiView(TestCase): def test_get_list(self): <|code_end|> . Write the next line using the current file imports: from unittest import TestCase from werkzeug.wrappers import BaseResponse from werkzeug.test import Client from app import ApiApp from rest_api_framework.controllers import WSGIDispatcher import json import datetime and context from other files: # Path: rest_api_framework/controllers.py # class WSGIDispatcher(DispatcherMiddleware): # """ # WSGIDispatcher take a list of :class:`.Controller` and mount them # on their ressource mount point. # basic syntax is: # # .. code-block:: python # # app = WSGIDispatcher([FirstApp, SecondApp]) # """ # # def __init__(self, apps, name='PRAF', version='devel', # base_url=None, formats=None, autodoc=True, # autospore=True, hello=True): # if formats is None: # formats = [] # endpoints = {} # for elem in apps: # endpoints["/{0}".format(elem.ressource["ressource_name"])] = elem() # if not formats: # formats = ["json"] # if autodoc: # endpoints["/schema"] = self.make_schema(apps) # if autospore: # endpoints["/spore"] = self.make_spore(apps, name, base_url, # version) # if hello: # endpoints["/"] = self.make_hello(name, version) # # app = NotFound() # mounts = endpoints # super(WSGIDispatcher, self).__init__(app, mounts=mounts) # # def make_schema(self, apps): # return AutoDocGenerator(apps) # # def make_spore(self, apps, name, base_url, version): # return AutoSporeGenerator(apps, name, base_url, version) # # def make_hello(self, name, version): # return HelloGenerator(name, version) , which may include functions, classes, or code. Output only the next line.
client = Client(WSGIDispatcher([ApiApp]),
Given snippet: <|code_start|>""" Fields type used with models """ class Field(object): """ The base field class. A Field is part of a Model class. It define an aspect of a ressource. """ __metaclass__ = ABCMeta def __init__(self, name, **options): self.name = name self.options = options class IntegerField(Field): """ An integer field. python type int, with IntegerValidator """ base_type = "integer" <|code_end|> , continue by predicting the next line. Consider current file imports: from abc import ABCMeta from .validators import (IntegerValidator, StringValidator, FloatValidator, SQLiteForeign) and context: # Path: rest_api_framework/models/validators.py # class IntegerValidator(Validator): # """ # Validate that a value is of type int # """ # # def validate(self, field): # """ # Check if field is an instance of type 'int' # """ # if isinstance(field, int): # return True # return False # # class StringValidator(Validator): # """ # Validate that a value is of type basestring (either str or unicode) # """ # # def validate(self, field): # if isinstance(field, basestring): # return True # return False # # class FloatValidator(Validator): # """ # Validate that a value is of float type # """ # # def validate(self, field): # if isinstance(field, float): # return True # return False # # class SQLiteForeign(Validator): # """ # Validate that the foreign row exists # """ # need_datastore = True # # def __init__(self, **options): # self.options = options # # def validate(self, field, datastore): # # cursor = datastore.conn.cursor() # # cursor.execute("SELECT * FROM sqlite_master WHERE type='table';") # # cursor = datastore.conn.cursor() # query = "SELECT {0} FROM {1} WHERE {2}=?".format( # self.options["foreign"]["column"], # self.options["foreign"]["table"], # self.options["foreign"]["column"], # ) # cursor.execute(query, (field, )) # if cursor.fetchone(): # return True # return False which might include code, classes, or functions. Output only the next line.
validators = [IntegerValidator()]
Given snippet: <|code_start|> class Field(object): """ The base field class. A Field is part of a Model class. It define an aspect of a ressource. """ __metaclass__ = ABCMeta def __init__(self, name, **options): self.name = name self.options = options class IntegerField(Field): """ An integer field. python type int, with IntegerValidator """ base_type = "integer" validators = [IntegerValidator()] example = 42 class StringField(Field): """ An string field. python type basestring (either str or basestring), with StringValidator """ base_type = "string" <|code_end|> , continue by predicting the next line. Consider current file imports: from abc import ABCMeta from .validators import (IntegerValidator, StringValidator, FloatValidator, SQLiteForeign) and context: # Path: rest_api_framework/models/validators.py # class IntegerValidator(Validator): # """ # Validate that a value is of type int # """ # # def validate(self, field): # """ # Check if field is an instance of type 'int' # """ # if isinstance(field, int): # return True # return False # # class StringValidator(Validator): # """ # Validate that a value is of type basestring (either str or unicode) # """ # # def validate(self, field): # if isinstance(field, basestring): # return True # return False # # class FloatValidator(Validator): # """ # Validate that a value is of float type # """ # # def validate(self, field): # if isinstance(field, float): # return True # return False # # class SQLiteForeign(Validator): # """ # Validate that the foreign row exists # """ # need_datastore = True # # def __init__(self, **options): # self.options = options # # def validate(self, field, datastore): # # cursor = datastore.conn.cursor() # # cursor.execute("SELECT * FROM sqlite_master WHERE type='table';") # # cursor = datastore.conn.cursor() # query = "SELECT {0} FROM {1} WHERE {2}=?".format( # self.options["foreign"]["column"], # self.options["foreign"]["table"], # self.options["foreign"]["column"], # ) # cursor.execute(query, (field, )) # if cursor.fetchone(): # return True # return False which might include code, classes, or functions. Output only the next line.
validators = [StringValidator()]
Here is a snippet: <|code_start|> base_type = "integer" example = 42 class StringForeingKey(ForeignKeyField, Field): """ A type of string and a Foreign key to check """ base_type = "string" example = "hackme" def __init__(self, name, **options): super(StringForeingKey, self).__init__(name, **options) self.validators = [SQLiteForeign(**options), StringValidator()] class StringPkField(PkField): """ A string based PkField """ base_type = "string" validators = [StringValidator()] example = "i6HOCjvZMQ4" class TimestampField(Field): """ A unix timestamp """ base_type = "float" <|code_end|> . Write the next line using the current file imports: from abc import ABCMeta from .validators import (IntegerValidator, StringValidator, FloatValidator, SQLiteForeign) and context from other files: # Path: rest_api_framework/models/validators.py # class IntegerValidator(Validator): # """ # Validate that a value is of type int # """ # # def validate(self, field): # """ # Check if field is an instance of type 'int' # """ # if isinstance(field, int): # return True # return False # # class StringValidator(Validator): # """ # Validate that a value is of type basestring (either str or unicode) # """ # # def validate(self, field): # if isinstance(field, basestring): # return True # return False # # class FloatValidator(Validator): # """ # Validate that a value is of float type # """ # # def validate(self, field): # if isinstance(field, float): # return True # return False # # class SQLiteForeign(Validator): # """ # Validate that the foreign row exists # """ # need_datastore = True # # def __init__(self, **options): # self.options = options # # def validate(self, field, datastore): # # cursor = datastore.conn.cursor() # # cursor.execute("SELECT * FROM sqlite_master WHERE type='table';") # # cursor = datastore.conn.cursor() # query = "SELECT {0} FROM {1} WHERE {2}=?".format( # self.options["foreign"]["column"], # self.options["foreign"]["table"], # self.options["foreign"]["column"], # ) # cursor.execute(query, (field, )) # if cursor.fetchone(): # return True # return False , which may include functions, classes, or code. Output only the next line.
validators = [FloatValidator()]
Predict the next line for this snippet: <|code_start|> base_type = "integer" validators = [IntegerValidator()] example = 42 class StringField(Field): """ An string field. python type basestring (either str or basestring), with StringValidator """ base_type = "string" validators = [StringValidator()] example = "Hello World" class PkField(Field): """ PkField is a mandatory field for a model. It define the unique ressource identifier. If your unique field is not an integer field, you have to inherit from this class and implement your own. see StringPkField """ base_type = "integer" validators = [] example = 42 class ForeignKeyField(object): def __init__(self, name, **options): <|code_end|> with the help of current file imports: from abc import ABCMeta from .validators import (IntegerValidator, StringValidator, FloatValidator, SQLiteForeign) and context from other files: # Path: rest_api_framework/models/validators.py # class IntegerValidator(Validator): # """ # Validate that a value is of type int # """ # # def validate(self, field): # """ # Check if field is an instance of type 'int' # """ # if isinstance(field, int): # return True # return False # # class StringValidator(Validator): # """ # Validate that a value is of type basestring (either str or unicode) # """ # # def validate(self, field): # if isinstance(field, basestring): # return True # return False # # class FloatValidator(Validator): # """ # Validate that a value is of float type # """ # # def validate(self, field): # if isinstance(field, float): # return True # return False # # class SQLiteForeign(Validator): # """ # Validate that the foreign row exists # """ # need_datastore = True # # def __init__(self, **options): # self.options = options # # def validate(self, field, datastore): # # cursor = datastore.conn.cursor() # # cursor.execute("SELECT * FROM sqlite_master WHERE type='table';") # # cursor = datastore.conn.cursor() # query = "SELECT {0} FROM {1} WHERE {2}=?".format( # self.options["foreign"]["column"], # self.options["foreign"]["table"], # self.options["foreign"]["column"], # ) # cursor.execute(query, (field, )) # if cursor.fetchone(): # return True # return False , which may contain function names, class names, or code. Output only the next line.
self.validators = [SQLiteForeign(**options), IntegerValidator()]