Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Given snippet: <|code_start|> " tagged ethe 1/2 ethe 1/4 to 1/6", "!", "vlan 200", " tagged ethe 1/2", "!", "vlan 300", " tagged ethe 1/2", "!", "vlan 1999", " untagged ethe 1/1", "!", "vlan 2999", " untagged ethe 1/2", "!", "!" ]) result = self.switch.get_interfaces() if1, if2, if3, if4, if5, if6 = result assert_that(if1.name, equal_to("ethernet 1/1")) assert_that(if1.shutdown, equal_to(False)) assert_that(if1.port_mode, equal_to(ACCESS)) assert_that(if1.access_vlan, equal_to(1999)) assert_that(if1.trunk_native_vlan, equal_to(None)) assert_that(if1.trunk_vlans, equal_to([])) assert_that(if2.name, equal_to("ethernet 1/2")) assert_that(if2.shutdown, equal_to(True)) <|code_end|> , continue by predicting the next line. Consider current file imports: import unittest import mock from flexmock import flexmock, flexmock_teardown from hamcrest import assert_that, has_length, equal_to, is_, none, empty from netaddr import IPNetwork from netaddr.ip import IPAddress from netman.adapters.switches import brocade_factory_ssh, brocade_factory_telnet from netman.adapters.switches.brocade import Brocade, parse_if_ranges from netman.adapters.switches.util import SubShell from netman.core.objects.access_groups import IN, OUT from netman.core.objects.exceptions import IPNotAvailable, UnknownVlan, UnknownIP, UnknownAccessGroup, BadVlanNumber, \ BadVlanName, UnknownInterface, TrunkVlanNotSet, UnknownVrf, VlanVrfNotSet, VrrpAlreadyExistsForVlan, BadVrrpPriorityNumber, BadVrrpGroupNumber, \ BadVrrpTimers, BadVrrpTracking, NoIpOnVlanForVrrp, VrrpDoesNotExistForVlan, UnknownDhcpRelayServer, DhcpRelayServerAlreadyExists, \ VlanAlreadyExist, InvalidAccessGroupName, IPAlreadySet from netman.core.objects.interface_states import OFF, ON from netman.core.objects.port_modes import ACCESS, TRUNK from netman.core.objects.switch_descriptor import SwitchDescriptor and context: # Path: netman/adapters/switches/util.py # class SubShell(object): # debug = False # # def __init__(self, ssh, enter, exit_cmd, validate=None): # self.ssh = ssh # self.enter = enter # self.exit = exit_cmd # self.validate = validate or (lambda x: None) # # def __enter__(self): # if isinstance(self.enter, list): # [self.validate(self.ssh.do(cmd)) for cmd in self.enter] # else: # self.validate(self.ssh.do(self.enter)) # return self.ssh # # def __exit__(self, eType, eValue, eTrace): # if self.debug and eType is not None: # logging.error("Subshell exception {}: {}\n{}" # .format(eType.__name__, eValue, "".join(traceback.format_tb(eTrace)))) # # self.ssh.do(self.exit) # # Path: netman/core/objects/port_modes.py # ACCESS = "ACCESS" # # TRUNK = "TRUNK" # # Path: netman/core/objects/switch_descriptor.py # class SwitchDescriptor(Model): # def __init__(self, model, hostname, username=None, password=None, port=None, netman_server=None): # self.model = model # self.hostname = hostname # self.username = username # self.password = password # self.port = port # self.netman_server = netman_server which might include code, classes, or functions. Output only the next line.
assert_that(if2.port_mode, equal_to(TRUNK))
Next line prediction: <|code_start|> self.sessions_manager = sessions_manager def hook_to(self, server): raise NotImplemented() @property def logger(self): return logging.getLogger(__name__) def _get_switch_descriptor_from_request_headers(self, hostname): headers_present = [h in request.headers for h in ['Netman-Model', 'Netman-Username', 'Netman-Password']] if not any(headers_present): return None if not all(headers_present): raise BadRequest('For anonymous switch usage, please specify headers: Netman-Model, Netman-Username and Netman-Password.') port = None if "Netman-Port" in request.headers: try: port = int(request.headers["Netman-Port"]) except ValueError: raise BadRequest('Netman-Port optional header should be an integer') netman_server = request.headers.get("Netman-Proxy-Server", None) if netman_server is not None and "," in netman_server: netman_server = [e.strip() for e in netman_server.split(",")] self.logger.info("Anonymous Switch Access ({}) {}@{}".format(request.headers['Netman-Model'], request.headers['Netman-Username'], hostname)) <|code_end|> . Use current file imports: (import logging from flask import request from netman.api.api_utils import BadRequest from netman.core.objects.switch_descriptor import SwitchDescriptor) and context including class names, function names, or small code snippets from other files: # Path: netman/core/objects/switch_descriptor.py # class SwitchDescriptor(Model): # def __init__(self, model, hostname, username=None, password=None, port=None, netman_server=None): # self.model = model # self.hostname = hostname # self.username = username # self.password = password # self.port = port # self.netman_server = netman_server . Output only the next line.
return SwitchDescriptor(
Based on the snippet: <|code_start|> self.server = server return self @to_response @content(is_session) def open_session(self, session_id, hostname): """ Open a locked session on a switch :arg str hostname: Hostname or IP of the switch :body: .. literalinclude:: ../doc_config/api_samples/post_switch_session.json :language: json :code 201 CREATED: Example output: .. literalinclude:: ../doc_config/api_samples/post_switch_session_result.json :language: json """ switch = self.resolve_switch(hostname) session_id = self.sessions_manager.open_session(switch, session_id) return 201, {'session_id': session_id} @to_response <|code_end|> , predict the immediate next line with the help of imports: from flask import request from netman.api.api_utils import BadRequest, to_response from netman.api.switch_api_base import SwitchApiBase from netman.api.validators import resource, content, Session, \ Resource, is_session and context (classes, functions, sometimes code) from other files: # Path: netman/api/switch_api_base.py # class SwitchApiBase(object): # def __init__(self, switch_factory, sessions_manager): # self.switch_factory = switch_factory # self.sessions_manager = sessions_manager # # def hook_to(self, server): # raise NotImplemented() # # @property # def logger(self): # return logging.getLogger(__name__) # # def _get_switch_descriptor_from_request_headers(self, hostname): # headers_present = [h in request.headers for h in ['Netman-Model', 'Netman-Username', 'Netman-Password']] # # if not any(headers_present): # return None # # if not all(headers_present): # raise BadRequest('For anonymous switch usage, please specify headers: Netman-Model, Netman-Username and Netman-Password.') # # port = None # if "Netman-Port" in request.headers: # try: # port = int(request.headers["Netman-Port"]) # except ValueError: # raise BadRequest('Netman-Port optional header should be an integer') # # netman_server = request.headers.get("Netman-Proxy-Server", None) # if netman_server is not None and "," in netman_server: # netman_server = [e.strip() for e in netman_server.split(",")] # # self.logger.info("Anonymous Switch Access ({}) {}@{}".format(request.headers['Netman-Model'], request.headers['Netman-Username'], hostname)) # return SwitchDescriptor( # hostname=hostname, # model=request.headers['Netman-Model'], # username=request.headers['Netman-Username'], # password=request.headers['Netman-Password'], # port=port, # netman_server=netman_server # ) # # def resolve_switch(self, hostname): # switch_descriptor = self._get_switch_descriptor_from_request_headers(hostname) # # if switch_descriptor: # return self.switch_factory.get_switch_by_descriptor(switch_descriptor) # return self.switch_factory.get_switch(hostname) # # def resolve_session(self, session_id): # return self.sessions_manager.get_switch_for_session(session_id) # # Path: netman/api/validators.py # def resource(*validators): # # def resource_decorator(fn): # @wraps(fn) # def wrapper(self, **kwargs): # with MultiContext(self, kwargs, *validators) as ctxs: # return fn(self, *ctxs, **kwargs) # # return wrapper # # return resource_decorator # # def content(validator_fn): # # def content_decorator(fn): # @wraps(fn) # def wrapper(*args, **kwargs): # kwargs.update(validator_fn(request.data)) # return fn(*args, **kwargs) # # return wrapper # # return content_decorator # # class Session: # def __init__(self, switch_api): # self.switch_api = switch_api # self.session = None # # def process(self, parameters): # self.session = parameters.pop('session_id') # self.switch_api.resolve_session(self.session) # # def __enter__(self): # return self.session # # def __exit__(self, *_): # pass # # class Resource: # def __init__(self, switch_api): # self.switch_api = switch_api # self.resource = None # # def process(self, parameters): # self.resource = parameters.pop('resource') # # def __enter__(self): # return self.resource # # def __exit__(self, *_): # pass # # def is_session(data, **_): # try: # json_data = json.loads(data) # except ValueError: # raise BadRequest("Malformed content, should be a JSON object") # # if "hostname" not in json_data: # raise MalformedSwitchSessionRequest() # return { # 'hostname': json_data["hostname"] # } . Output only the next line.
@resource(Session)
Given the following code snippet before the placeholder: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class SwitchSessionApi(SwitchApiBase): def __init__(self, switch_factory, sessions_manager): super(SwitchSessionApi, self).__init__(switch_factory, sessions_manager) self.server = None def hook_to(self, server): server.add_url_rule('/switches-sessions/<session_id>', view_func=self.open_session, methods=['POST']) server.add_url_rule('/switches-sessions/<session_id>', view_func=self.close_session, methods=['DELETE']) server.add_url_rule('/switches-sessions/<session_id>/actions', view_func=self.act_on_session, methods=['POST']) server.add_url_rule('/switches-sessions/<session_id>/<path:resource>', view_func=self.on_session, methods=['GET', 'PUT', 'POST', 'DELETE']) self.server = server return self @to_response <|code_end|> , predict the next line using imports from the current file: from flask import request from netman.api.api_utils import BadRequest, to_response from netman.api.switch_api_base import SwitchApiBase from netman.api.validators import resource, content, Session, \ Resource, is_session and context including class names, function names, and sometimes code from other files: # Path: netman/api/switch_api_base.py # class SwitchApiBase(object): # def __init__(self, switch_factory, sessions_manager): # self.switch_factory = switch_factory # self.sessions_manager = sessions_manager # # def hook_to(self, server): # raise NotImplemented() # # @property # def logger(self): # return logging.getLogger(__name__) # # def _get_switch_descriptor_from_request_headers(self, hostname): # headers_present = [h in request.headers for h in ['Netman-Model', 'Netman-Username', 'Netman-Password']] # # if not any(headers_present): # return None # # if not all(headers_present): # raise BadRequest('For anonymous switch usage, please specify headers: Netman-Model, Netman-Username and Netman-Password.') # # port = None # if "Netman-Port" in request.headers: # try: # port = int(request.headers["Netman-Port"]) # except ValueError: # raise BadRequest('Netman-Port optional header should be an integer') # # netman_server = request.headers.get("Netman-Proxy-Server", None) # if netman_server is not None and "," in netman_server: # netman_server = [e.strip() for e in netman_server.split(",")] # # self.logger.info("Anonymous Switch Access ({}) {}@{}".format(request.headers['Netman-Model'], request.headers['Netman-Username'], hostname)) # return SwitchDescriptor( # hostname=hostname, # model=request.headers['Netman-Model'], # username=request.headers['Netman-Username'], # password=request.headers['Netman-Password'], # port=port, # netman_server=netman_server # ) # # def resolve_switch(self, hostname): # switch_descriptor = self._get_switch_descriptor_from_request_headers(hostname) # # if switch_descriptor: # return self.switch_factory.get_switch_by_descriptor(switch_descriptor) # return self.switch_factory.get_switch(hostname) # # def resolve_session(self, session_id): # return self.sessions_manager.get_switch_for_session(session_id) # # Path: netman/api/validators.py # def resource(*validators): # # def resource_decorator(fn): # @wraps(fn) # def wrapper(self, **kwargs): # with MultiContext(self, kwargs, *validators) as ctxs: # return fn(self, *ctxs, **kwargs) # # return wrapper # # return resource_decorator # # def content(validator_fn): # # def content_decorator(fn): # @wraps(fn) # def wrapper(*args, **kwargs): # kwargs.update(validator_fn(request.data)) # return fn(*args, **kwargs) # # return wrapper # # return content_decorator # # class Session: # def __init__(self, switch_api): # self.switch_api = switch_api # self.session = None # # def process(self, parameters): # self.session = parameters.pop('session_id') # self.switch_api.resolve_session(self.session) # # def __enter__(self): # return self.session # # def __exit__(self, *_): # pass # # class Resource: # def __init__(self, switch_api): # self.switch_api = switch_api # self.resource = None # # def process(self, parameters): # self.resource = parameters.pop('resource') # # def __enter__(self): # return self.resource # # def __exit__(self, *_): # pass # # def is_session(data, **_): # try: # json_data = json.loads(data) # except ValueError: # raise BadRequest("Malformed content, should be a JSON object") # # if "hostname" not in json_data: # raise MalformedSwitchSessionRequest() # return { # 'hostname': json_data["hostname"] # } . Output only the next line.
@content(is_session)
Using the snippet: <|code_start|> self.server = server return self @to_response @content(is_session) def open_session(self, session_id, hostname): """ Open a locked session on a switch :arg str hostname: Hostname or IP of the switch :body: .. literalinclude:: ../doc_config/api_samples/post_switch_session.json :language: json :code 201 CREATED: Example output: .. literalinclude:: ../doc_config/api_samples/post_switch_session_result.json :language: json """ switch = self.resolve_switch(hostname) session_id = self.sessions_manager.open_session(switch, session_id) return 201, {'session_id': session_id} @to_response <|code_end|> , determine the next line of code. You have imports: from flask import request from netman.api.api_utils import BadRequest, to_response from netman.api.switch_api_base import SwitchApiBase from netman.api.validators import resource, content, Session, \ Resource, is_session and context (class names, function names, or code) available: # Path: netman/api/switch_api_base.py # class SwitchApiBase(object): # def __init__(self, switch_factory, sessions_manager): # self.switch_factory = switch_factory # self.sessions_manager = sessions_manager # # def hook_to(self, server): # raise NotImplemented() # # @property # def logger(self): # return logging.getLogger(__name__) # # def _get_switch_descriptor_from_request_headers(self, hostname): # headers_present = [h in request.headers for h in ['Netman-Model', 'Netman-Username', 'Netman-Password']] # # if not any(headers_present): # return None # # if not all(headers_present): # raise BadRequest('For anonymous switch usage, please specify headers: Netman-Model, Netman-Username and Netman-Password.') # # port = None # if "Netman-Port" in request.headers: # try: # port = int(request.headers["Netman-Port"]) # except ValueError: # raise BadRequest('Netman-Port optional header should be an integer') # # netman_server = request.headers.get("Netman-Proxy-Server", None) # if netman_server is not None and "," in netman_server: # netman_server = [e.strip() for e in netman_server.split(",")] # # self.logger.info("Anonymous Switch Access ({}) {}@{}".format(request.headers['Netman-Model'], request.headers['Netman-Username'], hostname)) # return SwitchDescriptor( # hostname=hostname, # model=request.headers['Netman-Model'], # username=request.headers['Netman-Username'], # password=request.headers['Netman-Password'], # port=port, # netman_server=netman_server # ) # # def resolve_switch(self, hostname): # switch_descriptor = self._get_switch_descriptor_from_request_headers(hostname) # # if switch_descriptor: # return self.switch_factory.get_switch_by_descriptor(switch_descriptor) # return self.switch_factory.get_switch(hostname) # # def resolve_session(self, session_id): # return self.sessions_manager.get_switch_for_session(session_id) # # Path: netman/api/validators.py # def resource(*validators): # # def resource_decorator(fn): # @wraps(fn) # def wrapper(self, **kwargs): # with MultiContext(self, kwargs, *validators) as ctxs: # return fn(self, *ctxs, **kwargs) # # return wrapper # # return resource_decorator # # def content(validator_fn): # # def content_decorator(fn): # @wraps(fn) # def wrapper(*args, **kwargs): # kwargs.update(validator_fn(request.data)) # return fn(*args, **kwargs) # # return wrapper # # return content_decorator # # class Session: # def __init__(self, switch_api): # self.switch_api = switch_api # self.session = None # # def process(self, parameters): # self.session = parameters.pop('session_id') # self.switch_api.resolve_session(self.session) # # def __enter__(self): # return self.session # # def __exit__(self, *_): # pass # # class Resource: # def __init__(self, switch_api): # self.switch_api = switch_api # self.resource = None # # def process(self, parameters): # self.resource = parameters.pop('resource') # # def __enter__(self): # return self.resource # # def __exit__(self, *_): # pass # # def is_session(data, **_): # try: # json_data = json.loads(data) # except ValueError: # raise BadRequest("Malformed content, should be a JSON object") # # if "hostname" not in json_data: # raise MalformedSwitchSessionRequest() # return { # 'hostname': json_data["hostname"] # } . Output only the next line.
@resource(Session)
Based on the snippet: <|code_start|> :code 201 CREATED: Example output: .. literalinclude:: ../doc_config/api_samples/post_switch_session_result.json :language: json """ switch = self.resolve_switch(hostname) session_id = self.sessions_manager.open_session(switch, session_id) return 201, {'session_id': session_id} @to_response @resource(Session) def close_session(self, session_id): """ Close a session on a switch :arg str session: ID of the session """ self.sessions_manager.close_session(session_id) return 204, None @to_response <|code_end|> , predict the immediate next line with the help of imports: from flask import request from netman.api.api_utils import BadRequest, to_response from netman.api.switch_api_base import SwitchApiBase from netman.api.validators import resource, content, Session, \ Resource, is_session and context (classes, functions, sometimes code) from other files: # Path: netman/api/switch_api_base.py # class SwitchApiBase(object): # def __init__(self, switch_factory, sessions_manager): # self.switch_factory = switch_factory # self.sessions_manager = sessions_manager # # def hook_to(self, server): # raise NotImplemented() # # @property # def logger(self): # return logging.getLogger(__name__) # # def _get_switch_descriptor_from_request_headers(self, hostname): # headers_present = [h in request.headers for h in ['Netman-Model', 'Netman-Username', 'Netman-Password']] # # if not any(headers_present): # return None # # if not all(headers_present): # raise BadRequest('For anonymous switch usage, please specify headers: Netman-Model, Netman-Username and Netman-Password.') # # port = None # if "Netman-Port" in request.headers: # try: # port = int(request.headers["Netman-Port"]) # except ValueError: # raise BadRequest('Netman-Port optional header should be an integer') # # netman_server = request.headers.get("Netman-Proxy-Server", None) # if netman_server is not None and "," in netman_server: # netman_server = [e.strip() for e in netman_server.split(",")] # # self.logger.info("Anonymous Switch Access ({}) {}@{}".format(request.headers['Netman-Model'], request.headers['Netman-Username'], hostname)) # return SwitchDescriptor( # hostname=hostname, # model=request.headers['Netman-Model'], # username=request.headers['Netman-Username'], # password=request.headers['Netman-Password'], # port=port, # netman_server=netman_server # ) # # def resolve_switch(self, hostname): # switch_descriptor = self._get_switch_descriptor_from_request_headers(hostname) # # if switch_descriptor: # return self.switch_factory.get_switch_by_descriptor(switch_descriptor) # return self.switch_factory.get_switch(hostname) # # def resolve_session(self, session_id): # return self.sessions_manager.get_switch_for_session(session_id) # # Path: netman/api/validators.py # def resource(*validators): # # def resource_decorator(fn): # @wraps(fn) # def wrapper(self, **kwargs): # with MultiContext(self, kwargs, *validators) as ctxs: # return fn(self, *ctxs, **kwargs) # # return wrapper # # return resource_decorator # # def content(validator_fn): # # def content_decorator(fn): # @wraps(fn) # def wrapper(*args, **kwargs): # kwargs.update(validator_fn(request.data)) # return fn(*args, **kwargs) # # return wrapper # # return content_decorator # # class Session: # def __init__(self, switch_api): # self.switch_api = switch_api # self.session = None # # def process(self, parameters): # self.session = parameters.pop('session_id') # self.switch_api.resolve_session(self.session) # # def __enter__(self): # return self.session # # def __exit__(self, *_): # pass # # class Resource: # def __init__(self, switch_api): # self.switch_api = switch_api # self.resource = None # # def process(self, parameters): # self.resource = parameters.pop('resource') # # def __enter__(self): # return self.resource # # def __exit__(self, *_): # pass # # def is_session(data, **_): # try: # json_data = json.loads(data) # except ValueError: # raise BadRequest("Malformed content, should be a JSON object") # # if "hostname" not in json_data: # raise MalformedSwitchSessionRequest() # return { # 'hostname': json_data["hostname"] # } . Output only the next line.
@resource(Session, Resource)
Next line prediction: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class SwitchSessionApi(SwitchApiBase): def __init__(self, switch_factory, sessions_manager): super(SwitchSessionApi, self).__init__(switch_factory, sessions_manager) self.server = None def hook_to(self, server): server.add_url_rule('/switches-sessions/<session_id>', view_func=self.open_session, methods=['POST']) server.add_url_rule('/switches-sessions/<session_id>', view_func=self.close_session, methods=['DELETE']) server.add_url_rule('/switches-sessions/<session_id>/actions', view_func=self.act_on_session, methods=['POST']) server.add_url_rule('/switches-sessions/<session_id>/<path:resource>', view_func=self.on_session, methods=['GET', 'PUT', 'POST', 'DELETE']) self.server = server return self @to_response <|code_end|> . Use current file imports: (from flask import request from netman.api.api_utils import BadRequest, to_response from netman.api.switch_api_base import SwitchApiBase from netman.api.validators import resource, content, Session, \ Resource, is_session) and context including class names, function names, or small code snippets from other files: # Path: netman/api/switch_api_base.py # class SwitchApiBase(object): # def __init__(self, switch_factory, sessions_manager): # self.switch_factory = switch_factory # self.sessions_manager = sessions_manager # # def hook_to(self, server): # raise NotImplemented() # # @property # def logger(self): # return logging.getLogger(__name__) # # def _get_switch_descriptor_from_request_headers(self, hostname): # headers_present = [h in request.headers for h in ['Netman-Model', 'Netman-Username', 'Netman-Password']] # # if not any(headers_present): # return None # # if not all(headers_present): # raise BadRequest('For anonymous switch usage, please specify headers: Netman-Model, Netman-Username and Netman-Password.') # # port = None # if "Netman-Port" in request.headers: # try: # port = int(request.headers["Netman-Port"]) # except ValueError: # raise BadRequest('Netman-Port optional header should be an integer') # # netman_server = request.headers.get("Netman-Proxy-Server", None) # if netman_server is not None and "," in netman_server: # netman_server = [e.strip() for e in netman_server.split(",")] # # self.logger.info("Anonymous Switch Access ({}) {}@{}".format(request.headers['Netman-Model'], request.headers['Netman-Username'], hostname)) # return SwitchDescriptor( # hostname=hostname, # model=request.headers['Netman-Model'], # username=request.headers['Netman-Username'], # password=request.headers['Netman-Password'], # port=port, # netman_server=netman_server # ) # # def resolve_switch(self, hostname): # switch_descriptor = self._get_switch_descriptor_from_request_headers(hostname) # # if switch_descriptor: # return self.switch_factory.get_switch_by_descriptor(switch_descriptor) # return self.switch_factory.get_switch(hostname) # # def resolve_session(self, session_id): # return self.sessions_manager.get_switch_for_session(session_id) # # Path: netman/api/validators.py # def resource(*validators): # # def resource_decorator(fn): # @wraps(fn) # def wrapper(self, **kwargs): # with MultiContext(self, kwargs, *validators) as ctxs: # return fn(self, *ctxs, **kwargs) # # return wrapper # # return resource_decorator # # def content(validator_fn): # # def content_decorator(fn): # @wraps(fn) # def wrapper(*args, **kwargs): # kwargs.update(validator_fn(request.data)) # return fn(*args, **kwargs) # # return wrapper # # return content_decorator # # class Session: # def __init__(self, switch_api): # self.switch_api = switch_api # self.session = None # # def process(self, parameters): # self.session = parameters.pop('session_id') # self.switch_api.resolve_session(self.session) # # def __enter__(self): # return self.session # # def __exit__(self, *_): # pass # # class Resource: # def __init__(self, switch_api): # self.switch_api = switch_api # self.resource = None # # def process(self, parameters): # self.resource = parameters.pop('resource') # # def __enter__(self): # return self.resource # # def __exit__(self, *_): # pass # # def is_session(data, **_): # try: # json_data = json.loads(data) # except ValueError: # raise BadRequest("Malformed content, should be a JSON object") # # if "hostname" not in json_data: # raise MalformedSwitchSessionRequest() # return { # 'hostname': json_data["hostname"] # } . Output only the next line.
@content(is_session)
Predict the next line after this snippet: <|code_start|> from scipy.signal import lfilter noise = randn(50000,1); % Normalized white Gaussian noise x = filter([1], [1 1/2 1/3 1/4], noise) x = x[45904:50000] x.reshape(4096, 1) x = x[0] Compute the predictor coefficients, estimated signal, prediction error, and autocorrelation sequence of the prediction error: 1.00000 + 0.00000i 0.51711 - 0.00000i 0.33908 - 0.00000i 0.24410 - 0.00000i :: a = lpc(x, 3) est_x = lfilter([0 -a(2:end)],1,x); % Estimated signal e = x - est_x; % Prediction error [acs, lags] = xcorr(e,'coeff'); % ACS of prediction error """ m = len(x) if N is None: N = m - 1 #default value if N is not provided elif N > m-1: #disp('Warning: zero-padding short input sequence') x.resize(N+1) #todo: check this zero-padding. <|code_end|> using the current file's imports: from numpy.fft import fft, ifft from .tools import nextpow2 from numpy import real from spectrum.levinson import LEVINSON and any relevant context from other files: # Path: src/spectrum/tools.py # def nextpow2(x): # """returns the smallest power of two that is greater than or equal to the # absolute value of x. # # This function is useful for optimizing FFT operations, which are # most efficient when sequence length is an exact power of two. # # :Example: # # .. doctest:: # # >>> from spectrum import nextpow2 # >>> x = [255, 256, 257] # >>> nextpow2(x) # array([8, 8, 9]) # # """ # res = ceil(log2(x)) # return res.astype('int') #we want integer values only but ceil gives float . Output only the next line.
X = fft(x, 2**nextpow2(2.*len(x)-1))
Continue the code snippet: <|code_start|> source_hash = request.POST['source_hash'] # print (url, domain) if request.POST.get('css'): # it's a stylesheet! css = request.POST['css'] for page in Stylesheet.objects.filter( url=url, domain=domain, source_hash=source_hash): if page.css == css: created = False break else: page = Stylesheet.objects.create( url=url, domain=domain, source_hash=source_hash, css=css, ) created = True if created: print "New CSS", domain, url print len(page), "bytes" else: print "Not new CSS", domain, url else: html = request.POST['html'] <|code_end|> . Use current file imports: from urlparse import urlparse from django import http from django.views.decorators.csrf import csrf_exempt from webalyzer.collector.models import Page, Stylesheet and context (classes, functions, or code) from other files: # Path: webalyzer/collector/models.py # class Page(models.Model): # domain = models.CharField(max_length=100, db_index=True) # url = models.URLField() # html = models.TextField() # size = models.PositiveIntegerField(default=0) # title = models.TextField(null=True) # added = models.DateTimeField(auto_now_add=True) # modified = models.DateTimeField(auto_now=True) # source_hash = models.IntegerField(default=0, db_index=True) # # def __unicode__(self): # return self.url # # def __repr__(self): # return '<%s: %s %.2fKb>' % ( # self.__class__.__name__, # self.url, # len(self.html) / 1024.0 # ) # # def __len__(self): # return len(self.html) # # class Stylesheet(models.Model): # domain = models.CharField(max_length=100, db_index=True) # url = models.URLField() # css = models.TextField() # size = models.PositiveIntegerField(default=0) # added = models.DateTimeField(auto_now_add=True) # modified = models.DateTimeField(auto_now=True) # source_hash = models.IntegerField(default=0, db_index=True) # # def __unicode__(self): # return self.url # # def __repr__(self): # return '<%s: %s %.2fKb>' % ( # self.__class__.__name__, # self.url, # len(self.css) / 1024.0 # ) # # def __len__(self): # return len(self.css) . Output only the next line.
for page in Page.objects.filter(
Using the snippet: <|code_start|> @csrf_exempt def collect(request): if request.method in ('GET', 'HEAD'): response = http.HttpResponse('Works') response['Access-Control-Allow-Origin'] = '*' return response url = request.POST['url'] domain = request.POST.get('domain', urlparse(url).netloc) source_hash = request.POST['source_hash'] # print (url, domain) if request.POST.get('css'): # it's a stylesheet! css = request.POST['css'] <|code_end|> , determine the next line of code. You have imports: from urlparse import urlparse from django import http from django.views.decorators.csrf import csrf_exempt from webalyzer.collector.models import Page, Stylesheet and context (class names, function names, or code) available: # Path: webalyzer/collector/models.py # class Page(models.Model): # domain = models.CharField(max_length=100, db_index=True) # url = models.URLField() # html = models.TextField() # size = models.PositiveIntegerField(default=0) # title = models.TextField(null=True) # added = models.DateTimeField(auto_now_add=True) # modified = models.DateTimeField(auto_now=True) # source_hash = models.IntegerField(default=0, db_index=True) # # def __unicode__(self): # return self.url # # def __repr__(self): # return '<%s: %s %.2fKb>' % ( # self.__class__.__name__, # self.url, # len(self.html) / 1024.0 # ) # # def __len__(self): # return len(self.html) # # class Stylesheet(models.Model): # domain = models.CharField(max_length=100, db_index=True) # url = models.URLField() # css = models.TextField() # size = models.PositiveIntegerField(default=0) # added = models.DateTimeField(auto_now_add=True) # modified = models.DateTimeField(auto_now=True) # source_hash = models.IntegerField(default=0, db_index=True) # # def __unicode__(self): # return self.url # # def __repr__(self): # return '<%s: %s %.2fKb>' % ( # self.__class__.__name__, # self.url, # len(self.css) / 1024.0 # ) # # def __len__(self): # return len(self.css) . Output only the next line.
for page in Stylesheet.objects.filter(
Continue the code snippet: <|code_start|> root, pretty_print=False, method='html', encoding='utf-8', )) # that 'screenshot.js' file is in the same directory as this file _here = os.path.dirname(__file__) width, height = 1400, 900 cmd = [ 'phantomjs', '--ignore-ssl-errors=yes', os.path.join(_here, 'screenshot.js'), html_file, png_file, str(width), str(height) ] # print cmd process = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) stdout, stderr = process.communicate() # print (stdout, stderr) if not os.path.isfile(png_file): raise Exception("No PNG file created") with open(png_file, 'rb') as f: <|code_end|> . Use current file imports: import os import subprocess import urlparse import shutil import tempfile from contextlib import contextmanager from lxml import etree from lxml.cssselect import CSSSelector from celery import shared_task from django.core.files import File from webalyzer.collected.models import Screenshot from webalyzer.collector.models import Page and context (classes, functions, or code) from other files: # Path: webalyzer/collected/models.py # class Screenshot(models.Model): # page = models.ForeignKey(Page) # file = ImageField(upload_to='screenshots') # width = models.PositiveIntegerField() # height = models.PositiveIntegerField() # engine = models.CharField(max_length=100, default='slimerjs') # added = models.DateTimeField(auto_now_add=True) # # @classmethod # def get(cls, page): # for each in cls.objects.filter(page=page).order_by('-added'): # return each # # Path: webalyzer/collector/models.py # class Page(models.Model): # domain = models.CharField(max_length=100, db_index=True) # url = models.URLField() # html = models.TextField() # size = models.PositiveIntegerField(default=0) # title = models.TextField(null=True) # added = models.DateTimeField(auto_now_add=True) # modified = models.DateTimeField(auto_now=True) # source_hash = models.IntegerField(default=0, db_index=True) # # def __unicode__(self): # return self.url # # def __repr__(self): # return '<%s: %s %.2fKb>' % ( # self.__class__.__name__, # self.url, # len(self.html) / 1024.0 # ) # # def __len__(self): # return len(self.html) . Output only the next line.
Screenshot.objects.create(
Given snippet: <|code_start|> # from django.conf import settings @contextmanager def tmpdir(*args, **kwargs): dir_ = tempfile.mkdtemp(*args, **kwargs) try: yield dir_ finally: # print "DELETE", dir_ shutil.rmtree(dir_) @shared_task def find_page_title(page_id): <|code_end|> , continue by predicting the next line. Consider current file imports: import os import subprocess import urlparse import shutil import tempfile from contextlib import contextmanager from lxml import etree from lxml.cssselect import CSSSelector from celery import shared_task from django.core.files import File from webalyzer.collected.models import Screenshot from webalyzer.collector.models import Page and context: # Path: webalyzer/collected/models.py # class Screenshot(models.Model): # page = models.ForeignKey(Page) # file = ImageField(upload_to='screenshots') # width = models.PositiveIntegerField() # height = models.PositiveIntegerField() # engine = models.CharField(max_length=100, default='slimerjs') # added = models.DateTimeField(auto_now_add=True) # # @classmethod # def get(cls, page): # for each in cls.objects.filter(page=page).order_by('-added'): # return each # # Path: webalyzer/collector/models.py # class Page(models.Model): # domain = models.CharField(max_length=100, db_index=True) # url = models.URLField() # html = models.TextField() # size = models.PositiveIntegerField(default=0) # title = models.TextField(null=True) # added = models.DateTimeField(auto_now_add=True) # modified = models.DateTimeField(auto_now=True) # source_hash = models.IntegerField(default=0, db_index=True) # # def __unicode__(self): # return self.url # # def __repr__(self): # return '<%s: %s %.2fKb>' % ( # self.__class__.__name__, # self.url, # len(self.html) / 1024.0 # ) # # def __len__(self): # return len(self.html) which might include code, classes, or functions. Output only the next line.
page = Page.objects.get(id=page_id)
Given the code snippet: <|code_start|> urlpatterns = patterns( '', url( '^check/(?P<source_type>[\w]+)/' '(?P<domain>[\w\.]+)/' '(?P<source_hash>[\-\w\.]+)$', <|code_end|> , generate the next line using the imports in this file: from django.conf.urls import patterns, url from webalyzer.collector import views and context (functions, classes, or occasionally code) from other files: # Path: webalyzer/collector/views.py # def collect(request): # def collect_check(request, source_hash, source_type, domain): . Output only the next line.
views.collect_check,
Next line prediction: <|code_start|> .annotate(m=Max('modified')) .order_by('-m') ) context['domains'] = [x['domain'] for x in results] return context @json_view @transaction.atomic def submit(request): if request.method != 'POST': # required_P return redirect(reverse('analyzer:start')) POST = json.loads(request.body) domain = POST['domain'] start_analysis.delay(domain) jobs_ahead = cache.get('jobs_ahead', 0) return { 'jobs_ahead': jobs_ahead, } @json_view def analyzed(request, domain): # from time import sleep # sleep(3) results = Result.objects.filter(domain=domain) if not results.count(): return {'count': 0} <|code_end|> . Use current file imports: (import os import json import difflib import hashlib import tempfile import subprocess import shutil from contextlib import contextmanager from pygments import highlight from pygments.lexers import CssLexer, DiffLexer from pygments.formatters import HtmlFormatter from jsonview.decorators import json_view from django import http from django.shortcuts import render, redirect, get_object_or_404 from django.core.urlresolvers import reverse from django.db.models import Max from django.db import transaction from django.core.cache import cache from webalyzer.collector.models import Page from webalyzer.analyzer.models import Result from .tasks import start_analysis) and context including class names, function names, or small code snippets from other files: # Path: webalyzer/collector/models.py # class Page(models.Model): # domain = models.CharField(max_length=100, db_index=True) # url = models.URLField() # html = models.TextField() # size = models.PositiveIntegerField(default=0) # title = models.TextField(null=True) # added = models.DateTimeField(auto_now_add=True) # modified = models.DateTimeField(auto_now=True) # source_hash = models.IntegerField(default=0, db_index=True) # # def __unicode__(self): # return self.url # # def __repr__(self): # return '<%s: %s %.2fKb>' % ( # self.__class__.__name__, # self.url, # len(self.html) / 1024.0 # ) # # def __len__(self): # return len(self.html) # # Path: webalyzer/analyzer/models.py # class Result(models.Model): # domain = models.CharField(max_length=100, db_index=True) # url = models.URLField() # line = models.PositiveIntegerField(null=True) # link's don't have this # before = models.TextField() # after = models.TextField() # ignored = models.BooleanField(default=False) # modified = models.DateTimeField(auto_now=True) # # @property # def suspects(self): # return Suspect.objects.filter(result=self) # # Path: webalyzer/analyzer/tasks.py # @shared_task # def start_analysis(domain): # pages = Page.objects.filter(domain=domain) # processor = ExtendedProcessor() # t0 = time.time() # for page in pages: # try: # processor.process_html(page.html, page.url) # except DownloadError as err: # print "Failed to downlod on", page.url # print err # raise # t1 = time.time() # processor.process() # t2 = time.time() # print t2-t1 # print t1-t0 # print # # delete all old analysises # Result.objects.filter(domain=domain).delete() # # for inline in processor.inlines: # result = Result.objects.create( # domain=domain, # url=inline.url, # line=inline.line, # before=smart_unicode(inline.before), # after=smart_unicode(inline.after), # ) # selectors = OrderedDict(get_selectors(result.before)) # after = set( # x[0] for x in get_selectors( # result.after # ) # ) # removed_keys = set(selectors.keys()) - after # lines = result.before.splitlines() # # for key in removed_keys: # selector, style = selectors[key] # line = None # for i, line_ in enumerate(lines): # if line_.startswith(selector): # line = i + 1 # break # # Suspect.objects.create( # result=result, # selector=key, # selector_full=selector, # style=style, # line=line # ) # # for link in processor.links: # result = Result.objects.create( # domain=domain, # url=link.href, # before=smart_unicode(link.before), # after=smart_unicode(link.after), # ) # selectors = OrderedDict(get_selectors( # result.before, result.url # )) # after = set( # x[0] for x in get_selectors( # result.after, result.url # ) # ) # removed_keys = set(selectors.keys()) - after # lines = result.before.splitlines() # # for key in removed_keys: # selector, style = selectors[key] # line = None # for i, line_ in enumerate(lines): # if line_.startswith(selector): # line = i + 1 # break # # Suspect.objects.create( # result=result, # selector=key, # selector_full=selector, # style=style, # line=line # ) . Output only the next line.
pages = Page.objects.filter(domain=domain)
Given snippet: <|code_start|> finally: shutil.rmtree(dir_) def prettify_css(css): with tmpfilename(css, 'css') as filename: process = subprocess.Popen( ['crass', filename, '--pretty'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT ) stdout, stderr = process.communicate() if not stdout and stderr: raise Exception(stderr) # ??? return stdout def index(request, *args, **kwargs): # the *args, **kwargs is because this view is used in urls.py # as a catch-all for the sake of pushstate context = {} html_formatter = HtmlFormatter(linenos=True) context['pygments_css'] = html_formatter.get_style_defs('.highlight') return render(request, 'analyzer/index.html', context) @json_view def recent_submissions(request): context = {} results = ( <|code_end|> , continue by predicting the next line. Consider current file imports: import os import json import difflib import hashlib import tempfile import subprocess import shutil from contextlib import contextmanager from pygments import highlight from pygments.lexers import CssLexer, DiffLexer from pygments.formatters import HtmlFormatter from jsonview.decorators import json_view from django import http from django.shortcuts import render, redirect, get_object_or_404 from django.core.urlresolvers import reverse from django.db.models import Max from django.db import transaction from django.core.cache import cache from webalyzer.collector.models import Page from webalyzer.analyzer.models import Result from .tasks import start_analysis and context: # Path: webalyzer/collector/models.py # class Page(models.Model): # domain = models.CharField(max_length=100, db_index=True) # url = models.URLField() # html = models.TextField() # size = models.PositiveIntegerField(default=0) # title = models.TextField(null=True) # added = models.DateTimeField(auto_now_add=True) # modified = models.DateTimeField(auto_now=True) # source_hash = models.IntegerField(default=0, db_index=True) # # def __unicode__(self): # return self.url # # def __repr__(self): # return '<%s: %s %.2fKb>' % ( # self.__class__.__name__, # self.url, # len(self.html) / 1024.0 # ) # # def __len__(self): # return len(self.html) # # Path: webalyzer/analyzer/models.py # class Result(models.Model): # domain = models.CharField(max_length=100, db_index=True) # url = models.URLField() # line = models.PositiveIntegerField(null=True) # link's don't have this # before = models.TextField() # after = models.TextField() # ignored = models.BooleanField(default=False) # modified = models.DateTimeField(auto_now=True) # # @property # def suspects(self): # return Suspect.objects.filter(result=self) # # Path: webalyzer/analyzer/tasks.py # @shared_task # def start_analysis(domain): # pages = Page.objects.filter(domain=domain) # processor = ExtendedProcessor() # t0 = time.time() # for page in pages: # try: # processor.process_html(page.html, page.url) # except DownloadError as err: # print "Failed to downlod on", page.url # print err # raise # t1 = time.time() # processor.process() # t2 = time.time() # print t2-t1 # print t1-t0 # print # # delete all old analysises # Result.objects.filter(domain=domain).delete() # # for inline in processor.inlines: # result = Result.objects.create( # domain=domain, # url=inline.url, # line=inline.line, # before=smart_unicode(inline.before), # after=smart_unicode(inline.after), # ) # selectors = OrderedDict(get_selectors(result.before)) # after = set( # x[0] for x in get_selectors( # result.after # ) # ) # removed_keys = set(selectors.keys()) - after # lines = result.before.splitlines() # # for key in removed_keys: # selector, style = selectors[key] # line = None # for i, line_ in enumerate(lines): # if line_.startswith(selector): # line = i + 1 # break # # Suspect.objects.create( # result=result, # selector=key, # selector_full=selector, # style=style, # line=line # ) # # for link in processor.links: # result = Result.objects.create( # domain=domain, # url=link.href, # before=smart_unicode(link.before), # after=smart_unicode(link.after), # ) # selectors = OrderedDict(get_selectors( # result.before, result.url # )) # after = set( # x[0] for x in get_selectors( # result.after, result.url # ) # ) # removed_keys = set(selectors.keys()) - after # lines = result.before.splitlines() # # for key in removed_keys: # selector, style = selectors[key] # line = None # for i, line_ in enumerate(lines): # if line_.startswith(selector): # line = i + 1 # break # # Suspect.objects.create( # result=result, # selector=key, # selector_full=selector, # style=style, # line=line # ) which might include code, classes, or functions. Output only the next line.
Result.objects.values('domain')
Here is a snippet: <|code_start|> def index(request, *args, **kwargs): # the *args, **kwargs is because this view is used in urls.py # as a catch-all for the sake of pushstate context = {} html_formatter = HtmlFormatter(linenos=True) context['pygments_css'] = html_formatter.get_style_defs('.highlight') return render(request, 'analyzer/index.html', context) @json_view def recent_submissions(request): context = {} results = ( Result.objects.values('domain') .annotate(m=Max('modified')) .order_by('-m') ) context['domains'] = [x['domain'] for x in results] return context @json_view @transaction.atomic def submit(request): if request.method != 'POST': # required_P return redirect(reverse('analyzer:start')) POST = json.loads(request.body) domain = POST['domain'] <|code_end|> . Write the next line using the current file imports: import os import json import difflib import hashlib import tempfile import subprocess import shutil from contextlib import contextmanager from pygments import highlight from pygments.lexers import CssLexer, DiffLexer from pygments.formatters import HtmlFormatter from jsonview.decorators import json_view from django import http from django.shortcuts import render, redirect, get_object_or_404 from django.core.urlresolvers import reverse from django.db.models import Max from django.db import transaction from django.core.cache import cache from webalyzer.collector.models import Page from webalyzer.analyzer.models import Result from .tasks import start_analysis and context from other files: # Path: webalyzer/collector/models.py # class Page(models.Model): # domain = models.CharField(max_length=100, db_index=True) # url = models.URLField() # html = models.TextField() # size = models.PositiveIntegerField(default=0) # title = models.TextField(null=True) # added = models.DateTimeField(auto_now_add=True) # modified = models.DateTimeField(auto_now=True) # source_hash = models.IntegerField(default=0, db_index=True) # # def __unicode__(self): # return self.url # # def __repr__(self): # return '<%s: %s %.2fKb>' % ( # self.__class__.__name__, # self.url, # len(self.html) / 1024.0 # ) # # def __len__(self): # return len(self.html) # # Path: webalyzer/analyzer/models.py # class Result(models.Model): # domain = models.CharField(max_length=100, db_index=True) # url = models.URLField() # line = models.PositiveIntegerField(null=True) # link's don't have this # before = models.TextField() # after = models.TextField() # ignored = models.BooleanField(default=False) # modified = models.DateTimeField(auto_now=True) # # @property # def suspects(self): # return Suspect.objects.filter(result=self) # # Path: webalyzer/analyzer/tasks.py # @shared_task # def start_analysis(domain): # pages = Page.objects.filter(domain=domain) # processor = ExtendedProcessor() # t0 = time.time() # for page in pages: # try: # processor.process_html(page.html, page.url) # except DownloadError as err: # print "Failed to downlod on", page.url # print err # raise # t1 = time.time() # processor.process() # t2 = time.time() # print t2-t1 # print t1-t0 # print # # delete all old analysises # Result.objects.filter(domain=domain).delete() # # for inline in processor.inlines: # result = Result.objects.create( # domain=domain, # url=inline.url, # line=inline.line, # before=smart_unicode(inline.before), # after=smart_unicode(inline.after), # ) # selectors = OrderedDict(get_selectors(result.before)) # after = set( # x[0] for x in get_selectors( # result.after # ) # ) # removed_keys = set(selectors.keys()) - after # lines = result.before.splitlines() # # for key in removed_keys: # selector, style = selectors[key] # line = None # for i, line_ in enumerate(lines): # if line_.startswith(selector): # line = i + 1 # break # # Suspect.objects.create( # result=result, # selector=key, # selector_full=selector, # style=style, # line=line # ) # # for link in processor.links: # result = Result.objects.create( # domain=domain, # url=link.href, # before=smart_unicode(link.before), # after=smart_unicode(link.after), # ) # selectors = OrderedDict(get_selectors( # result.before, result.url # )) # after = set( # x[0] for x in get_selectors( # result.after, result.url # ) # ) # removed_keys = set(selectors.keys()) - after # lines = result.before.splitlines() # # for key in removed_keys: # selector, style = selectors[key] # line = None # for i, line_ in enumerate(lines): # if line_.startswith(selector): # line = i + 1 # break # # Suspect.objects.create( # result=result, # selector=key, # selector_full=selector, # style=style, # line=line # ) , which may include functions, classes, or code. Output only the next line.
start_analysis.delay(domain)
Next line prediction: <|code_start|> @shared_task def start_analysis(domain): pages = Page.objects.filter(domain=domain) processor = ExtendedProcessor() t0 = time.time() for page in pages: try: processor.process_html(page.html, page.url) except DownloadError as err: print "Failed to downlod on", page.url print err raise t1 = time.time() processor.process() t2 = time.time() print t2-t1 print t1-t0 print # delete all old analysises <|code_end|> . Use current file imports: (import os import stat import codecs import hashlib import tempfile import time import requests import cssutils from collections import OrderedDict from django.utils.encoding import smart_unicode from django.conf import settings from celery import shared_task from mincss.processor import Processor, DownloadError from webalyzer.collector.models import Page from webalyzer.analyzer.models import Result, Suspect) and context including class names, function names, or small code snippets from other files: # Path: webalyzer/collector/models.py # class Page(models.Model): # domain = models.CharField(max_length=100, db_index=True) # url = models.URLField() # html = models.TextField() # size = models.PositiveIntegerField(default=0) # title = models.TextField(null=True) # added = models.DateTimeField(auto_now_add=True) # modified = models.DateTimeField(auto_now=True) # source_hash = models.IntegerField(default=0, db_index=True) # # def __unicode__(self): # return self.url # # def __repr__(self): # return '<%s: %s %.2fKb>' % ( # self.__class__.__name__, # self.url, # len(self.html) / 1024.0 # ) # # def __len__(self): # return len(self.html) # # Path: webalyzer/analyzer/models.py # class Result(models.Model): # domain = models.CharField(max_length=100, db_index=True) # url = models.URLField() # line = models.PositiveIntegerField(null=True) # link's don't have this # before = models.TextField() # after = models.TextField() # ignored = models.BooleanField(default=False) # modified = models.DateTimeField(auto_now=True) # # @property # def suspects(self): # return Suspect.objects.filter(result=self) # # class Suspect(models.Model): # result = models.ForeignKey(Result) # selector = models.TextField() # # useful when the selector appears in a bundle with other selectors # selector_full = models.TextField() # style = models.TextField() # line = models.PositiveIntegerField(null=True) # null if it goes wrong # modified = models.DateTimeField(auto_now=True) # # class Meta: # ordering = ('modified',) # # @property # def size(self): # return len(self.style) . Output only the next line.
Result.objects.filter(domain=domain).delete()
Predict the next line after this snippet: <|code_start|> print t1-t0 print # delete all old analysises Result.objects.filter(domain=domain).delete() for inline in processor.inlines: result = Result.objects.create( domain=domain, url=inline.url, line=inline.line, before=smart_unicode(inline.before), after=smart_unicode(inline.after), ) selectors = OrderedDict(get_selectors(result.before)) after = set( x[0] for x in get_selectors( result.after ) ) removed_keys = set(selectors.keys()) - after lines = result.before.splitlines() for key in removed_keys: selector, style = selectors[key] line = None for i, line_ in enumerate(lines): if line_.startswith(selector): line = i + 1 break <|code_end|> using the current file's imports: import os import stat import codecs import hashlib import tempfile import time import requests import cssutils from collections import OrderedDict from django.utils.encoding import smart_unicode from django.conf import settings from celery import shared_task from mincss.processor import Processor, DownloadError from webalyzer.collector.models import Page from webalyzer.analyzer.models import Result, Suspect and any relevant context from other files: # Path: webalyzer/collector/models.py # class Page(models.Model): # domain = models.CharField(max_length=100, db_index=True) # url = models.URLField() # html = models.TextField() # size = models.PositiveIntegerField(default=0) # title = models.TextField(null=True) # added = models.DateTimeField(auto_now_add=True) # modified = models.DateTimeField(auto_now=True) # source_hash = models.IntegerField(default=0, db_index=True) # # def __unicode__(self): # return self.url # # def __repr__(self): # return '<%s: %s %.2fKb>' % ( # self.__class__.__name__, # self.url, # len(self.html) / 1024.0 # ) # # def __len__(self): # return len(self.html) # # Path: webalyzer/analyzer/models.py # class Result(models.Model): # domain = models.CharField(max_length=100, db_index=True) # url = models.URLField() # line = models.PositiveIntegerField(null=True) # link's don't have this # before = models.TextField() # after = models.TextField() # ignored = models.BooleanField(default=False) # modified = models.DateTimeField(auto_now=True) # # @property # def suspects(self): # return Suspect.objects.filter(result=self) # # class Suspect(models.Model): # result = models.ForeignKey(Result) # selector = models.TextField() # # useful when the selector appears in a bundle with other selectors # selector_full = models.TextField() # style = models.TextField() # line = models.PositiveIntegerField(null=True) # null if it goes wrong # modified = models.DateTimeField(auto_now=True) # # class Meta: # ordering = ('modified',) # # @property # def size(self): # return len(self.style) . Output only the next line.
Suspect.objects.create(
Given the following code snippet before the placeholder: <|code_start|> def index(request, *args, **kwargs): # the *args, **kwargs is because this view is used in urls.py # as a catch-all for the sake of pushstate context = {} # html_formatter = HtmlFormatter(linenos=True) # context['pygments_css'] = html_formatter.get_style_defs('.highlight') return render(request, 'collected/index.html', context) @json_view def recently_collected_domains(request): # TODO this'll be based on auth or something instead context = {} results = ( <|code_end|> , predict the next line using imports from the current file: import time from jsonview.decorators import json_view from sorl.thumbnail import get_thumbnail from django import http from django.shortcuts import render, get_object_or_404 from django.db.models import Sum, Max from django.core.cache import cache from django.core.paginator import Paginator from webalyzer.collector.models import Page from webalyzer.collected.models import Screenshot from .tasks import find_page_title, generate_screenshot and context including class names, function names, and sometimes code from other files: # Path: webalyzer/collector/models.py # class Page(models.Model): # domain = models.CharField(max_length=100, db_index=True) # url = models.URLField() # html = models.TextField() # size = models.PositiveIntegerField(default=0) # title = models.TextField(null=True) # added = models.DateTimeField(auto_now_add=True) # modified = models.DateTimeField(auto_now=True) # source_hash = models.IntegerField(default=0, db_index=True) # # def __unicode__(self): # return self.url # # def __repr__(self): # return '<%s: %s %.2fKb>' % ( # self.__class__.__name__, # self.url, # len(self.html) / 1024.0 # ) # # def __len__(self): # return len(self.html) # # Path: webalyzer/collected/models.py # class Screenshot(models.Model): # page = models.ForeignKey(Page) # file = ImageField(upload_to='screenshots') # width = models.PositiveIntegerField() # height = models.PositiveIntegerField() # engine = models.CharField(max_length=100, default='slimerjs') # added = models.DateTimeField(auto_now_add=True) # # @classmethod # def get(cls, page): # for each in cls.objects.filter(page=page).order_by('-added'): # return each # # Path: webalyzer/collected/tasks.py # @shared_task # def find_page_title(page_id): # page = Page.objects.get(id=page_id) # parser = etree.HTMLParser() # html = page.html.strip() # tree = etree.fromstring(html, parser).getroottree() # dom = tree.getroot() # # for element in CSSSelector('title')(dom): # page.title = element.text.strip() # page.save() # return # # @shared_task # def generate_screenshot(page_id): # print "Generating screenshot for", page_id # page = Page.objects.get(id=page_id) # parser = etree.HTMLParser() # html = page.html.strip() # if not html.lower().startswith('<!doctype'): # html = '<!doctype html>\n' + html # tree = etree.fromstring(html, parser).getroottree() # dom = tree.getroot() # # lxml inserts a doctype if none exists, so only include it in # # the root if it was in the original html. # root = tree if html.startswith(tree.docinfo.doctype) else dom # # # remove all scripts # for script in CSSSelector('script')(dom): # script.getparent().remove(script) # for element in CSSSelector('img[src]')(dom): # element.attrib['src'] = urlparse.urljoin( # page.url, # element.attrib['src'] # ) # for element in CSSSelector('link[href]')(dom): # if not element.attrib.get('rel') == 'stylesheet': # continue # element.attrib['href'] = urlparse.urljoin( # page.url, # element.attrib['href'] # ) # # with tmpdir(str(page.id)) as dir_: # html_file = os.path.join( # dir_, # 'page-{}.html'.format(page.id) # ) # png_file = os.path.join( # dir_, # 'screenshot-{}.png'.format(page.id) # ) # with open(html_file, 'w') as f: # f.write('<!doctype html>\n') # f.write(etree.tostring( # root, # pretty_print=False, # method='html', # encoding='utf-8', # )) # # # that 'screenshot.js' file is in the same directory as this file # _here = os.path.dirname(__file__) # width, height = 1400, 900 # cmd = [ # 'phantomjs', # '--ignore-ssl-errors=yes', # os.path.join(_here, 'screenshot.js'), # html_file, # png_file, # str(width), # str(height) # ] # # print cmd # process = subprocess.Popen( # cmd, # stdout=subprocess.PIPE, # stderr=subprocess.PIPE # ) # stdout, stderr = process.communicate() # # print (stdout, stderr) # if not os.path.isfile(png_file): # raise Exception("No PNG file created") # # with open(png_file, 'rb') as f: # Screenshot.objects.create( # page=page, # file=File(f), # width=width, # height=height, # engine='phantomjs' # ) . Output only the next line.
Page.objects.values('domain')
Given the following code snippet before the placeholder: <|code_start|> # context['results'] = all_results context['pages_count'] = pages.count() p = Paginator(pages.order_by('-modified'), 10) page = int(request.GET.get('page', 1)) some_pages = [] missing_titles = [] for page in p.page(page).object_list: some_pages.append({ 'id': page.id, 'url': page.url, 'title': page.title, 'size': page.size, 'added': page.added.isoformat(), 'modified': page.modified.isoformat(), }) if page.title is None: missing_titles.append(page.id) find_page_title.delay(page.id) # find_page_title(page.id) context['pages'] = some_pages context['missing_title'] = missing_titles return context def page_thumbnail(request, domain, id): dimensions = request.GET.get('dimensions') page = get_object_or_404(Page, domain=domain, id=id) <|code_end|> , predict the next line using imports from the current file: import time from jsonview.decorators import json_view from sorl.thumbnail import get_thumbnail from django import http from django.shortcuts import render, get_object_or_404 from django.db.models import Sum, Max from django.core.cache import cache from django.core.paginator import Paginator from webalyzer.collector.models import Page from webalyzer.collected.models import Screenshot from .tasks import find_page_title, generate_screenshot and context including class names, function names, and sometimes code from other files: # Path: webalyzer/collector/models.py # class Page(models.Model): # domain = models.CharField(max_length=100, db_index=True) # url = models.URLField() # html = models.TextField() # size = models.PositiveIntegerField(default=0) # title = models.TextField(null=True) # added = models.DateTimeField(auto_now_add=True) # modified = models.DateTimeField(auto_now=True) # source_hash = models.IntegerField(default=0, db_index=True) # # def __unicode__(self): # return self.url # # def __repr__(self): # return '<%s: %s %.2fKb>' % ( # self.__class__.__name__, # self.url, # len(self.html) / 1024.0 # ) # # def __len__(self): # return len(self.html) # # Path: webalyzer/collected/models.py # class Screenshot(models.Model): # page = models.ForeignKey(Page) # file = ImageField(upload_to='screenshots') # width = models.PositiveIntegerField() # height = models.PositiveIntegerField() # engine = models.CharField(max_length=100, default='slimerjs') # added = models.DateTimeField(auto_now_add=True) # # @classmethod # def get(cls, page): # for each in cls.objects.filter(page=page).order_by('-added'): # return each # # Path: webalyzer/collected/tasks.py # @shared_task # def find_page_title(page_id): # page = Page.objects.get(id=page_id) # parser = etree.HTMLParser() # html = page.html.strip() # tree = etree.fromstring(html, parser).getroottree() # dom = tree.getroot() # # for element in CSSSelector('title')(dom): # page.title = element.text.strip() # page.save() # return # # @shared_task # def generate_screenshot(page_id): # print "Generating screenshot for", page_id # page = Page.objects.get(id=page_id) # parser = etree.HTMLParser() # html = page.html.strip() # if not html.lower().startswith('<!doctype'): # html = '<!doctype html>\n' + html # tree = etree.fromstring(html, parser).getroottree() # dom = tree.getroot() # # lxml inserts a doctype if none exists, so only include it in # # the root if it was in the original html. # root = tree if html.startswith(tree.docinfo.doctype) else dom # # # remove all scripts # for script in CSSSelector('script')(dom): # script.getparent().remove(script) # for element in CSSSelector('img[src]')(dom): # element.attrib['src'] = urlparse.urljoin( # page.url, # element.attrib['src'] # ) # for element in CSSSelector('link[href]')(dom): # if not element.attrib.get('rel') == 'stylesheet': # continue # element.attrib['href'] = urlparse.urljoin( # page.url, # element.attrib['href'] # ) # # with tmpdir(str(page.id)) as dir_: # html_file = os.path.join( # dir_, # 'page-{}.html'.format(page.id) # ) # png_file = os.path.join( # dir_, # 'screenshot-{}.png'.format(page.id) # ) # with open(html_file, 'w') as f: # f.write('<!doctype html>\n') # f.write(etree.tostring( # root, # pretty_print=False, # method='html', # encoding='utf-8', # )) # # # that 'screenshot.js' file is in the same directory as this file # _here = os.path.dirname(__file__) # width, height = 1400, 900 # cmd = [ # 'phantomjs', # '--ignore-ssl-errors=yes', # os.path.join(_here, 'screenshot.js'), # html_file, # png_file, # str(width), # str(height) # ] # # print cmd # process = subprocess.Popen( # cmd, # stdout=subprocess.PIPE, # stderr=subprocess.PIPE # ) # stdout, stderr = process.communicate() # # print (stdout, stderr) # if not os.path.isfile(png_file): # raise Exception("No PNG file created") # # with open(png_file, 'rb') as f: # Screenshot.objects.create( # page=page, # file=File(f), # width=width, # height=height, # engine='phantomjs' # ) . Output only the next line.
screenshot = Screenshot.get(page)
Given the code snippet: <|code_start|> .order_by('-m') ) context['domains'] = [x['domain'] for x in results] return context @json_view def collected_pages(request, domain): pages = Page.objects.filter(domain=domain) context = {} context['total_html_size'] = pages.aggregate(Sum('size'))['size__sum'] context['domain'] = domain # context['results'] = all_results context['pages_count'] = pages.count() p = Paginator(pages.order_by('-modified'), 10) page = int(request.GET.get('page', 1)) some_pages = [] missing_titles = [] for page in p.page(page).object_list: some_pages.append({ 'id': page.id, 'url': page.url, 'title': page.title, 'size': page.size, 'added': page.added.isoformat(), 'modified': page.modified.isoformat(), }) if page.title is None: missing_titles.append(page.id) <|code_end|> , generate the next line using the imports in this file: import time from jsonview.decorators import json_view from sorl.thumbnail import get_thumbnail from django import http from django.shortcuts import render, get_object_or_404 from django.db.models import Sum, Max from django.core.cache import cache from django.core.paginator import Paginator from webalyzer.collector.models import Page from webalyzer.collected.models import Screenshot from .tasks import find_page_title, generate_screenshot and context (functions, classes, or occasionally code) from other files: # Path: webalyzer/collector/models.py # class Page(models.Model): # domain = models.CharField(max_length=100, db_index=True) # url = models.URLField() # html = models.TextField() # size = models.PositiveIntegerField(default=0) # title = models.TextField(null=True) # added = models.DateTimeField(auto_now_add=True) # modified = models.DateTimeField(auto_now=True) # source_hash = models.IntegerField(default=0, db_index=True) # # def __unicode__(self): # return self.url # # def __repr__(self): # return '<%s: %s %.2fKb>' % ( # self.__class__.__name__, # self.url, # len(self.html) / 1024.0 # ) # # def __len__(self): # return len(self.html) # # Path: webalyzer/collected/models.py # class Screenshot(models.Model): # page = models.ForeignKey(Page) # file = ImageField(upload_to='screenshots') # width = models.PositiveIntegerField() # height = models.PositiveIntegerField() # engine = models.CharField(max_length=100, default='slimerjs') # added = models.DateTimeField(auto_now_add=True) # # @classmethod # def get(cls, page): # for each in cls.objects.filter(page=page).order_by('-added'): # return each # # Path: webalyzer/collected/tasks.py # @shared_task # def find_page_title(page_id): # page = Page.objects.get(id=page_id) # parser = etree.HTMLParser() # html = page.html.strip() # tree = etree.fromstring(html, parser).getroottree() # dom = tree.getroot() # # for element in CSSSelector('title')(dom): # page.title = element.text.strip() # page.save() # return # # @shared_task # def generate_screenshot(page_id): # print "Generating screenshot for", page_id # page = Page.objects.get(id=page_id) # parser = etree.HTMLParser() # html = page.html.strip() # if not html.lower().startswith('<!doctype'): # html = '<!doctype html>\n' + html # tree = etree.fromstring(html, parser).getroottree() # dom = tree.getroot() # # lxml inserts a doctype if none exists, so only include it in # # the root if it was in the original html. # root = tree if html.startswith(tree.docinfo.doctype) else dom # # # remove all scripts # for script in CSSSelector('script')(dom): # script.getparent().remove(script) # for element in CSSSelector('img[src]')(dom): # element.attrib['src'] = urlparse.urljoin( # page.url, # element.attrib['src'] # ) # for element in CSSSelector('link[href]')(dom): # if not element.attrib.get('rel') == 'stylesheet': # continue # element.attrib['href'] = urlparse.urljoin( # page.url, # element.attrib['href'] # ) # # with tmpdir(str(page.id)) as dir_: # html_file = os.path.join( # dir_, # 'page-{}.html'.format(page.id) # ) # png_file = os.path.join( # dir_, # 'screenshot-{}.png'.format(page.id) # ) # with open(html_file, 'w') as f: # f.write('<!doctype html>\n') # f.write(etree.tostring( # root, # pretty_print=False, # method='html', # encoding='utf-8', # )) # # # that 'screenshot.js' file is in the same directory as this file # _here = os.path.dirname(__file__) # width, height = 1400, 900 # cmd = [ # 'phantomjs', # '--ignore-ssl-errors=yes', # os.path.join(_here, 'screenshot.js'), # html_file, # png_file, # str(width), # str(height) # ] # # print cmd # process = subprocess.Popen( # cmd, # stdout=subprocess.PIPE, # stderr=subprocess.PIPE # ) # stdout, stderr = process.communicate() # # print (stdout, stderr) # if not os.path.isfile(png_file): # raise Exception("No PNG file created") # # with open(png_file, 'rb') as f: # Screenshot.objects.create( # page=page, # file=File(f), # width=width, # height=height, # engine='phantomjs' # ) . Output only the next line.
find_page_title.delay(page.id)
Given snippet: <|code_start|> context['pages'] = some_pages context['missing_title'] = missing_titles return context def page_thumbnail(request, domain, id): dimensions = request.GET.get('dimensions') page = get_object_or_404(Page, domain=domain, id=id) screenshot = Screenshot.get(page) if screenshot: if dimensions: thumb = get_thumbnail( screenshot.file, dimensions, # crop='center', crop='top', quality=80, ) r = http.HttpResponse(content_type='image/png') r.write(thumb.read()) return r else: return http.FileResponse(screenshot.file, content_type='image/png') else: cache_key = 'generating_screenshot_{}'.format(page.id) if not cache.get(cache_key): cache.set(cache_key, str(time.time()), 60) <|code_end|> , continue by predicting the next line. Consider current file imports: import time from jsonview.decorators import json_view from sorl.thumbnail import get_thumbnail from django import http from django.shortcuts import render, get_object_or_404 from django.db.models import Sum, Max from django.core.cache import cache from django.core.paginator import Paginator from webalyzer.collector.models import Page from webalyzer.collected.models import Screenshot from .tasks import find_page_title, generate_screenshot and context: # Path: webalyzer/collector/models.py # class Page(models.Model): # domain = models.CharField(max_length=100, db_index=True) # url = models.URLField() # html = models.TextField() # size = models.PositiveIntegerField(default=0) # title = models.TextField(null=True) # added = models.DateTimeField(auto_now_add=True) # modified = models.DateTimeField(auto_now=True) # source_hash = models.IntegerField(default=0, db_index=True) # # def __unicode__(self): # return self.url # # def __repr__(self): # return '<%s: %s %.2fKb>' % ( # self.__class__.__name__, # self.url, # len(self.html) / 1024.0 # ) # # def __len__(self): # return len(self.html) # # Path: webalyzer/collected/models.py # class Screenshot(models.Model): # page = models.ForeignKey(Page) # file = ImageField(upload_to='screenshots') # width = models.PositiveIntegerField() # height = models.PositiveIntegerField() # engine = models.CharField(max_length=100, default='slimerjs') # added = models.DateTimeField(auto_now_add=True) # # @classmethod # def get(cls, page): # for each in cls.objects.filter(page=page).order_by('-added'): # return each # # Path: webalyzer/collected/tasks.py # @shared_task # def find_page_title(page_id): # page = Page.objects.get(id=page_id) # parser = etree.HTMLParser() # html = page.html.strip() # tree = etree.fromstring(html, parser).getroottree() # dom = tree.getroot() # # for element in CSSSelector('title')(dom): # page.title = element.text.strip() # page.save() # return # # @shared_task # def generate_screenshot(page_id): # print "Generating screenshot for", page_id # page = Page.objects.get(id=page_id) # parser = etree.HTMLParser() # html = page.html.strip() # if not html.lower().startswith('<!doctype'): # html = '<!doctype html>\n' + html # tree = etree.fromstring(html, parser).getroottree() # dom = tree.getroot() # # lxml inserts a doctype if none exists, so only include it in # # the root if it was in the original html. # root = tree if html.startswith(tree.docinfo.doctype) else dom # # # remove all scripts # for script in CSSSelector('script')(dom): # script.getparent().remove(script) # for element in CSSSelector('img[src]')(dom): # element.attrib['src'] = urlparse.urljoin( # page.url, # element.attrib['src'] # ) # for element in CSSSelector('link[href]')(dom): # if not element.attrib.get('rel') == 'stylesheet': # continue # element.attrib['href'] = urlparse.urljoin( # page.url, # element.attrib['href'] # ) # # with tmpdir(str(page.id)) as dir_: # html_file = os.path.join( # dir_, # 'page-{}.html'.format(page.id) # ) # png_file = os.path.join( # dir_, # 'screenshot-{}.png'.format(page.id) # ) # with open(html_file, 'w') as f: # f.write('<!doctype html>\n') # f.write(etree.tostring( # root, # pretty_print=False, # method='html', # encoding='utf-8', # )) # # # that 'screenshot.js' file is in the same directory as this file # _here = os.path.dirname(__file__) # width, height = 1400, 900 # cmd = [ # 'phantomjs', # '--ignore-ssl-errors=yes', # os.path.join(_here, 'screenshot.js'), # html_file, # png_file, # str(width), # str(height) # ] # # print cmd # process = subprocess.Popen( # cmd, # stdout=subprocess.PIPE, # stderr=subprocess.PIPE # ) # stdout, stderr = process.communicate() # # print (stdout, stderr) # if not os.path.isfile(png_file): # raise Exception("No PNG file created") # # with open(png_file, 'rb') as f: # Screenshot.objects.create( # page=page, # file=File(f), # width=width, # height=height, # engine='phantomjs' # ) which might include code, classes, or functions. Output only the next line.
generate_screenshot.delay(page.id)
Here is a snippet: <|code_start|> def pause(self): """Pause thread""" self._advance.clear() def unpause(self): """Unpause thread""" self._advance.set() def process(self, dirobj): """Process dirobj""" self._queue.put(dirobj) self._awoken.set() # Backend imports class BzrRoot(VcsRoot, Bzr): """Bzr root""" class GitRoot(VcsRoot, Git): """Git root""" class HgRoot(VcsRoot, Hg): """Hg root""" <|code_end|> . Write the next line using the current file imports: import os import subprocess import threading import time import queue import Queue as queue # pylint: disable=import-error from io import open from ranger.ext import spawn from .bzr import Bzr # NOQA pylint: disable=wrong-import-position from .git import Git # NOQA pylint: disable=wrong-import-position from .hg import Hg # NOQA pylint: disable=wrong-import-position from .svn import SVN # NOQA pylint: disable=wrong-import-position and context from other files: # Path: ranger/ext/spawn.py # def spawn(*popenargs, **kwargs): # """Runs a program, waits for its termination and returns its stdout # # This function is similar to python 2.7's subprocess.check_output, # but is favored due to python 2.6 compatibility. # # The arguments may be: # # spawn(string) # spawn(command, arg1, arg2...) # spawn([command, arg1, arg2]) # # Will be run through a shell if `popenargs` is a string, otherwise the command # is executed directly. # # The keyword argument `decode` determines if the output shall be decoded # with the encoding UTF-8. # # Further keyword arguments are passed to Popen. # """ # if len(popenargs) == 1: # return check_output(popenargs[0], **kwargs) # return check_output(list(popenargs), **kwargs) # # Path: ranger/ext/vcs/svn.py # class SVN(Vcs): # """VCS implementation for Subversion""" # # Generic # _status_translations = ( # ('ADR', 'staged'), # ('C', 'conflict'), # ('I', 'ignored'), # ('M~', 'changed'), # ('X', 'none'), # ('?', 'untracked'), # ('!', 'deleted'), # ) # # def _log(self, refspec=None, maxres=None, filelist=None): # """Retrieves log message and parses it""" # args = ['log', '--xml'] # # if refspec: # args += ['--limit', '1', '--revision', refspec] # elif maxres: # args += ['--limit', str(maxres)] # # if filelist: # args += ['--'] + filelist # # try: # output = self._run(args) # except VcsError: # return None # if not output: # return None # # log = [] # for entry in etree.fromstring(output).findall('./logentry'): # new = {} # new['short'] = entry.get('revision') # new['revid'] = entry.get('revision') # new['author'] = entry.find('./author').text # new['date'] = datetime.strptime( # entry.find('./date').text, # '%Y-%m-%dT%H:%M:%S.%fZ', # ) # new['summary'] = entry.find('./msg').text.split('\n')[0] # log.append(new) # return log # # def _status_translate(self, code): # """Translate status code""" # for code_x, status in self._status_translations: # if code in code_x: # return status # return 'unknown' # # def _remote_url(self): # """Remote url""" # try: # output = self._run(['info', '--xml']) # except VcsError: # return None # if not output: # return None # return etree.fromstring(output).find('./entry/url').text or None # # # Action Interface # # def action_add(self, filelist=None): # args = ['add'] # if filelist: # args += ['--'] + filelist # self._run(args, catchout=False) # # def action_reset(self, filelist=None): # args = ['revert', '--'] # if filelist: # args += filelist # else: # args += self.rootvcs.status_subpaths.keys() # pylint: disable=no-member # self._run(args, catchout=False) # # # Data Interface # # def data_status_root(self): # statuses = set() # # # Paths with status # lines = self._run(['status']).split('\n') # lines = list(filter(None, lines)) # if not lines: # return 'sync' # for line in lines: # code = line[0] # if code == ' ': # continue # statuses.add(self._status_translate(code)) # # for status in self.DIRSTATUSES: # if status in statuses: # return status # return 'sync' # # def data_status_subpaths(self): # statuses = {} # # # Paths with status # lines = self._run(['status']).split('\n') # lines = list(filter(None, lines)) # for line in lines: # code, path = line[0], line[8:] # if code == ' ': # continue # statuses[os.path.normpath(path)] = self._status_translate(code) # # return statuses # # def data_status_remote(self): # remote = self._remote_url() # if remote is None or remote.startswith('file://'): # return 'none' # return 'unknown' # # def data_branch(self): # return None # # def data_info(self, rev=None): # if rev is None: # rev = self.HEAD # # log = self._log(refspec=rev) # if not log: # if rev == self.HEAD: # return None # else: # raise VcsError('Revision {0:s} does not exist'.format(rev)) # elif len(log) == 1: # return log[0] # else: # raise VcsError('More than one instance of revision {0:s}'.format(rev)) , which may include functions, classes, or code. Output only the next line.
class SVNRoot(VcsRoot, SVN):
Using the snippet: <|code_start|># -*- encoding: utf-8 -*- # This file is part of ranger, the console file manager. # License: GNU GPL version 3, see the file "AUTHORS" for details. from __future__ import (absolute_import, division, print_function) ASCIIONLY = set(chr(c) for c in range(1, 128)) NARROW = 1 WIDE = 2 WIDE_SYMBOLS = set('WF') def uwid(string): """Return the width of a string""" <|code_end|> , determine the next line of code. You have imports: import sys import doctest from unicodedata import east_asian_width from ranger import PY3 and context (class names, function names, or code) available: # Path: ranger.py # ARGV = sys.argv[1:sys.argv.index('--')] if '--' in sys.argv else sys.argv[1:] . Output only the next line.
if not PY3:
Given the following code snippet before the placeholder: <|code_start|># This file is part of ranger, the console file manager. # License: GNU GPL version 3, see the file "AUTHORS" for details. from __future__ import (absolute_import, division, print_function) N_FIRST_BYTES = 256 CONTROL_CHARACTERS = set(list(range(0, 9)) + list(range(14, 32))) <|code_end|> , predict the next line using imports from the current file: import re from ranger import PY3 from ranger.container.fsobject import FileSystemObject and context including class names, function names, and sometimes code from other files: # Path: ranger.py # ARGV = sys.argv[1:sys.argv.index('--')] if '--' in sys.argv else sys.argv[1:] . Output only the next line.
if not PY3:
Given the following code snippet before the placeholder: <|code_start|># This file is part of ranger, the console file manager. # License: GNU GPL version 3, see the file "AUTHORS" for details. # TODO: Add an optional "!" to all commands and set a flag if it's there from __future__ import (absolute_import, division, print_function) __all__ = ['Command', 'LinemodeBase', 'hook_init', 'hook_ready', 'register_linemode'] # COMPAT _SETTINGS_RE = re.compile(r'^\s*([^\s]+?)=(.*)$') _ALIAS_LINE_RE = re.compile(r'(\s+)') def _command_init(cls): # Escape macros for tab completion if cls.resolve_macros: tab_old = cls.tab def tab(self, tabnum): results = tab_old(self, tabnum) if results is None: return None elif isinstance(results, str): <|code_end|> , predict the next line using imports from the current file: import os import re import ranger import logging import doctest import sys from ranger import MACRO_DELIMITER, MACRO_DELIMITER_ESC from ranger.core.shared import FileManagerAware from ranger.ext.lazy_property import lazy_property from ranger.api import LinemodeBase, hook_init, hook_ready, register_linemode # COMPAT from os.path import dirname, basename, expanduser, join from os.path import dirname, basename, expanduser, join from ranger.ext.get_executables import get_executables and context including class names, function names, and sometimes code from other files: # Path: ranger.py # ARGV = sys.argv[1:sys.argv.index('--')] if '--' in sys.argv else sys.argv[1:] . Output only the next line.
return results.replace(MACRO_DELIMITER, MACRO_DELIMITER_ESC)
Given the code snippet: <|code_start|># This file is part of ranger, the console file manager. # License: GNU GPL version 3, see the file "AUTHORS" for details. # TODO: Add an optional "!" to all commands and set a flag if it's there from __future__ import (absolute_import, division, print_function) __all__ = ['Command', 'LinemodeBase', 'hook_init', 'hook_ready', 'register_linemode'] # COMPAT _SETTINGS_RE = re.compile(r'^\s*([^\s]+?)=(.*)$') _ALIAS_LINE_RE = re.compile(r'(\s+)') def _command_init(cls): # Escape macros for tab completion if cls.resolve_macros: tab_old = cls.tab def tab(self, tabnum): results = tab_old(self, tabnum) if results is None: return None elif isinstance(results, str): <|code_end|> , generate the next line using the imports in this file: import os import re import ranger import logging import doctest import sys from ranger import MACRO_DELIMITER, MACRO_DELIMITER_ESC from ranger.core.shared import FileManagerAware from ranger.ext.lazy_property import lazy_property from ranger.api import LinemodeBase, hook_init, hook_ready, register_linemode # COMPAT from os.path import dirname, basename, expanduser, join from os.path import dirname, basename, expanduser, join from ranger.ext.get_executables import get_executables and context (functions, classes, or occasionally code) from other files: # Path: ranger.py # ARGV = sys.argv[1:sys.argv.index('--')] if '--' in sys.argv else sys.argv[1:] . Output only the next line.
return results.replace(MACRO_DELIMITER, MACRO_DELIMITER_ESC)
Given the following code snippet before the placeholder: <|code_start|> else: real = None # determine if there have been changes if current == original and current != real: continue # another ranger instance has changed the bookmark if key not in self.dct: del real_dict[key] # the user has deleted it else: real_dict[key] = current # the user has changed it self._set_dict(real_dict, original=real_dict_copy) def save(self): """Save the bookmarks to the bookmarkfile. This is done automatically after every modification if autosave is True. """ self.update() if self.path is None: return path_new = self.path + '.new' try: with open(path_new, 'w', encoding="utf-8") as fobj: for key, value in self.dct.items(): if key in ALLOWED_KEYS \ and key not in self.nonpersistent_bookmarks: key_value = "{0}:{1}\n".format(key, value) <|code_end|> , predict the next line using imports from the current file: import string import re import os from io import open from ranger import PY3 from ranger.core.shared import FileManagerAware and context including class names, function names, and sometimes code from other files: # Path: ranger.py # ARGV = sys.argv[1:sys.argv.index('--')] if '--' in sys.argv else sys.argv[1:] . Output only the next line.
if not PY3 and isinstance(key_value, str):
Continue the code snippet: <|code_start|># This file is part of ranger, the console file manager. # License: GNU GPL version 3, see the file "AUTHORS" for details. from __future__ import (absolute_import, division, print_function) ENCODING = 'utf-8' def check_output(popenargs, **kwargs): """Runs a program, waits for its termination and returns its output This function is functionally identical to python 2.7's subprocess.check_output, but is favored due to python 2.6 compatibility. Will be run through a shell if `popenargs` is a string, otherwise the command is executed directly. The keyword argument `decode` determines if the output shall be decoded with the encoding UTF-8. Further keyword arguments are passed to Popen. """ do_decode = kwargs.pop('decode', True) kwargs.setdefault('stdout', PIPE) kwargs.setdefault('shell', isinstance(popenargs, str)) if 'stderr' in kwargs: <|code_end|> . Use current file imports: from io import open from os import devnull from subprocess import PIPE, CalledProcessError from ranger.ext.popen23 import Popen23 and context (classes, functions, or code) from other files: # Path: ranger/ext/popen23.py # @contextmanager # def Popen23(*args, **kwargs): # pylint: disable=invalid-name # if PY3: # yield Popen(*args, **kwargs) # return # else: # popen2 = Popen(*args, **kwargs) # try: # yield popen2 # finally: # # From Lib/subprocess.py Popen.__exit__: # if popen2.stdout: # popen2.stdout.close() # if popen2.stderr: # popen2.stderr.close() # try: # Flushing a BufferedWriter may raise an error # if popen2.stdin: # popen2.stdin.close() # finally: # # Wait for the process to terminate, to avoid zombies. # popen2.wait() . Output only the next line.
with Popen23(popenargs, **kwargs) as process:
Continue the code snippet: <|code_start|> (lambda fobj: fobj.is_file and not fobj.is_link), InodeFilterConstants.LINKS: (lambda fobj: fobj.is_link), } def __init__(self, filetype): if filetype not in self.type_to_function: raise KeyError(filetype) self.filetype = filetype def __call__(self, fobj): return self.type_to_function[self.filetype](fobj) def __str__(self): return "<Filter: type == '{ft}'>".format(ft=self.filetype) @filter_combinator("or") class OrFilter(BaseFilter): def __init__(self, stack): self.subfilters = [stack[-2], stack[-1]] stack.pop() stack.pop() stack.append(self) def __call__(self, fobj): # Turn logical AND (accept_file()) into a logical OR with the # De Morgan's laws. <|code_end|> . Use current file imports: import re from itertools import izip_longest as zip_longest from itertools import zip_longest from os.path import abspath from ranger.container.directory import accept_file, InodeFilterConstants from ranger.core.shared import FileManagerAware from ranger.ext.hash import hash_chunks and context (classes, functions, or code) from other files: # Path: ranger/container/directory.py # def accept_file(fobj, filters): # """ # Returns True if file shall be shown, otherwise False. # Parameters: # fobj - an instance of FileSystemObject # filters - an array of lambdas, each expects a fobj and # returns True if fobj shall be shown, # otherwise False. # """ # for filt in filters: # if filt and not filt(fobj): # return False # return True # # class InodeFilterConstants(object): # pylint: disable=too-few-public-methods # DIRS = 'd' # FILES = 'f' # LINKS = 'l' # # Path: ranger/ext/hash.py # def hash_chunks(filepath, h=None): # if not h: # h = sha256() # if isdir(filepath): # h.update(filepath) # yield h.hexdigest() # for fp in listdir(filepath): # for fp_chunk in hash_chunks(fp, h=h): # yield fp_chunk # elif getsize(filepath) == 0: # yield h.hexdigest() # else: # with open(filepath, 'rb') as f: # # Read the file in ~64KiB chunks (multiple of sha256's block # # size that works well enough with HDDs and SSDs) # for chunk in iter(lambda: f.read(h.block_size * 1024), b''): # h.update(chunk) # yield h.hexdigest() . Output only the next line.
return not accept_file(
Continue the code snippet: <|code_start|> for dups in group_by_hash(self.fm.thisdir.files_all): if len(dups) >= 2: duplicates.update(dups) return duplicates @stack_filter("unique") class UniqueFilter(BaseFilter, FileManagerAware): def __init__(self, _): self.unique = self.get_unique() def __call__(self, fobj): return fobj in self.unique def __str__(self): return "<Filter: unique>" def get_unique(self): unique = set() for dups in group_by_hash(self.fm.thisdir.files_all): try: unique.add(min(dups, key=lambda fobj: fobj.stat.st_ctime)) except ValueError: pass return unique @stack_filter("type") class TypeFilter(BaseFilter): type_to_function = { <|code_end|> . Use current file imports: import re from itertools import izip_longest as zip_longest from itertools import zip_longest from os.path import abspath from ranger.container.directory import accept_file, InodeFilterConstants from ranger.core.shared import FileManagerAware from ranger.ext.hash import hash_chunks and context (classes, functions, or code) from other files: # Path: ranger/container/directory.py # def accept_file(fobj, filters): # """ # Returns True if file shall be shown, otherwise False. # Parameters: # fobj - an instance of FileSystemObject # filters - an array of lambdas, each expects a fobj and # returns True if fobj shall be shown, # otherwise False. # """ # for filt in filters: # if filt and not filt(fobj): # return False # return True # # class InodeFilterConstants(object): # pylint: disable=too-few-public-methods # DIRS = 'd' # FILES = 'f' # LINKS = 'l' # # Path: ranger/ext/hash.py # def hash_chunks(filepath, h=None): # if not h: # h = sha256() # if isdir(filepath): # h.update(filepath) # yield h.hexdigest() # for fp in listdir(filepath): # for fp_chunk in hash_chunks(fp, h=h): # yield fp_chunk # elif getsize(filepath) == 0: # yield h.hexdigest() # else: # with open(filepath, 'rb') as f: # # Read the file in ~64KiB chunks (multiple of sha256's block # # size that works well enough with HDDs and SSDs) # for chunk in iter(lambda: f.read(h.block_size * 1024), b''): # h.update(chunk) # yield h.hexdigest() . Output only the next line.
InodeFilterConstants.DIRS:
Using the snippet: <|code_start|> @stack_filter("mime") class MimeFilter(BaseFilter, FileManagerAware): def __init__(self, pattern): self.pattern = pattern self.regex = re.compile(pattern) def __call__(self, fobj): mimetype, _ = self.fm.mimetypes.guess_type(fobj.relative_path) if mimetype is None: return False return self.regex.search(mimetype) def __str__(self): return "<Filter: mimetype =~ /{pat}/>".format(pat=self.pattern) @stack_filter("hash") class HashFilter(BaseFilter, FileManagerAware): def __init__(self, filepath=None): if filepath is None: self.filepath = self.fm.thisfile.path else: self.filepath = filepath if self.filepath is None: self.fm.notify("Error: No file selected for hashing!", bad=True) # TODO: Lazily generated list would be more efficient, a generator # isn't enough because this object is reused for every fsobject # in the current directory. <|code_end|> , determine the next line of code. You have imports: import re from itertools import izip_longest as zip_longest from itertools import zip_longest from os.path import abspath from ranger.container.directory import accept_file, InodeFilterConstants from ranger.core.shared import FileManagerAware from ranger.ext.hash import hash_chunks and context (class names, function names, or code) available: # Path: ranger/container/directory.py # def accept_file(fobj, filters): # """ # Returns True if file shall be shown, otherwise False. # Parameters: # fobj - an instance of FileSystemObject # filters - an array of lambdas, each expects a fobj and # returns True if fobj shall be shown, # otherwise False. # """ # for filt in filters: # if filt and not filt(fobj): # return False # return True # # class InodeFilterConstants(object): # pylint: disable=too-few-public-methods # DIRS = 'd' # FILES = 'f' # LINKS = 'l' # # Path: ranger/ext/hash.py # def hash_chunks(filepath, h=None): # if not h: # h = sha256() # if isdir(filepath): # h.update(filepath) # yield h.hexdigest() # for fp in listdir(filepath): # for fp_chunk in hash_chunks(fp, h=h): # yield fp_chunk # elif getsize(filepath) == 0: # yield h.hexdigest() # else: # with open(filepath, 'rb') as f: # # Read the file in ~64KiB chunks (multiple of sha256's block # # size that works well enough with HDDs and SSDs) # for chunk in iter(lambda: f.read(h.block_size * 1024), b''): # h.update(chunk) # yield h.hexdigest() . Output only the next line.
self.filehash = list(hash_chunks(abspath(self.filepath)))
Given the code snippet: <|code_start|> def walklevel(some_dir, level): some_dir = some_dir.rstrip(os.path.sep) followlinks = level > 0 assert os.path.isdir(some_dir) num_sep = some_dir.count(os.path.sep) for root, dirs, files in os.walk(some_dir, followlinks=followlinks): yield root, dirs, files num_sep_this = root.count(os.path.sep) if level != -1 and num_sep + level <= num_sep_this: del dirs[:] def mtimelevel(path, level): mtime = os.stat(path).st_mtime for dirpath, dirnames, _ in walklevel(path, level): dirlist = [os.path.join("/", dirpath, d) for d in dirnames if level == -1 or dirpath.count(os.path.sep) - path.count(os.path.sep) <= level] mtime = max(mtime, max([-1] + [os.stat(d).st_mtime for d in dirlist])) return mtime class InodeFilterConstants(object): # pylint: disable=too-few-public-methods DIRS = 'd' FILES = 'f' LINKS = 'l' class Directory( # pylint: disable=too-many-instance-attributes,too-many-public-methods <|code_end|> , generate the next line using the imports in this file: import locale import os.path import random import re from os import stat as os_stat, lstat as os_lstat from collections import deque from time import time from ranger.container.fsobject import BAD_INFO, FileSystemObject from ranger.core.loader import Loadable from ranger.ext.mount_path import mount_path from ranger.container.file import File from ranger.ext.accumulator import Accumulator from ranger.ext.lazy_property import lazy_property from ranger.ext.human_readable import human_readable from ranger.container.settings import LocalSettings from ranger.ext.vcs import Vcs and context (functions, classes, or occasionally code) from other files: # Path: ranger/core/loader.py # class Loadable(object): # paused = False # progressbar_supported = False # # def __init__(self, gen, descr): # self.load_generator = gen # self.description = descr # self.percent = 0 # # def get_description(self): # return self.description # # def pause(self): # self.paused = True # # def unpause(self): # try: # del self.paused # except AttributeError: # pass # # def destroy(self): # pass # # Path: ranger/container/file.py # class File(FileSystemObject): # is_file = True # preview_data = None # preview_known = False # preview_loading = False # _firstbytes = None # # @property # def firstbytes(self): # if self._firstbytes is not None: # return self._firstbytes # try: # with open(self.path, 'rb') as fobj: # self._firstbytes = set(fobj.read(N_FIRST_BYTES)) # # IOError for Python2, OSError for Python3 # except (IOError, OSError): # return None # return self._firstbytes # # def is_binary(self): # if self.firstbytes and CONTROL_CHARACTERS & self.firstbytes: # return True # return False # # def has_preview(self): # pylint: disable=too-many-return-statements # if not self.fm.settings.preview_files: # return False # if self.is_socket or self.is_fifo or self.is_device: # return False # if not self.accessible: # return False # if self.fm.settings.preview_max_size and \ # self.size > self.fm.settings.preview_max_size: # return False # if self.fm.settings.preview_script and \ # self.fm.settings.use_preview_script: # return True # if self.container: # return False # if PREVIEW_WHITELIST.search(self.basename): # return True # if PREVIEW_BLACKLIST.search(self.basename): # return False # if self.path == '/dev/core' or self.path == '/proc/kcore': # return False # if self.is_binary(): # return False # return True # # def get_preview_source(self, width, height): # return self.fm.get_preview(self, width, height) # # def is_image_preview(self): # try: # return self.fm.previews[self.realpath]['imagepreview'] # except KeyError: # return False # # def __eq__(self, other): # return isinstance(other, File) and self.path == other.path # # def __neq__(self, other): # return not self.__eq__(other) # # def __hash__(self): # return hash(self.path) # # Path: ranger/container/settings.py # class LocalSettings(object): # pylint: disable=too-few-public-methods # # def __init__(self, path, parent): # self.__dict__['_parent'] = parent # self.__dict__['_path'] = path # # def __setattr__(self, name, value): # if name.startswith('_'): # self.__dict__[name] = value # else: # self._parent.set(name, value, self._path) # # def __getattr__(self, name): # if name.startswith('_'): # return self.__dict__[name] # if name.startswith('signal_'): # return getattr(self._parent, name) # return self._parent.get(name, self._path) # # def __iter__(self): # for setting in self._parent._settings: # pylint: disable=protected-access # yield setting # # __getitem__ = __getattr__ # __setitem__ = __setattr__ . Output only the next line.
FileSystemObject, Accumulator, Loadable):
Based on the snippet: <|code_start|> file_stat = file_lstat except OSError: file_lstat = None file_stat = None if file_lstat and file_stat: stats = (file_stat, file_lstat) is_a_dir = file_stat.st_mode & 0o170000 == 0o040000 else: stats = None is_a_dir = False if is_a_dir: item = self.fm.get_directory(name, preload=stats, path_is_abs=True, basename_is_rel_to=basename_is_rel_to) item.load_if_outdated() if self.flat: item.relative_path = os.path.relpath(item.path, self.path) else: item.relative_path = item.basename item.relative_path_lower = item.relative_path.lower() if item.vcs and item.vcs.track: if item.vcs.is_root_pointer: has_vcschild = True else: item.vcsstatus = \ item.vcs.rootvcs.status_subpath( # pylint: disable=no-member os.path.join(self.realpath, item.basename), is_directory=True, ) else: <|code_end|> , predict the immediate next line with the help of imports: import locale import os.path import random import re from os import stat as os_stat, lstat as os_lstat from collections import deque from time import time from ranger.container.fsobject import BAD_INFO, FileSystemObject from ranger.core.loader import Loadable from ranger.ext.mount_path import mount_path from ranger.container.file import File from ranger.ext.accumulator import Accumulator from ranger.ext.lazy_property import lazy_property from ranger.ext.human_readable import human_readable from ranger.container.settings import LocalSettings from ranger.ext.vcs import Vcs and context (classes, functions, sometimes code) from other files: # Path: ranger/core/loader.py # class Loadable(object): # paused = False # progressbar_supported = False # # def __init__(self, gen, descr): # self.load_generator = gen # self.description = descr # self.percent = 0 # # def get_description(self): # return self.description # # def pause(self): # self.paused = True # # def unpause(self): # try: # del self.paused # except AttributeError: # pass # # def destroy(self): # pass # # Path: ranger/container/file.py # class File(FileSystemObject): # is_file = True # preview_data = None # preview_known = False # preview_loading = False # _firstbytes = None # # @property # def firstbytes(self): # if self._firstbytes is not None: # return self._firstbytes # try: # with open(self.path, 'rb') as fobj: # self._firstbytes = set(fobj.read(N_FIRST_BYTES)) # # IOError for Python2, OSError for Python3 # except (IOError, OSError): # return None # return self._firstbytes # # def is_binary(self): # if self.firstbytes and CONTROL_CHARACTERS & self.firstbytes: # return True # return False # # def has_preview(self): # pylint: disable=too-many-return-statements # if not self.fm.settings.preview_files: # return False # if self.is_socket or self.is_fifo or self.is_device: # return False # if not self.accessible: # return False # if self.fm.settings.preview_max_size and \ # self.size > self.fm.settings.preview_max_size: # return False # if self.fm.settings.preview_script and \ # self.fm.settings.use_preview_script: # return True # if self.container: # return False # if PREVIEW_WHITELIST.search(self.basename): # return True # if PREVIEW_BLACKLIST.search(self.basename): # return False # if self.path == '/dev/core' or self.path == '/proc/kcore': # return False # if self.is_binary(): # return False # return True # # def get_preview_source(self, width, height): # return self.fm.get_preview(self, width, height) # # def is_image_preview(self): # try: # return self.fm.previews[self.realpath]['imagepreview'] # except KeyError: # return False # # def __eq__(self, other): # return isinstance(other, File) and self.path == other.path # # def __neq__(self, other): # return not self.__eq__(other) # # def __hash__(self): # return hash(self.path) # # Path: ranger/container/settings.py # class LocalSettings(object): # pylint: disable=too-few-public-methods # # def __init__(self, path, parent): # self.__dict__['_parent'] = parent # self.__dict__['_path'] = path # # def __setattr__(self, name, value): # if name.startswith('_'): # self.__dict__[name] = value # else: # self._parent.set(name, value, self._path) # # def __getattr__(self, name): # if name.startswith('_'): # return self.__dict__[name] # if name.startswith('signal_'): # return getattr(self._parent, name) # return self._parent.get(name, self._path) # # def __iter__(self): # for setting in self._parent._settings: # pylint: disable=protected-access # yield setting # # __getitem__ = __getattr__ # __setitem__ = __setattr__ . Output only the next line.
item = File(name, preload=stats, path_is_abs=True,
Using the snippet: <|code_start|> 'size': lambda path: -(path.size or 1), 'mtime': lambda path: -(path.stat and path.stat.st_mtime or 1), 'ctime': lambda path: -(path.stat and path.stat.st_ctime or 1), 'atime': lambda path: -(path.stat and path.stat.st_atime or 1), 'random': lambda path: random.random(), 'type': lambda path: path.mimetype or '', 'extension': lambda path: path.extension or '', } def __init__(self, path, **kw): assert not os.path.isfile(path), "No directory given!" Loadable.__init__(self, None, None) Accumulator.__init__(self) FileSystemObject.__init__(self, path, **kw) self.marked_items = [] self.filter_stack = [] self._signal_functions = [] func = self.signal_function_factory(self.sort) self._signal_functions += [func] for opt in ('sort_directories_first', 'sort', 'sort_reverse', 'sort_case_insensitive'): self.settings.signal_bind('setopt.' + opt, func, weak=True, autosort=False) func = self.signal_function_factory(self.refilter) self._signal_functions += [func] for opt in ('hidden_filter', 'show_hidden'): self.settings.signal_bind('setopt.' + opt, func, weak=True, autosort=False) <|code_end|> , determine the next line of code. You have imports: import locale import os.path import random import re from os import stat as os_stat, lstat as os_lstat from collections import deque from time import time from ranger.container.fsobject import BAD_INFO, FileSystemObject from ranger.core.loader import Loadable from ranger.ext.mount_path import mount_path from ranger.container.file import File from ranger.ext.accumulator import Accumulator from ranger.ext.lazy_property import lazy_property from ranger.ext.human_readable import human_readable from ranger.container.settings import LocalSettings from ranger.ext.vcs import Vcs and context (class names, function names, or code) available: # Path: ranger/core/loader.py # class Loadable(object): # paused = False # progressbar_supported = False # # def __init__(self, gen, descr): # self.load_generator = gen # self.description = descr # self.percent = 0 # # def get_description(self): # return self.description # # def pause(self): # self.paused = True # # def unpause(self): # try: # del self.paused # except AttributeError: # pass # # def destroy(self): # pass # # Path: ranger/container/file.py # class File(FileSystemObject): # is_file = True # preview_data = None # preview_known = False # preview_loading = False # _firstbytes = None # # @property # def firstbytes(self): # if self._firstbytes is not None: # return self._firstbytes # try: # with open(self.path, 'rb') as fobj: # self._firstbytes = set(fobj.read(N_FIRST_BYTES)) # # IOError for Python2, OSError for Python3 # except (IOError, OSError): # return None # return self._firstbytes # # def is_binary(self): # if self.firstbytes and CONTROL_CHARACTERS & self.firstbytes: # return True # return False # # def has_preview(self): # pylint: disable=too-many-return-statements # if not self.fm.settings.preview_files: # return False # if self.is_socket or self.is_fifo or self.is_device: # return False # if not self.accessible: # return False # if self.fm.settings.preview_max_size and \ # self.size > self.fm.settings.preview_max_size: # return False # if self.fm.settings.preview_script and \ # self.fm.settings.use_preview_script: # return True # if self.container: # return False # if PREVIEW_WHITELIST.search(self.basename): # return True # if PREVIEW_BLACKLIST.search(self.basename): # return False # if self.path == '/dev/core' or self.path == '/proc/kcore': # return False # if self.is_binary(): # return False # return True # # def get_preview_source(self, width, height): # return self.fm.get_preview(self, width, height) # # def is_image_preview(self): # try: # return self.fm.previews[self.realpath]['imagepreview'] # except KeyError: # return False # # def __eq__(self, other): # return isinstance(other, File) and self.path == other.path # # def __neq__(self, other): # return not self.__eq__(other) # # def __hash__(self): # return hash(self.path) # # Path: ranger/container/settings.py # class LocalSettings(object): # pylint: disable=too-few-public-methods # # def __init__(self, path, parent): # self.__dict__['_parent'] = parent # self.__dict__['_path'] = path # # def __setattr__(self, name, value): # if name.startswith('_'): # self.__dict__[name] = value # else: # self._parent.set(name, value, self._path) # # def __getattr__(self, name): # if name.startswith('_'): # return self.__dict__[name] # if name.startswith('signal_'): # return getattr(self._parent, name) # return self._parent.get(name, self._path) # # def __iter__(self): # for setting in self._parent._settings: # pylint: disable=protected-access # yield setting # # __getitem__ = __getattr__ # __setitem__ = __setattr__ . Output only the next line.
self.settings = LocalSettings(path, self.settings)
Here is a snippet: <|code_start|> def infostring(self, fobj, metadata): if metadata.authors: authorstring = metadata.authors if ',' in authorstring: authorstring = authorstring[0:authorstring.find(",")] return authorstring return "" class PermissionsLinemode(LinemodeBase): name = "permissions" def filetitle(self, fobj, metadata): return "%s %s %s %s" % ( fobj.get_permission_string(), fobj.user, fobj.group, fobj.relative_path) def infostring(self, fobj, metadata): return "" class FileInfoLinemode(LinemodeBase): name = "fileinfo" def filetitle(self, fobj, metadata): return fobj.relative_path def infostring(self, fobj, metadata): if not fobj.is_directory: try: <|code_end|> . Write the next line using the current file imports: from abc import ABCMeta, abstractproperty, abstractmethod from datetime import datetime from ranger.ext.human_readable import human_readable, human_readable_time from ranger.ext import spawn from subprocess import CalledProcessError and context from other files: # Path: ranger/ext/spawn.py # def spawn(*popenargs, **kwargs): # """Runs a program, waits for its termination and returns its stdout # # This function is similar to python 2.7's subprocess.check_output, # but is favored due to python 2.6 compatibility. # # The arguments may be: # # spawn(string) # spawn(command, arg1, arg2...) # spawn([command, arg1, arg2]) # # Will be run through a shell if `popenargs` is a string, otherwise the command # is executed directly. # # The keyword argument `decode` determines if the output shall be decoded # with the encoding UTF-8. # # Further keyword arguments are passed to Popen. # """ # if len(popenargs) == 1: # return check_output(popenargs[0], **kwargs) # return check_output(list(popenargs), **kwargs) , which may include functions, classes, or code. Output only the next line.
fileinfo = spawn.check_output(["file", "-Lb", fobj.path]).strip()
Based on the snippet: <|code_start|> action = ['sudo'] + (f_flag and ['-b'] or []) + action toggle_ui = True context.wait = True if 't' in context.flags: if not ('WAYLAND_DISPLAY' in os.environ or sys.platform == 'darwin' or 'DISPLAY' in os.environ): return self._log("Can not run with 't' flag, no display found!") term = get_term() if isinstance(action, str): action = term + ' -e ' + action else: action = [term, '-e'] + action toggle_ui = False context.wait = False popen_kws['args'] = action # Finally, run it if toggle_ui: self._activate_ui(False) try: error = None process = None self.fm.signal_emit('runner.execute.before', popen_kws=popen_kws, context=context) try: if 'f' in context.flags and 'r' not in context.flags: # This can fail and return False if os.fork() is not # supported, but we assume it is, since curses is used. <|code_end|> , predict the immediate next line with the help of imports: import logging import os import sys from io import open from subprocess import Popen, PIPE, STDOUT from ranger.ext.get_executables import get_executables, get_term from ranger.ext.popen_forked import Popen_forked and context (classes, functions, sometimes code) from other files: # Path: ranger/ext/popen_forked.py # def Popen_forked(*args, **kwargs): # pylint: disable=invalid-name # """Forks process and runs Popen with the given args and kwargs. # # Returns True if forking succeeded, otherwise False. # """ # try: # pid = os.fork() # except OSError: # return False # if pid == 0: # os.setsid() # with open(os.devnull, 'r', encoding="utf-8") as null_r, open( # os.devnull, 'w', encoding="utf-8" # ) as null_w: # kwargs['stdin'] = null_r # kwargs['stdout'] = kwargs['stderr'] = null_w # Popen(*args, **kwargs) # os._exit(0) # pylint: disable=protected-access # else: # os.wait() # return True . Output only the next line.
Popen_forked(**popen_kws)
Continue the code snippet: <|code_start|> def add(self, string, *lst, **kw): colorstr = ColoredString(string, self.base_color_tag, *lst) colorstr.__dict__.update(kw) self.append(colorstr) def add_space(self, n=1): self.add(' ' * n, 'space') def sumsize(self): return sum(len(item) for item in self) def fixedsize(self): n = 0 for item in self: if item.fixed: n += len(item) else: n += item.min_size return n class ColoredString(object): def __init__(self, string, *lst): self.string = WideString(string) self.lst = lst self.fixed = False if not string or not self.string.chars: self.min_size = 0 <|code_end|> . Use current file imports: from ranger import PY3 from ranger.ext.widestring import WideString, utf_char_width and context (classes, functions, or code) from other files: # Path: ranger.py # ARGV = sys.argv[1:sys.argv.index('--')] if '--' in sys.argv else sys.argv[1:] # # Path: ranger/ext/widestring.py # class WideString(object): # pylint: disable=too-few-public-methods # # def __init__(self, string, chars=None): # try: # self.string = str(string) # except UnicodeEncodeError: # # Here I assume that string is a "unicode" object, because why else # # would str(string) raise a UnicodeEncodeError? # self.string = string.encode('latin-1', 'ignore') # if chars is None: # self.chars = string_to_charlist(string) # else: # self.chars = chars # # def __add__(self, string): # """ # >>> (WideString("a") + WideString("b")).string # 'ab' # >>> (WideString("a") + WideString("b")).chars # ['a', 'b'] # >>> (WideString("afd") + "bc").chars # ['a', 'f', 'd', 'b', 'c'] # """ # if isinstance(string, str): # return WideString(self.string + string) # elif isinstance(string, WideString): # return WideString(self.string + string.string, self.chars + string.chars) # return None # # def __radd__(self, string): # """ # >>> ("bc" + WideString("afd")).chars # ['b', 'c', 'a', 'f', 'd'] # """ # if isinstance(string, str): # return WideString(string + self.string) # elif isinstance(string, WideString): # return WideString(string.string + self.string, string.chars + self.chars) # return None # # def __str__(self): # return self.string # # def __repr__(self): # return '<' + self.__class__.__name__ + " '" + self.string + "'>" # # def __getslice__(self, start, stop): # """ # >>> WideString("asdf")[1:3] # <WideString 'sd'> # >>> WideString("asdf")[1:-100] # <WideString ''> # >>> WideString("モヒカン")[2:4] # <WideString 'ヒ'> # >>> WideString("モヒカン")[2:5] # <WideString 'ヒ '> # >>> WideString("モabカン")[2:5] # <WideString 'ab '> # >>> WideString("モヒカン")[1:5] # <WideString ' ヒ '> # >>> WideString("モヒカン")[:] # <WideString 'モヒカン'> # >>> WideString("aモ")[0:3] # <WideString 'aモ'> # >>> WideString("aモ")[0:2] # <WideString 'a '> # >>> WideString("aモ")[0:1] # <WideString 'a'> # """ # if stop is None or stop > len(self.chars): # stop = len(self.chars) # if stop < 0: # stop = len(self.chars) + stop # if stop < 0: # return WideString("") # if start is None or start < 0: # start = 0 # if stop < len(self.chars) and self.chars[stop] == '': # if self.chars[start] == '': # return WideString(' ' + ''.join(self.chars[start:stop - 1]) + ' ') # return WideString(''.join(self.chars[start:stop - 1]) + ' ') # if self.chars[start] == '': # return WideString(' ' + ''.join(self.chars[start:stop - 1])) # return WideString(''.join(self.chars[start:stop])) # # def __getitem__(self, i): # """ # >>> WideString("asdf")[2] # <WideString 'd'> # >>> WideString("……")[0] # <WideString '…'> # >>> WideString("……")[1] # <WideString '…'> # """ # if isinstance(i, slice): # return self.__getslice__(i.start, i.stop) # return self.__getslice__(i, i + 1) # # def __len__(self): # """ # >>> len(WideString("poo")) # 3 # >>> len(WideString("モヒカン")) # 8 # """ # return len(self.chars) # # def utf_char_width(string): # """Return the width of a single character""" # if east_asian_width(string) in WIDE_SYMBOLS: # return WIDE # return NARROW . Output only the next line.
elif PY3:
Given snippet: <|code_start|> class BarSide(list): def __init__(self, base_color_tag): # pylint: disable=super-init-not-called self.base_color_tag = base_color_tag def add(self, string, *lst, **kw): colorstr = ColoredString(string, self.base_color_tag, *lst) colorstr.__dict__.update(kw) self.append(colorstr) def add_space(self, n=1): self.add(' ' * n, 'space') def sumsize(self): return sum(len(item) for item in self) def fixedsize(self): n = 0 for item in self: if item.fixed: n += len(item) else: n += item.min_size return n class ColoredString(object): def __init__(self, string, *lst): <|code_end|> , continue by predicting the next line. Consider current file imports: from ranger import PY3 from ranger.ext.widestring import WideString, utf_char_width and context: # Path: ranger.py # ARGV = sys.argv[1:sys.argv.index('--')] if '--' in sys.argv else sys.argv[1:] # # Path: ranger/ext/widestring.py # class WideString(object): # pylint: disable=too-few-public-methods # # def __init__(self, string, chars=None): # try: # self.string = str(string) # except UnicodeEncodeError: # # Here I assume that string is a "unicode" object, because why else # # would str(string) raise a UnicodeEncodeError? # self.string = string.encode('latin-1', 'ignore') # if chars is None: # self.chars = string_to_charlist(string) # else: # self.chars = chars # # def __add__(self, string): # """ # >>> (WideString("a") + WideString("b")).string # 'ab' # >>> (WideString("a") + WideString("b")).chars # ['a', 'b'] # >>> (WideString("afd") + "bc").chars # ['a', 'f', 'd', 'b', 'c'] # """ # if isinstance(string, str): # return WideString(self.string + string) # elif isinstance(string, WideString): # return WideString(self.string + string.string, self.chars + string.chars) # return None # # def __radd__(self, string): # """ # >>> ("bc" + WideString("afd")).chars # ['b', 'c', 'a', 'f', 'd'] # """ # if isinstance(string, str): # return WideString(string + self.string) # elif isinstance(string, WideString): # return WideString(string.string + self.string, string.chars + self.chars) # return None # # def __str__(self): # return self.string # # def __repr__(self): # return '<' + self.__class__.__name__ + " '" + self.string + "'>" # # def __getslice__(self, start, stop): # """ # >>> WideString("asdf")[1:3] # <WideString 'sd'> # >>> WideString("asdf")[1:-100] # <WideString ''> # >>> WideString("モヒカン")[2:4] # <WideString 'ヒ'> # >>> WideString("モヒカン")[2:5] # <WideString 'ヒ '> # >>> WideString("モabカン")[2:5] # <WideString 'ab '> # >>> WideString("モヒカン")[1:5] # <WideString ' ヒ '> # >>> WideString("モヒカン")[:] # <WideString 'モヒカン'> # >>> WideString("aモ")[0:3] # <WideString 'aモ'> # >>> WideString("aモ")[0:2] # <WideString 'a '> # >>> WideString("aモ")[0:1] # <WideString 'a'> # """ # if stop is None or stop > len(self.chars): # stop = len(self.chars) # if stop < 0: # stop = len(self.chars) + stop # if stop < 0: # return WideString("") # if start is None or start < 0: # start = 0 # if stop < len(self.chars) and self.chars[stop] == '': # if self.chars[start] == '': # return WideString(' ' + ''.join(self.chars[start:stop - 1]) + ' ') # return WideString(''.join(self.chars[start:stop - 1]) + ' ') # if self.chars[start] == '': # return WideString(' ' + ''.join(self.chars[start:stop - 1])) # return WideString(''.join(self.chars[start:stop])) # # def __getitem__(self, i): # """ # >>> WideString("asdf")[2] # <WideString 'd'> # >>> WideString("……")[0] # <WideString '…'> # >>> WideString("……")[1] # <WideString '…'> # """ # if isinstance(i, slice): # return self.__getslice__(i.start, i.stop) # return self.__getslice__(i, i + 1) # # def __len__(self): # """ # >>> len(WideString("poo")) # 3 # >>> len(WideString("モヒカン")) # 8 # """ # return len(self.chars) # # def utf_char_width(string): # """Return the width of a single character""" # if east_asian_width(string) in WIDE_SYMBOLS: # return WIDE # return NARROW which might include code, classes, or functions. Output only the next line.
self.string = WideString(string)
Predict the next line after this snippet: <|code_start|> def add(self, string, *lst, **kw): colorstr = ColoredString(string, self.base_color_tag, *lst) colorstr.__dict__.update(kw) self.append(colorstr) def add_space(self, n=1): self.add(' ' * n, 'space') def sumsize(self): return sum(len(item) for item in self) def fixedsize(self): n = 0 for item in self: if item.fixed: n += len(item) else: n += item.min_size return n class ColoredString(object): def __init__(self, string, *lst): self.string = WideString(string) self.lst = lst self.fixed = False if not string or not self.string.chars: self.min_size = 0 elif PY3: <|code_end|> using the current file's imports: from ranger import PY3 from ranger.ext.widestring import WideString, utf_char_width and any relevant context from other files: # Path: ranger.py # ARGV = sys.argv[1:sys.argv.index('--')] if '--' in sys.argv else sys.argv[1:] # # Path: ranger/ext/widestring.py # class WideString(object): # pylint: disable=too-few-public-methods # # def __init__(self, string, chars=None): # try: # self.string = str(string) # except UnicodeEncodeError: # # Here I assume that string is a "unicode" object, because why else # # would str(string) raise a UnicodeEncodeError? # self.string = string.encode('latin-1', 'ignore') # if chars is None: # self.chars = string_to_charlist(string) # else: # self.chars = chars # # def __add__(self, string): # """ # >>> (WideString("a") + WideString("b")).string # 'ab' # >>> (WideString("a") + WideString("b")).chars # ['a', 'b'] # >>> (WideString("afd") + "bc").chars # ['a', 'f', 'd', 'b', 'c'] # """ # if isinstance(string, str): # return WideString(self.string + string) # elif isinstance(string, WideString): # return WideString(self.string + string.string, self.chars + string.chars) # return None # # def __radd__(self, string): # """ # >>> ("bc" + WideString("afd")).chars # ['b', 'c', 'a', 'f', 'd'] # """ # if isinstance(string, str): # return WideString(string + self.string) # elif isinstance(string, WideString): # return WideString(string.string + self.string, string.chars + self.chars) # return None # # def __str__(self): # return self.string # # def __repr__(self): # return '<' + self.__class__.__name__ + " '" + self.string + "'>" # # def __getslice__(self, start, stop): # """ # >>> WideString("asdf")[1:3] # <WideString 'sd'> # >>> WideString("asdf")[1:-100] # <WideString ''> # >>> WideString("モヒカン")[2:4] # <WideString 'ヒ'> # >>> WideString("モヒカン")[2:5] # <WideString 'ヒ '> # >>> WideString("モabカン")[2:5] # <WideString 'ab '> # >>> WideString("モヒカン")[1:5] # <WideString ' ヒ '> # >>> WideString("モヒカン")[:] # <WideString 'モヒカン'> # >>> WideString("aモ")[0:3] # <WideString 'aモ'> # >>> WideString("aモ")[0:2] # <WideString 'a '> # >>> WideString("aモ")[0:1] # <WideString 'a'> # """ # if stop is None or stop > len(self.chars): # stop = len(self.chars) # if stop < 0: # stop = len(self.chars) + stop # if stop < 0: # return WideString("") # if start is None or start < 0: # start = 0 # if stop < len(self.chars) and self.chars[stop] == '': # if self.chars[start] == '': # return WideString(' ' + ''.join(self.chars[start:stop - 1]) + ' ') # return WideString(''.join(self.chars[start:stop - 1]) + ' ') # if self.chars[start] == '': # return WideString(' ' + ''.join(self.chars[start:stop - 1])) # return WideString(''.join(self.chars[start:stop])) # # def __getitem__(self, i): # """ # >>> WideString("asdf")[2] # <WideString 'd'> # >>> WideString("……")[0] # <WideString '…'> # >>> WideString("……")[1] # <WideString '…'> # """ # if isinstance(i, slice): # return self.__getslice__(i.start, i.stop) # return self.__getslice__(i, i + 1) # # def __len__(self): # """ # >>> len(WideString("poo")) # 3 # >>> len(WideString("モヒカン")) # 8 # """ # return len(self.chars) # # def utf_char_width(string): # """Return the width of a single character""" # if east_asian_width(string) in WIDE_SYMBOLS: # return WIDE # return NARROW . Output only the next line.
self.min_size = utf_char_width(string[0])
Given snippet: <|code_start|> del pointer[keys[pos]] elif len(keys) == pos + 1: try: del pointer[keys[pos]] except KeyError: pass try: keys.pop() except IndexError: pass class KeyMaps(dict): def __init__(self, keybuffer=None): dict.__init__(self) self.keybuffer = keybuffer self.used_keymap = None def use_keymap(self, keymap_name): self.keybuffer.keymap = self.get(keymap_name, {}) if self.used_keymap != keymap_name: self.used_keymap = keymap_name self.keybuffer.clear() def _clean_input(self, context, keys): try: pointer = self[context] except KeyError: self[context] = pointer = {} <|code_end|> , continue by predicting the next line. Consider current file imports: import sys import copy import curses.ascii import doctest from ranger import PY3 and context: # Path: ranger.py # ARGV = sys.argv[1:sys.argv.index('--')] if '--' in sys.argv else sys.argv[1:] which might include code, classes, or functions. Output only the next line.
if PY3:
Based on the snippet: <|code_start|> scale = max_height / height return width * scale elif width > max_width: scale = max_width / width return width * scale return width @staticmethod def _encode_image_content(path): """Read and encode the contents of path""" with open(path, 'rb') as fobj: return base64.b64encode(fobj.read()).decode('utf-8') @staticmethod def _get_image_dimensions(path): """Determine image size using imghdr""" with open(path, 'rb') as file_handle: file_header = file_handle.read(24) image_type = imghdr.what(path) if len(file_header) != 24: return 0, 0 if image_type == 'png': check = struct.unpack('>i', file_header[4:8])[0] if check != 0x0d0a1a0a: return 0, 0 width, height = struct.unpack('>ii', file_header[16:24]) elif image_type == 'gif': width, height = struct.unpack('<HH', file_header[6:10]) elif image_type == 'jpeg': <|code_end|> , predict the immediate next line with the help of imports: import base64 import curses import errno import fcntl import imghdr import os import struct import sys import warnings import json import threading import termios import codecs import PIL.Image from subprocess import Popen, PIPE from collections import defaultdict from contextlib import contextmanager from tempfile import NamedTemporaryFile from ranger import PY3 from ranger.core.shared import FileManagerAware, SettingsAware from ranger.ext.popen23 import Popen23 from time import sleep and context (classes, functions, sometimes code) from other files: # Path: ranger.py # ARGV = sys.argv[1:sys.argv.index('--')] if '--' in sys.argv else sys.argv[1:] # # Path: ranger/ext/popen23.py # @contextmanager # def Popen23(*args, **kwargs): # pylint: disable=invalid-name # if PY3: # yield Popen(*args, **kwargs) # return # else: # popen2 = Popen(*args, **kwargs) # try: # yield popen2 # finally: # # From Lib/subprocess.py Popen.__exit__: # if popen2.stdout: # popen2.stdout.close() # if popen2.stderr: # popen2.stderr.close() # try: # Flushing a BufferedWriter may raise an error # if popen2.stdin: # popen2.stdin.close() # finally: # # Wait for the process to terminate, to avoid zombies. # popen2.wait() . Output only the next line.
unreadable = OSError if PY3 else IOError
Given the code snippet: <|code_start|> def initialize(self): """start w3mimgdisplay""" self.binary_path = None self.binary_path = self._find_w3mimgdisplay_executable() # may crash # We cannot close the process because that stops the preview. self.process = Popen([self.binary_path] + W3MIMGDISPLAY_OPTIONS, cwd=self.working_dir, stdin=PIPE, stdout=PIPE, universal_newlines=True) self.is_initialized = True @staticmethod def _find_w3mimgdisplay_executable(): paths = [os.environ.get(W3MIMGDISPLAY_ENV, None)] + W3MIMGDISPLAY_PATHS for path in paths: if path is not None and os.path.exists(path): return path raise ImageDisplayError("No w3mimgdisplay executable found. Please set " "the path manually by setting the %s environment variable. (see " "man page)" % W3MIMGDISPLAY_ENV) def _get_font_dimensions(self): # Get the height and width of a character displayed in the terminal in # pixels. if self.binary_path is None: self.binary_path = self._find_w3mimgdisplay_executable() farg = struct.pack("HHHH", 0, 0, 0, 0) fd_stdout = sys.stdout.fileno() fretint = fcntl.ioctl(fd_stdout, termios.TIOCGWINSZ, farg) rows, cols, xpixels, ypixels = struct.unpack("HHHH", fretint) if xpixels == 0 and ypixels == 0: <|code_end|> , generate the next line using the imports in this file: import base64 import curses import errno import fcntl import imghdr import os import struct import sys import warnings import json import threading import termios import codecs import PIL.Image from subprocess import Popen, PIPE from collections import defaultdict from contextlib import contextmanager from tempfile import NamedTemporaryFile from ranger import PY3 from ranger.core.shared import FileManagerAware, SettingsAware from ranger.ext.popen23 import Popen23 from time import sleep and context (functions, classes, or occasionally code) from other files: # Path: ranger.py # ARGV = sys.argv[1:sys.argv.index('--')] if '--' in sys.argv else sys.argv[1:] # # Path: ranger/ext/popen23.py # @contextmanager # def Popen23(*args, **kwargs): # pylint: disable=invalid-name # if PY3: # yield Popen(*args, **kwargs) # return # else: # popen2 = Popen(*args, **kwargs) # try: # yield popen2 # finally: # # From Lib/subprocess.py Popen.__exit__: # if popen2.stdout: # popen2.stdout.close() # if popen2.stderr: # popen2.stderr.close() # try: # Flushing a BufferedWriter may raise an error # if popen2.stdin: # popen2.stdin.close() # finally: # # Wait for the process to terminate, to avoid zombies. # popen2.wait() . Output only the next line.
with Popen23(
Next line prediction: <|code_start|># This file is part of ranger, the console file manager. # License: GNU GPL version 3, see the file "AUTHORS" for details. """The main function responsible to initialize the FM object and stuff.""" from __future__ import (absolute_import, division, print_function) LOG = getLogger(__name__) VERSION_MSG = [ <|code_end|> . Use current file imports: (import atexit import locale import os.path import shutil import sys import tempfile import ranger.api import cProfile import pstats import traceback import ranger.core.shared import ranger.api.commands import imp # pylint: disable=deprecated-module import importlib from io import open from logging import getLogger from ranger import VERSION from ranger.container.settings import Settings from ranger.core.shared import FileManagerAware, SettingsAware from ranger.core.fm import FM from ranger.ext.logutils import setup_logging from ranger.ext.openstruct import OpenStruct from ranger.container.directory import InodeFilterConstants from ranger.ext.keybinding_parser import (special_keys, reversed_special_keys) from ranger.ext import curses_interrupt_handler from optparse import OptionParser # pylint: disable=deprecated-module from ranger import CONFDIR, CACHEDIR, DATADIR, USAGE from tempfile import mkdtemp from ranger.core.actions import Actions from ranger.config import commands as commands_default from importlib import util from importlib.machinery import SourceFileLoader from errno import EEXIST) and context including class names, function names, or small code snippets from other files: # Path: ranger.py # ARGV = sys.argv[1:sys.argv.index('--')] if '--' in sys.argv else sys.argv[1:] . Output only the next line.
'ranger version: {0}'.format(VERSION),
Based on the snippet: <|code_start|>context is a struct which contains all entries of CONTEXT_KEYS, associated with either True or False. Define which colorscheme in your settings (e.g. ~/.config/ranger/rc.conf): set colorscheme yourschemename """ from __future__ import (absolute_import, division, print_function) class ColorSchemeError(Exception): pass class ColorScheme(object): """This is the class that colorschemes must inherit from. it defines the get() method, which returns the color tuple which fits to the given keys. """ @cached_function def get(self, *keys): """Returns the (fg, bg, attr) for the given keys. Using this function rather than use() will cache all colors for faster access. """ <|code_end|> , predict the immediate next line with the help of imports: import os.path import ranger from curses import color_pair from io import open from ranger.gui.color import get_color from ranger.gui.context import Context from ranger.core.main import allow_access_to_confdir from ranger.ext.cached_function import cached_function from ranger.ext.iter_tools import flatten and context (classes, functions, sometimes code) from other files: # Path: ranger/gui/context.py # class Context(object): # pylint: disable=too-few-public-methods # # def __init__(self, keys): # # set all given keys to True # dictionary = self.__dict__ # for key in keys: # dictionary[key] = True # # Path: ranger/core/main.py # def allow_access_to_confdir(confdir, allow): # from errno import EEXIST # # if allow: # try: # os.makedirs(confdir) # except OSError as err: # if err.errno != EEXIST: # EEXIST means it already exists # print("This configuration directory could not be created:") # print(confdir) # print("To run ranger without the need for configuration") # print("files, use the --clean option.") # raise SystemExit # else: # LOG.debug("Created config directory '%s'", confdir) # if confdir not in sys.path: # sys.path[0:0] = [confdir] # else: # if sys.path[0] == confdir: # del sys.path[0] # # Path: ranger/ext/iter_tools.py # def flatten(lst): # """Flatten an iterable. # # All contained tuples, lists, deques and sets are replaced by their # elements and flattened as well. # # >>> l = [1, 2, [3, [4], [5, 6]], 7] # >>> list(flatten(l)) # [1, 2, 3, 4, 5, 6, 7] # >>> list(flatten(())) # [] # """ # for elem in lst: # if isinstance(elem, (tuple, list, set, deque)): # for subelem in flatten(elem): # yield subelem # else: # yield elem . Output only the next line.
context = Context(keys)
Here is a snippet: <|code_start|> return issubclass(cls, ColorScheme) except TypeError: return False # create ~/.config/ranger/colorschemes/__init__.py if it doesn't exist if usecustom: if os.path.exists(signal.fm.confpath('colorschemes')): initpy = signal.fm.confpath('colorschemes', '__init__.py') if not os.path.exists(initpy): with open(initpy, "a", encoding="utf-8"): # Just create the file pass if usecustom and \ exists(signal.fm.confpath('colorschemes', scheme_name)): scheme_supermodule = 'colorschemes' elif exists(signal.fm.relpath('colorschemes', scheme_name)): scheme_supermodule = 'ranger.colorschemes' usecustom = False else: scheme_supermodule = None # found no matching file. if scheme_supermodule is None: if signal.previous and isinstance(signal.previous, ColorScheme): signal.value = signal.previous else: signal.value = ColorScheme() raise ColorSchemeError("Cannot locate colorscheme `%s'" % scheme_name) else: if usecustom: <|code_end|> . Write the next line using the current file imports: import os.path import ranger from curses import color_pair from io import open from ranger.gui.color import get_color from ranger.gui.context import Context from ranger.core.main import allow_access_to_confdir from ranger.ext.cached_function import cached_function from ranger.ext.iter_tools import flatten and context from other files: # Path: ranger/gui/context.py # class Context(object): # pylint: disable=too-few-public-methods # # def __init__(self, keys): # # set all given keys to True # dictionary = self.__dict__ # for key in keys: # dictionary[key] = True # # Path: ranger/core/main.py # def allow_access_to_confdir(confdir, allow): # from errno import EEXIST # # if allow: # try: # os.makedirs(confdir) # except OSError as err: # if err.errno != EEXIST: # EEXIST means it already exists # print("This configuration directory could not be created:") # print(confdir) # print("To run ranger without the need for configuration") # print("files, use the --clean option.") # raise SystemExit # else: # LOG.debug("Created config directory '%s'", confdir) # if confdir not in sys.path: # sys.path[0:0] = [confdir] # else: # if sys.path[0] == confdir: # del sys.path[0] # # Path: ranger/ext/iter_tools.py # def flatten(lst): # """Flatten an iterable. # # All contained tuples, lists, deques and sets are replaced by their # elements and flattened as well. # # >>> l = [1, 2, [3, [4], [5, 6]], 7] # >>> list(flatten(l)) # [1, 2, 3, 4, 5, 6, 7] # >>> list(flatten(())) # [] # """ # for elem in lst: # if isinstance(elem, (tuple, list, set, deque)): # for subelem in flatten(elem): # yield subelem # else: # yield elem , which may include functions, classes, or code. Output only the next line.
allow_access_to_confdir(ranger.args.confdir, True)
Predict the next line for this snippet: <|code_start|> pass class ColorScheme(object): """This is the class that colorschemes must inherit from. it defines the get() method, which returns the color tuple which fits to the given keys. """ @cached_function def get(self, *keys): """Returns the (fg, bg, attr) for the given keys. Using this function rather than use() will cache all colors for faster access. """ context = Context(keys) color = self.use(context) if len(color) != 3 or not all(isinstance(value, int) for value in color): raise ValueError("Bad Value from colorscheme. Need " "a tuple of (foreground_color, background_color, attribute).") return color @cached_function def get_attr(self, *keys): """Returns the curses attribute for the specified keys Ready to use for curses.setattr() """ <|code_end|> with the help of current file imports: import os.path import ranger from curses import color_pair from io import open from ranger.gui.color import get_color from ranger.gui.context import Context from ranger.core.main import allow_access_to_confdir from ranger.ext.cached_function import cached_function from ranger.ext.iter_tools import flatten and context from other files: # Path: ranger/gui/context.py # class Context(object): # pylint: disable=too-few-public-methods # # def __init__(self, keys): # # set all given keys to True # dictionary = self.__dict__ # for key in keys: # dictionary[key] = True # # Path: ranger/core/main.py # def allow_access_to_confdir(confdir, allow): # from errno import EEXIST # # if allow: # try: # os.makedirs(confdir) # except OSError as err: # if err.errno != EEXIST: # EEXIST means it already exists # print("This configuration directory could not be created:") # print(confdir) # print("To run ranger without the need for configuration") # print("files, use the --clean option.") # raise SystemExit # else: # LOG.debug("Created config directory '%s'", confdir) # if confdir not in sys.path: # sys.path[0:0] = [confdir] # else: # if sys.path[0] == confdir: # del sys.path[0] # # Path: ranger/ext/iter_tools.py # def flatten(lst): # """Flatten an iterable. # # All contained tuples, lists, deques and sets are replaced by their # elements and flattened as well. # # >>> l = [1, 2, [3, [4], [5, 6]], 7] # >>> list(flatten(l)) # [1, 2, 3, 4, 5, 6, 7] # >>> list(flatten(())) # [] # """ # for elem in lst: # if isinstance(elem, (tuple, list, set, deque)): # for subelem in flatten(elem): # yield subelem # else: # yield elem , which may contain function names, class names, or code. Output only the next line.
fg, bg, attr = self.get(*flatten(keys))
Given snippet: <|code_start|> log = logging.getLogger(__name__) def run( tracked_entities: List[TrackedEntity], *, sender_id: str, receiver_id: str, country: str, receiverorganization: str, receivercountrycode: str, ): root = E.ichicsr(lang="en") <|code_end|> , continue by predicting the next line. Consider current file imports: import logging from typing import List from lxml.builder import E from .e2b_resources import build_messageheader, build_safetyreport, print_root from .models.e2b import TrackedEntity and context: # Path: dhis2_core/src/dhis2/e2b/e2b_resources.py # def build_messageheader(root: etree.Element, sender_id: str, receiver_id: str): # mh = E.ichicsrmessageheader( # E.messagetype("ichicsr"), # E.messageformatversion("2.1"), # E.messageformatrelease("2.0"), # E.messagenumb(str(uuid4())), # E.messagesenderidentifier(sender_id), # E.messagereceiveridentifier(receiver_id), # E.messagedateformat("204"), # E.messagedate(date_format_204(datetime.now())), # ) # # root.append(mh) # # def build_safetyreport( # root: etree.Element, # te: TrackedEntity, # en: Enrollment, # country: str, # receiverorganization: str, # receivercountrycode: str, # ): # sr = etree.SubElement(root, "safetyreport") # # id = get_attribute_value("h5FuguPFF2j", te) # # if country: # country = country.upper() # # if id: # id = f"{country}-{id}" # else: # id = f"{country}" # # sr.append(E.safetyreportversion("1")) # sr.append(E.safetyreportid(id)) # sr.append(E.primarysourcecountry(country)) # sr.append(E.occurcountry(country)) # sr.append(E.transmissiondateformat("102")) # sr.append(E.transmissiondate(date_format_102(datetime.now()))) # sr.append(E.reporttype("1")) # sr.append(E.serious(get_yes_no("fq1c1A3EOX5", te))) # # dead = get_yes_no("DOA6ZFMro84", te) == "1" # # if dead: # sr.append(E.seriousnessdeath("1")) # else: # sr.append(E.seriousnessdeath("2")) # # sr.append(E.seriousnesslifethreatening(get_yes_no("lATDYNmTLKD", te))) # sr.append(E.seriousnesshospitalization(get_yes_no("Il1lTfknLdd", te))) # sr.append(E.seriousnessdisabling(get_yes_no("lsO8n8ZmLAB", te))) # sr.append(E.seriousnesscongenitalanomali(get_yes_no("lSBsxcQU0kO", te))) # sr.append(E.seriousnessother(get_yes_no("tWcNgbkOETR", te))) # sr.append(E.receivedateformat("102")) # sr.append(E.receivedate(date_format_102(datetime.now()))) # sr.append(E.receiptdateformat("102")) # sr.append(E.receiptdate(date_format_102(datetime.now()))) # sr.append(E.additionaldocument("2")) # # sr.append(E.fulfillexpeditecriteria("1")) # # reporter_name = get_data_value("uZ9c4fKXuNS", te) # qualification = "1" if reporter_name.upper().startswith("DR ") else "3" # # sr.append( # E.primarysource( # E.reportergivename(reporter_name), # E.reporterorganization(get_data_value("Q20pEixZxCs", te)), # TODO resolve org unit # E.qualification(qualification), # ) # ) # # sr.append( # E.sender( # E.senderorganization("DHIS2"), # ) # ) # # sr.append( # E.receiver( # E.receivertype("5"), # E.receiverorganization(receiverorganization), # E.receivercountrycode(receivercountrycode), # ) # ) # # build_safetyreport_patient(sr, te) # # def print_root(root: etree.Element, pretty_print: bool = True): # print( # etree.tostring( # root, # pretty_print=pretty_print, # standalone=False, # encoding="UTF-8", # doctype='<!DOCTYPE ichicsr SYSTEM "http://eudravigilance.ema.europa.eu/dtd/icsr21xml.dtd">', # ).decode() # ) # # Path: dhis2_core/src/dhis2/e2b/models/e2b.py # class TrackedEntity(BaseModel): # created: datetime # lastUpdated: datetime # trackedEntityInstance: str # trackedEntityType: str # orgUnit: str # storedBy: Optional[str] # enrollments: List[Enrollment] = [] # attributes: Union[Dict[str, AttributeValue], List[AttributeValue]] = [] which might include code, classes, or functions. Output only the next line.
build_messageheader(root, sender_id, receiver_id)
Based on the snippet: <|code_start|> log = logging.getLogger(__name__) def run( tracked_entities: List[TrackedEntity], *, sender_id: str, receiver_id: str, country: str, receiverorganization: str, receivercountrycode: str, ): root = E.ichicsr(lang="en") build_messageheader(root, sender_id, receiver_id) for te in tracked_entities: <|code_end|> , predict the immediate next line with the help of imports: import logging from typing import List from lxml.builder import E from .e2b_resources import build_messageheader, build_safetyreport, print_root from .models.e2b import TrackedEntity and context (classes, functions, sometimes code) from other files: # Path: dhis2_core/src/dhis2/e2b/e2b_resources.py # def build_messageheader(root: etree.Element, sender_id: str, receiver_id: str): # mh = E.ichicsrmessageheader( # E.messagetype("ichicsr"), # E.messageformatversion("2.1"), # E.messageformatrelease("2.0"), # E.messagenumb(str(uuid4())), # E.messagesenderidentifier(sender_id), # E.messagereceiveridentifier(receiver_id), # E.messagedateformat("204"), # E.messagedate(date_format_204(datetime.now())), # ) # # root.append(mh) # # def build_safetyreport( # root: etree.Element, # te: TrackedEntity, # en: Enrollment, # country: str, # receiverorganization: str, # receivercountrycode: str, # ): # sr = etree.SubElement(root, "safetyreport") # # id = get_attribute_value("h5FuguPFF2j", te) # # if country: # country = country.upper() # # if id: # id = f"{country}-{id}" # else: # id = f"{country}" # # sr.append(E.safetyreportversion("1")) # sr.append(E.safetyreportid(id)) # sr.append(E.primarysourcecountry(country)) # sr.append(E.occurcountry(country)) # sr.append(E.transmissiondateformat("102")) # sr.append(E.transmissiondate(date_format_102(datetime.now()))) # sr.append(E.reporttype("1")) # sr.append(E.serious(get_yes_no("fq1c1A3EOX5", te))) # # dead = get_yes_no("DOA6ZFMro84", te) == "1" # # if dead: # sr.append(E.seriousnessdeath("1")) # else: # sr.append(E.seriousnessdeath("2")) # # sr.append(E.seriousnesslifethreatening(get_yes_no("lATDYNmTLKD", te))) # sr.append(E.seriousnesshospitalization(get_yes_no("Il1lTfknLdd", te))) # sr.append(E.seriousnessdisabling(get_yes_no("lsO8n8ZmLAB", te))) # sr.append(E.seriousnesscongenitalanomali(get_yes_no("lSBsxcQU0kO", te))) # sr.append(E.seriousnessother(get_yes_no("tWcNgbkOETR", te))) # sr.append(E.receivedateformat("102")) # sr.append(E.receivedate(date_format_102(datetime.now()))) # sr.append(E.receiptdateformat("102")) # sr.append(E.receiptdate(date_format_102(datetime.now()))) # sr.append(E.additionaldocument("2")) # # sr.append(E.fulfillexpeditecriteria("1")) # # reporter_name = get_data_value("uZ9c4fKXuNS", te) # qualification = "1" if reporter_name.upper().startswith("DR ") else "3" # # sr.append( # E.primarysource( # E.reportergivename(reporter_name), # E.reporterorganization(get_data_value("Q20pEixZxCs", te)), # TODO resolve org unit # E.qualification(qualification), # ) # ) # # sr.append( # E.sender( # E.senderorganization("DHIS2"), # ) # ) # # sr.append( # E.receiver( # E.receivertype("5"), # E.receiverorganization(receiverorganization), # E.receivercountrycode(receivercountrycode), # ) # ) # # build_safetyreport_patient(sr, te) # # def print_root(root: etree.Element, pretty_print: bool = True): # print( # etree.tostring( # root, # pretty_print=pretty_print, # standalone=False, # encoding="UTF-8", # doctype='<!DOCTYPE ichicsr SYSTEM "http://eudravigilance.ema.europa.eu/dtd/icsr21xml.dtd">', # ).decode() # ) # # Path: dhis2_core/src/dhis2/e2b/models/e2b.py # class TrackedEntity(BaseModel): # created: datetime # lastUpdated: datetime # trackedEntityInstance: str # trackedEntityType: str # orgUnit: str # storedBy: Optional[str] # enrollments: List[Enrollment] = [] # attributes: Union[Dict[str, AttributeValue], List[AttributeValue]] = [] . Output only the next line.
build_safetyreport(
Given snippet: <|code_start|> log = logging.getLogger(__name__) def run( tracked_entities: List[TrackedEntity], *, sender_id: str, receiver_id: str, country: str, receiverorganization: str, receivercountrycode: str, ): root = E.ichicsr(lang="en") build_messageheader(root, sender_id, receiver_id) for te in tracked_entities: build_safetyreport( root, te, te.enrollments[0], country, receiverorganization, receivercountrycode, ) <|code_end|> , continue by predicting the next line. Consider current file imports: import logging from typing import List from lxml.builder import E from .e2b_resources import build_messageheader, build_safetyreport, print_root from .models.e2b import TrackedEntity and context: # Path: dhis2_core/src/dhis2/e2b/e2b_resources.py # def build_messageheader(root: etree.Element, sender_id: str, receiver_id: str): # mh = E.ichicsrmessageheader( # E.messagetype("ichicsr"), # E.messageformatversion("2.1"), # E.messageformatrelease("2.0"), # E.messagenumb(str(uuid4())), # E.messagesenderidentifier(sender_id), # E.messagereceiveridentifier(receiver_id), # E.messagedateformat("204"), # E.messagedate(date_format_204(datetime.now())), # ) # # root.append(mh) # # def build_safetyreport( # root: etree.Element, # te: TrackedEntity, # en: Enrollment, # country: str, # receiverorganization: str, # receivercountrycode: str, # ): # sr = etree.SubElement(root, "safetyreport") # # id = get_attribute_value("h5FuguPFF2j", te) # # if country: # country = country.upper() # # if id: # id = f"{country}-{id}" # else: # id = f"{country}" # # sr.append(E.safetyreportversion("1")) # sr.append(E.safetyreportid(id)) # sr.append(E.primarysourcecountry(country)) # sr.append(E.occurcountry(country)) # sr.append(E.transmissiondateformat("102")) # sr.append(E.transmissiondate(date_format_102(datetime.now()))) # sr.append(E.reporttype("1")) # sr.append(E.serious(get_yes_no("fq1c1A3EOX5", te))) # # dead = get_yes_no("DOA6ZFMro84", te) == "1" # # if dead: # sr.append(E.seriousnessdeath("1")) # else: # sr.append(E.seriousnessdeath("2")) # # sr.append(E.seriousnesslifethreatening(get_yes_no("lATDYNmTLKD", te))) # sr.append(E.seriousnesshospitalization(get_yes_no("Il1lTfknLdd", te))) # sr.append(E.seriousnessdisabling(get_yes_no("lsO8n8ZmLAB", te))) # sr.append(E.seriousnesscongenitalanomali(get_yes_no("lSBsxcQU0kO", te))) # sr.append(E.seriousnessother(get_yes_no("tWcNgbkOETR", te))) # sr.append(E.receivedateformat("102")) # sr.append(E.receivedate(date_format_102(datetime.now()))) # sr.append(E.receiptdateformat("102")) # sr.append(E.receiptdate(date_format_102(datetime.now()))) # sr.append(E.additionaldocument("2")) # # sr.append(E.fulfillexpeditecriteria("1")) # # reporter_name = get_data_value("uZ9c4fKXuNS", te) # qualification = "1" if reporter_name.upper().startswith("DR ") else "3" # # sr.append( # E.primarysource( # E.reportergivename(reporter_name), # E.reporterorganization(get_data_value("Q20pEixZxCs", te)), # TODO resolve org unit # E.qualification(qualification), # ) # ) # # sr.append( # E.sender( # E.senderorganization("DHIS2"), # ) # ) # # sr.append( # E.receiver( # E.receivertype("5"), # E.receiverorganization(receiverorganization), # E.receivercountrycode(receivercountrycode), # ) # ) # # build_safetyreport_patient(sr, te) # # def print_root(root: etree.Element, pretty_print: bool = True): # print( # etree.tostring( # root, # pretty_print=pretty_print, # standalone=False, # encoding="UTF-8", # doctype='<!DOCTYPE ichicsr SYSTEM "http://eudravigilance.ema.europa.eu/dtd/icsr21xml.dtd">', # ).decode() # ) # # Path: dhis2_core/src/dhis2/e2b/models/e2b.py # class TrackedEntity(BaseModel): # created: datetime # lastUpdated: datetime # trackedEntityInstance: str # trackedEntityType: str # orgUnit: str # storedBy: Optional[str] # enrollments: List[Enrollment] = [] # attributes: Union[Dict[str, AttributeValue], List[AttributeValue]] = [] which might include code, classes, or functions. Output only the next line.
print_root(root)
Using the snippet: <|code_start|> try: except ImportError: log = logging.getLogger(__name__) def parse_file(filename: str) -> Dict[str, Any]: data: Dict[str, Any] = {} fp = Path(filename).resolve() if not fp.exists() or not fp.is_file(): return None try: with open(fp) as f: if filename.endswith(".yml"): data = load(f, Loader=Loader) elif filename.endswith(".json"): data = json.load(f) except Exception as e: # noqa print(e) return None return data <|code_end|> , determine the next line of code. You have imports: import json import logging from pathlib import Path from typing import Any, Dict, List from yaml import load as load from .http import BaseHttpRequest from .inventory import HostResolved from .metadata.models import Schema, Schemas from yaml import CLoader as Loader from yaml import Loader and context (class names, function names, or code) available: # Path: dhis2_core/src/dhis2/core/http.py # class BaseHttpRequest: # def __init__(self, host: HostResolved, format: Union[MediaFormat, str] = MediaFormat.json): # self.host = host # self.format = format # # def get( # self, # path, # params={}, # headers={}, # ): # url = self._get_url(path) # headers = self._get_headers(headers) # auth = self._get_auth() # params = self._get_params(params) # # log.info(f"Starting GET request '{url}' with params='{params}'") # # response = requests.get( # url=url, # headers=headers, # params=params, # auth=auth, # ) # # log.info(f"Finished GET request '{response.request.url}'' with status code '{response.status_code}''") # # if not response.ok: # return self._handle_errors(response) # # data = None # # if MediaFormat.json == self.format: # data = response.json() # else: # data = response.text # # return data # # def post( # self, # path, # data, # params={}, # headers={}, # ): # url = self._get_url(path) # headers = self._get_headers(headers) # auth = self._get_auth() # params = self._get_params(params) # # if not isinstance(data, str): # data = json.dumps(data) # # if log.isEnabledFor(logging.DEBUG): # log.info(f"Starting POST request '{url}' with params='{params}' and data={data}") # else: # log.info(f"Starting POST request '{url} with params={params}'") # # response = requests.post( # url=url, # headers=headers, # params=params, # auth=auth, # data=data, # ) # # log.info(f"Finished POST request '{response.request.url}'' with status code '{response.status_code}''") # # if not response.ok: # return self._handle_errors(response) # # if MediaFormat.json == self.format: # data = response.json() # else: # data = response.text # # return data # # def _handle_errors(self, response: Response): # if 401 == response.status_code: # log.error(f"Invalid login credentials for '{self.host.key}''") # if 404 == response.status_code: # log.error(f"Invalid url '{response.request.url}', please check 'baseUrl' for '{self.host.key}'") # else: # log.error(f"Unhandled status code {response.status_code}={response.text}") # # sys.exit(-1) # # def _get_auth(self) -> Union[Tuple[str], None]: # if "http-basic" == self.host.auth.type: # return (self.host.auth.username, self.host.auth.password) # # return None # # def _get_headers(self, headers: Dict[str, str] = {}) -> Dict[str, str]: # headers = deepcopy(headers) # # if isinstance(self.format, MediaFormat): # headers["Content-Type"] = self.format.value # headers["Accept"] = self.format.value # else: # headers["Content-Type"] = self.format # headers["Accept"] = self.format # # headers["X-Requested-With"] = "XMLHttpRequest" # # headers.update(self.host.headers) # # return headers # # def _get_params(self, params={}) -> Dict[str, str]: # params = deepcopy(params) # params.update(self.host.params) # # return params # # def _get_url(self, path="") -> str: # return f"{self.host.baseUrl}/{path}" # # Path: dhis2_core/src/dhis2/core/inventory.py # class HostResolved(BaseModel): # type: Union[HostType, str] = HostType.dhis2 # key: str # baseUrl: str # headers: Mapping[str, str] = {} # params: Mapping[str, str] = {} # auth: Union[NoopAuthtype, BasicAuthtype] # # Path: dhis2_core/src/dhis2/core/metadata/models/schema.py # class Schema(BaseModel): # klass: str # shareable: bool # metadata: bool # relativeApiEndpoint: Optional[str] # plural: str # displayName: str # singular: str # secondaryMetadata: bool # collectionName: Optional[str] # implicitPrivateAuthority: bool # nameableObject: bool # href: str # subscribable: bool # order: int # translatable: bool # identifiableObject: bool # favoritable: bool # subscribableObject: bool # dataShareable: bool # apiEndpoint: Optional[str] # embeddedObject: bool # defaultPrivate: str # name: str # namespace: Optional[str] # persisted: bool # references: List[str] = [] # authorities: List[Authority] = [] # properties: List[Property] = [] # # class Schemas(BaseModel): # schemas: List[Schema] = [] . Output only the next line.
def load_and_parse_schema(host: HostResolved) -> List[Schema]:
Next line prediction: <|code_start|> try: except ImportError: log = logging.getLogger(__name__) def parse_file(filename: str) -> Dict[str, Any]: data: Dict[str, Any] = {} fp = Path(filename).resolve() if not fp.exists() or not fp.is_file(): return None try: with open(fp) as f: if filename.endswith(".yml"): data = load(f, Loader=Loader) elif filename.endswith(".json"): data = json.load(f) except Exception as e: # noqa print(e) return None return data <|code_end|> . Use current file imports: (import json import logging from pathlib import Path from typing import Any, Dict, List from yaml import load as load from .http import BaseHttpRequest from .inventory import HostResolved from .metadata.models import Schema, Schemas from yaml import CLoader as Loader from yaml import Loader) and context including class names, function names, or small code snippets from other files: # Path: dhis2_core/src/dhis2/core/http.py # class BaseHttpRequest: # def __init__(self, host: HostResolved, format: Union[MediaFormat, str] = MediaFormat.json): # self.host = host # self.format = format # # def get( # self, # path, # params={}, # headers={}, # ): # url = self._get_url(path) # headers = self._get_headers(headers) # auth = self._get_auth() # params = self._get_params(params) # # log.info(f"Starting GET request '{url}' with params='{params}'") # # response = requests.get( # url=url, # headers=headers, # params=params, # auth=auth, # ) # # log.info(f"Finished GET request '{response.request.url}'' with status code '{response.status_code}''") # # if not response.ok: # return self._handle_errors(response) # # data = None # # if MediaFormat.json == self.format: # data = response.json() # else: # data = response.text # # return data # # def post( # self, # path, # data, # params={}, # headers={}, # ): # url = self._get_url(path) # headers = self._get_headers(headers) # auth = self._get_auth() # params = self._get_params(params) # # if not isinstance(data, str): # data = json.dumps(data) # # if log.isEnabledFor(logging.DEBUG): # log.info(f"Starting POST request '{url}' with params='{params}' and data={data}") # else: # log.info(f"Starting POST request '{url} with params={params}'") # # response = requests.post( # url=url, # headers=headers, # params=params, # auth=auth, # data=data, # ) # # log.info(f"Finished POST request '{response.request.url}'' with status code '{response.status_code}''") # # if not response.ok: # return self._handle_errors(response) # # if MediaFormat.json == self.format: # data = response.json() # else: # data = response.text # # return data # # def _handle_errors(self, response: Response): # if 401 == response.status_code: # log.error(f"Invalid login credentials for '{self.host.key}''") # if 404 == response.status_code: # log.error(f"Invalid url '{response.request.url}', please check 'baseUrl' for '{self.host.key}'") # else: # log.error(f"Unhandled status code {response.status_code}={response.text}") # # sys.exit(-1) # # def _get_auth(self) -> Union[Tuple[str], None]: # if "http-basic" == self.host.auth.type: # return (self.host.auth.username, self.host.auth.password) # # return None # # def _get_headers(self, headers: Dict[str, str] = {}) -> Dict[str, str]: # headers = deepcopy(headers) # # if isinstance(self.format, MediaFormat): # headers["Content-Type"] = self.format.value # headers["Accept"] = self.format.value # else: # headers["Content-Type"] = self.format # headers["Accept"] = self.format # # headers["X-Requested-With"] = "XMLHttpRequest" # # headers.update(self.host.headers) # # return headers # # def _get_params(self, params={}) -> Dict[str, str]: # params = deepcopy(params) # params.update(self.host.params) # # return params # # def _get_url(self, path="") -> str: # return f"{self.host.baseUrl}/{path}" # # Path: dhis2_core/src/dhis2/core/inventory.py # class HostResolved(BaseModel): # type: Union[HostType, str] = HostType.dhis2 # key: str # baseUrl: str # headers: Mapping[str, str] = {} # params: Mapping[str, str] = {} # auth: Union[NoopAuthtype, BasicAuthtype] # # Path: dhis2_core/src/dhis2/core/metadata/models/schema.py # class Schema(BaseModel): # klass: str # shareable: bool # metadata: bool # relativeApiEndpoint: Optional[str] # plural: str # displayName: str # singular: str # secondaryMetadata: bool # collectionName: Optional[str] # implicitPrivateAuthority: bool # nameableObject: bool # href: str # subscribable: bool # order: int # translatable: bool # identifiableObject: bool # favoritable: bool # subscribableObject: bool # dataShareable: bool # apiEndpoint: Optional[str] # embeddedObject: bool # defaultPrivate: str # name: str # namespace: Optional[str] # persisted: bool # references: List[str] = [] # authorities: List[Authority] = [] # properties: List[Property] = [] # # class Schemas(BaseModel): # schemas: List[Schema] = [] . Output only the next line.
def load_and_parse_schema(host: HostResolved) -> List[Schema]:
Given the following code snippet before the placeholder: <|code_start|> @click.group("code-list") def cli_code_list(): """ Various commands for code-list data exchange """ pass @cli_code_list.command("icd11") @click.argument("host-id") @click.option("--linearizationname", default="mms") @click.option("--release-id", default="2020-09") @click.option("--language", default="en") @click.option("--root-id") @click.pass_obj def cmd_code_list_icd11( ctx, host_id: str, linearizationname: str, release_id: str, language: str, root_id: str, ): """ Generate dhis2 option sets from icd11 source **experimental** """ host = resolve_one(host_id, ctx.inventory) if not "icd11" == host.type: log.error(f"Invalid source type '{host.type}', only 'icd11' sources are allowed") sys.exit(-1) <|code_end|> , predict the next line using imports from the current file: import json import logging import sys import click from dhis2.core.inventory import resolve_one from dhis2.core.utils import parse_file from . import svcm from .icd11 import fetch_icd11_dhis2_option_sets from .icd10 import fetch_icd10_dhis2_option_sets and context including class names, function names, and sometimes code from other files: # Path: dhis2_core/src/dhis2/code_list/icd11.py # def fetch_icd11_dhis2_option_sets( # host: HostResolved, # linearizationname: str, # release_id: str, # language: str, # root_id: str, # ): # log.info("ICD11 export job started") # # icd11 = _icd11_fetch_all(host, linearizationname, release_id, language, root_id) # # log.info("Converting to DHIS2 optionset/options payload") # dhis2 = _dhis2_make_option_sets(icd11) # # log.info("ICD11 export job finished") # # return dhis2 # # Path: dhis2_core/src/dhis2/code_list/icd10.py # def fetch_icd10_dhis2_option_sets( # host: HostResolved, # release_id: str, # language: str, # root_id: str, # ): # log.info("ICD10 export job started") # # icd10 = _icd10_fetch_all(host, release_id, language, root_id) # # log.info("Converting to DHIS2 optionset/options payload") # dhis2 = _dhis2_make_option_sets(icd10) # # log.info("ICD10 export job finished") # # return dhis2 . Output only the next line.
option_sets = fetch_icd11_dhis2_option_sets(
Based on the snippet: <|code_start|> linearizationname=linearizationname, release_id=release_id, language=language, root_id=root_id, ) if option_sets: click.echo(json.dumps(option_sets, indent=2, ensure_ascii=False)) @cli_code_list.command("icd10") @click.argument("host-id") @click.option("--release-id", default="2016") @click.option("--language", default="en") @click.option("--root-id") @click.pass_obj def cmd_code_list_icd10( ctx, host_id: str, release_id: str, language: str, root_id: str, ): """ Generate dhis2 option sets from icd10 source **experimental** """ host = resolve_one(host_id, ctx.inventory) if not "icd10" == host.type: log.error(f"Invalid source type '{host.type}', only 'icd10' sources are allowed") sys.exit(-1) <|code_end|> , predict the immediate next line with the help of imports: import json import logging import sys import click from dhis2.core.inventory import resolve_one from dhis2.core.utils import parse_file from . import svcm from .icd11 import fetch_icd11_dhis2_option_sets from .icd10 import fetch_icd10_dhis2_option_sets and context (classes, functions, sometimes code) from other files: # Path: dhis2_core/src/dhis2/code_list/icd11.py # def fetch_icd11_dhis2_option_sets( # host: HostResolved, # linearizationname: str, # release_id: str, # language: str, # root_id: str, # ): # log.info("ICD11 export job started") # # icd11 = _icd11_fetch_all(host, linearizationname, release_id, language, root_id) # # log.info("Converting to DHIS2 optionset/options payload") # dhis2 = _dhis2_make_option_sets(icd11) # # log.info("ICD11 export job finished") # # return dhis2 # # Path: dhis2_core/src/dhis2/code_list/icd10.py # def fetch_icd10_dhis2_option_sets( # host: HostResolved, # release_id: str, # language: str, # root_id: str, # ): # log.info("ICD10 export job started") # # icd10 = _icd10_fetch_all(host, release_id, language, root_id) # # log.info("Converting to DHIS2 optionset/options payload") # dhis2 = _dhis2_make_option_sets(icd10) # # log.info("ICD10 export job finished") # # return dhis2 . Output only the next line.
option_sets = fetch_icd10_dhis2_option_sets(
Given the following code snippet before the placeholder: <|code_start|> def date_format_102(dt: datetime) -> str: return dt.strftime("%Y%m%d") def date_format_204(dt: datetime) -> str: return dt.strftime("%Y%m%d%H%M%S") def date_format_203(dt: datetime) -> str: return dt.strftime("%Y%m%d%H%M") def get_attribute_value(at: str, te: TrackedEntity, defaultValue=None) -> Union[str, None]: av = te.attributes.get(at, defaultValue) if not av: return defaultValue if av.value: return av.value return defaultValue def get_data_value(de: str, te: TrackedEntity, idx: int = 0, defaultValue=None) -> Union[str, None]: <|code_end|> , predict the next line using imports from the current file: from datetime import datetime from typing import Union from .models.e2b import Enrollment, Event, EventDataValue, TrackedEntity and context including class names, function names, and sometimes code from other files: # Path: dhis2_core/src/dhis2/e2b/models/e2b.py # class Enrollment(BaseModel): # created: datetime # lastUpdated: datetime # enrollment: str # trackedEntityInstance: str # orgUnit: str # storedBy: Optional[str] # status: str # completedDate: Optional[str] # events: List[Event] = [] # attributes: Union[Dict[str, AttributeValue], List[AttributeValue]] = [] # # class Event(BaseModel): # created: datetime # lastUpdated: datetime # event: str # program: str # programStage: str # trackedEntityInstance: str # orgUnit: str # status: str # dueDate: datetime # eventDate: datetime # completedDate: Optional[str] # storedBy: Optional[str] # dataValues: Union[Dict[str, EventDataValue], List[EventDataValue]] = [] # # class EventDataValue(BaseModel): # created: datetime # lastUpdated: datetime # dataElement: str # value: str # providedElsewhere: bool # storedBy: Optional[str] # # class TrackedEntity(BaseModel): # created: datetime # lastUpdated: datetime # trackedEntityInstance: str # trackedEntityType: str # orgUnit: str # storedBy: Optional[str] # enrollments: List[Enrollment] = [] # attributes: Union[Dict[str, AttributeValue], List[AttributeValue]] = [] . Output only the next line.
en: Enrollment = te.enrollments[idx]
Predict the next line after this snippet: <|code_start|> def date_format_102(dt: datetime) -> str: return dt.strftime("%Y%m%d") def date_format_204(dt: datetime) -> str: return dt.strftime("%Y%m%d%H%M%S") def date_format_203(dt: datetime) -> str: return dt.strftime("%Y%m%d%H%M") def get_attribute_value(at: str, te: TrackedEntity, defaultValue=None) -> Union[str, None]: av = te.attributes.get(at, defaultValue) if not av: return defaultValue if av.value: return av.value return defaultValue def get_data_value(de: str, te: TrackedEntity, idx: int = 0, defaultValue=None) -> Union[str, None]: en: Enrollment = te.enrollments[idx] <|code_end|> using the current file's imports: from datetime import datetime from typing import Union from .models.e2b import Enrollment, Event, EventDataValue, TrackedEntity and any relevant context from other files: # Path: dhis2_core/src/dhis2/e2b/models/e2b.py # class Enrollment(BaseModel): # created: datetime # lastUpdated: datetime # enrollment: str # trackedEntityInstance: str # orgUnit: str # storedBy: Optional[str] # status: str # completedDate: Optional[str] # events: List[Event] = [] # attributes: Union[Dict[str, AttributeValue], List[AttributeValue]] = [] # # class Event(BaseModel): # created: datetime # lastUpdated: datetime # event: str # program: str # programStage: str # trackedEntityInstance: str # orgUnit: str # status: str # dueDate: datetime # eventDate: datetime # completedDate: Optional[str] # storedBy: Optional[str] # dataValues: Union[Dict[str, EventDataValue], List[EventDataValue]] = [] # # class EventDataValue(BaseModel): # created: datetime # lastUpdated: datetime # dataElement: str # value: str # providedElsewhere: bool # storedBy: Optional[str] # # class TrackedEntity(BaseModel): # created: datetime # lastUpdated: datetime # trackedEntityInstance: str # trackedEntityType: str # orgUnit: str # storedBy: Optional[str] # enrollments: List[Enrollment] = [] # attributes: Union[Dict[str, AttributeValue], List[AttributeValue]] = [] . Output only the next line.
ev: Event = en.events["so8YZ9J3MeO"] # AEFI stage
Predict the next line for this snippet: <|code_start|> return dt.strftime("%Y%m%d") def date_format_204(dt: datetime) -> str: return dt.strftime("%Y%m%d%H%M%S") def date_format_203(dt: datetime) -> str: return dt.strftime("%Y%m%d%H%M") def get_attribute_value(at: str, te: TrackedEntity, defaultValue=None) -> Union[str, None]: av = te.attributes.get(at, defaultValue) if not av: return defaultValue if av.value: return av.value return defaultValue def get_data_value(de: str, te: TrackedEntity, idx: int = 0, defaultValue=None) -> Union[str, None]: en: Enrollment = te.enrollments[idx] ev: Event = en.events["so8YZ9J3MeO"] # AEFI stage if de not in ev.dataValues: return defaultValue <|code_end|> with the help of current file imports: from datetime import datetime from typing import Union from .models.e2b import Enrollment, Event, EventDataValue, TrackedEntity and context from other files: # Path: dhis2_core/src/dhis2/e2b/models/e2b.py # class Enrollment(BaseModel): # created: datetime # lastUpdated: datetime # enrollment: str # trackedEntityInstance: str # orgUnit: str # storedBy: Optional[str] # status: str # completedDate: Optional[str] # events: List[Event] = [] # attributes: Union[Dict[str, AttributeValue], List[AttributeValue]] = [] # # class Event(BaseModel): # created: datetime # lastUpdated: datetime # event: str # program: str # programStage: str # trackedEntityInstance: str # orgUnit: str # status: str # dueDate: datetime # eventDate: datetime # completedDate: Optional[str] # storedBy: Optional[str] # dataValues: Union[Dict[str, EventDataValue], List[EventDataValue]] = [] # # class EventDataValue(BaseModel): # created: datetime # lastUpdated: datetime # dataElement: str # value: str # providedElsewhere: bool # storedBy: Optional[str] # # class TrackedEntity(BaseModel): # created: datetime # lastUpdated: datetime # trackedEntityInstance: str # trackedEntityType: str # orgUnit: str # storedBy: Optional[str] # enrollments: List[Enrollment] = [] # attributes: Union[Dict[str, AttributeValue], List[AttributeValue]] = [] , which may contain function names, class names, or code. Output only the next line.
dv: EventDataValue = ev.dataValues[de]
Based on the snippet: <|code_start|> def date_format_102(dt: datetime) -> str: return dt.strftime("%Y%m%d") def date_format_204(dt: datetime) -> str: return dt.strftime("%Y%m%d%H%M%S") def date_format_203(dt: datetime) -> str: return dt.strftime("%Y%m%d%H%M") <|code_end|> , predict the immediate next line with the help of imports: from datetime import datetime from typing import Union from .models.e2b import Enrollment, Event, EventDataValue, TrackedEntity and context (classes, functions, sometimes code) from other files: # Path: dhis2_core/src/dhis2/e2b/models/e2b.py # class Enrollment(BaseModel): # created: datetime # lastUpdated: datetime # enrollment: str # trackedEntityInstance: str # orgUnit: str # storedBy: Optional[str] # status: str # completedDate: Optional[str] # events: List[Event] = [] # attributes: Union[Dict[str, AttributeValue], List[AttributeValue]] = [] # # class Event(BaseModel): # created: datetime # lastUpdated: datetime # event: str # program: str # programStage: str # trackedEntityInstance: str # orgUnit: str # status: str # dueDate: datetime # eventDate: datetime # completedDate: Optional[str] # storedBy: Optional[str] # dataValues: Union[Dict[str, EventDataValue], List[EventDataValue]] = [] # # class EventDataValue(BaseModel): # created: datetime # lastUpdated: datetime # dataElement: str # value: str # providedElsewhere: bool # storedBy: Optional[str] # # class TrackedEntity(BaseModel): # created: datetime # lastUpdated: datetime # trackedEntityInstance: str # trackedEntityType: str # orgUnit: str # storedBy: Optional[str] # enrollments: List[Enrollment] = [] # attributes: Union[Dict[str, AttributeValue], List[AttributeValue]] = [] . Output only the next line.
def get_attribute_value(at: str, te: TrackedEntity, defaultValue=None) -> Union[str, None]:
Using the snippet: <|code_start|> log = logging.getLogger(__name__) def _icd11_fetch( host: HostResolved, linearizationname: str, release_id: str, language: str, id: str, ): req = BaseHttpRequest(host) url = f"icd/release/11/{release_id}/{linearizationname}" if id: url = f"icd/release/11/{release_id}/{linearizationname}/{id}" data = req.get( url, headers={ "Accept-Language": language, "API-Version": "v2", }, ) <|code_end|> , determine the next line of code. You have imports: import logging from typing import List from dhis2.core.http import BaseHttpRequest from dhis2.core.inventory import HostResolved from .models.icd11 import LinearizationEntity and context (class names, function names, or code) available: # Path: dhis2_core/src/dhis2/code_list/models/icd11.py # class LinearizationEntity(BaseModel): # id: str = Field(alias="@id") # context: str = Field(alias="@context") # title: Optional[LanguageSpecificText] # definition: Optional[LanguageSpecificText] # longDefinition: Optional[LanguageSpecificText] # fullySpecifiedName: Optional[LanguageSpecificText] # source: Optional[str] # code: Optional[str] # codingNote: Optional[LanguageSpecificText] # blockId: Optional[str] # codeRange: Optional[str] # # # chapter : if the entity is a chapter. (i.e. at the top level of the classification # # block : higher level entity which don't have codes # # category : An ICD entity that bears a code # # classKind: Optional[Literal["block", "category", "chapter", "window"]] # child: Union[List[str], List["LinearizationEntity"]] = [] # parent: Union[List[str], List["LinearizationEntity"]] = [] # browserUrl: Optional[str] . Output only the next line.
return LinearizationEntity(**data)
Using the snippet: <|code_start|>#!/usr/bin/env python def require_program(host: HostResolved, pr: str) -> None: request = BaseHttpRequest(host) request.get(f"api/programs/{pr}") def get_aefi_patient(host: HostResolved, pr: str, te: str) -> TrackedEntity: require_program(host, pr) request = BaseHttpRequest(host) response = request.get( f"api/trackedEntityInstances/{te}", params={ "fields": "*", "program": pr, }, ) te = TrackedEntity(**response) <|code_end|> , determine the next line of code. You have imports: from typing import Dict from dhis2.core.http import BaseHttpRequest from dhis2.core.inventory import HostResolved, resolve_one from .models.e2b import AttributeValue, EventDataValue, TrackedEntity import click import dhis2.e2b.r2 as r2 and context (class names, function names, or code) available: # Path: dhis2_core/src/dhis2/e2b/models/e2b.py # class AttributeValue(BaseModel): # created: datetime # lastUpdated: datetime # attribute: str # value: str # storedBy: Optional[str] # # class EventDataValue(BaseModel): # created: datetime # lastUpdated: datetime # dataElement: str # value: str # providedElsewhere: bool # storedBy: Optional[str] # # class TrackedEntity(BaseModel): # created: datetime # lastUpdated: datetime # trackedEntityInstance: str # trackedEntityType: str # orgUnit: str # storedBy: Optional[str] # enrollments: List[Enrollment] = [] # attributes: Union[Dict[str, AttributeValue], List[AttributeValue]] = [] . Output only the next line.
attributes: Dict[str, AttributeValue] = {}
Using the snippet: <|code_start|> request.get(f"api/programs/{pr}") def get_aefi_patient(host: HostResolved, pr: str, te: str) -> TrackedEntity: require_program(host, pr) request = BaseHttpRequest(host) response = request.get( f"api/trackedEntityInstances/{te}", params={ "fields": "*", "program": pr, }, ) te = TrackedEntity(**response) attributes: Dict[str, AttributeValue] = {} for av in te.attributes: attributes[av.attribute] = av for en in te.enrollments: for av in en.attributes: attributes[av.attribute] = av del en.attributes events = {} for ev in en.events: <|code_end|> , determine the next line of code. You have imports: from typing import Dict from dhis2.core.http import BaseHttpRequest from dhis2.core.inventory import HostResolved, resolve_one from .models.e2b import AttributeValue, EventDataValue, TrackedEntity import click import dhis2.e2b.r2 as r2 and context (class names, function names, or code) available: # Path: dhis2_core/src/dhis2/e2b/models/e2b.py # class AttributeValue(BaseModel): # created: datetime # lastUpdated: datetime # attribute: str # value: str # storedBy: Optional[str] # # class EventDataValue(BaseModel): # created: datetime # lastUpdated: datetime # dataElement: str # value: str # providedElsewhere: bool # storedBy: Optional[str] # # class TrackedEntity(BaseModel): # created: datetime # lastUpdated: datetime # trackedEntityInstance: str # trackedEntityType: str # orgUnit: str # storedBy: Optional[str] # enrollments: List[Enrollment] = [] # attributes: Union[Dict[str, AttributeValue], List[AttributeValue]] = [] . Output only the next line.
dataValues: Dict[str, EventDataValue] = {}
Using the snippet: <|code_start|>#!/usr/bin/env python def require_program(host: HostResolved, pr: str) -> None: request = BaseHttpRequest(host) request.get(f"api/programs/{pr}") <|code_end|> , determine the next line of code. You have imports: from typing import Dict from dhis2.core.http import BaseHttpRequest from dhis2.core.inventory import HostResolved, resolve_one from .models.e2b import AttributeValue, EventDataValue, TrackedEntity import click import dhis2.e2b.r2 as r2 and context (class names, function names, or code) available: # Path: dhis2_core/src/dhis2/e2b/models/e2b.py # class AttributeValue(BaseModel): # created: datetime # lastUpdated: datetime # attribute: str # value: str # storedBy: Optional[str] # # class EventDataValue(BaseModel): # created: datetime # lastUpdated: datetime # dataElement: str # value: str # providedElsewhere: bool # storedBy: Optional[str] # # class TrackedEntity(BaseModel): # created: datetime # lastUpdated: datetime # trackedEntityInstance: str # trackedEntityType: str # orgUnit: str # storedBy: Optional[str] # enrollments: List[Enrollment] = [] # attributes: Union[Dict[str, AttributeValue], List[AttributeValue]] = [] . Output only the next line.
def get_aefi_patient(host: HostResolved, pr: str, te: str) -> TrackedEntity:
Using the snippet: <|code_start|> log.info("Doing nothing with result") return target_null host = resolve_one(id, inventory) if "dhis2" in host.type: log.error("'dhis2' target type is not currently supported") sys.exit(-1) log.info(f"Creating target from '{host.key}' with base url '{host.baseUrl}'") def target_push(data: Any): payload: Bundle = data[1] return BaseHttpRequest(host).post("", data=payload.as_json()) return target_push def transform(config: MCSDConfig, data: Any): host: HostResolved = data[0] payload: Dict[str, Any] = data[1] org_units: List[OrgUnit] = [] for org_unit in payload.get("organisationUnits", []): org_units.append(OrgUnit(**org_unit)) return ( host, <|code_end|> , determine the next line of code. You have imports: import json import logging import sys from typing import Any, Callable, Dict, List from dhis2.core.http import BaseHttpRequest from dhis2.core.inventory import HostResolved, Inventory, resolve_one from fhir.resources.bundle import Bundle from .mcsd_resources import build_bundle from .models.mcsd import MCSDConfig, OrgUnit and context (class names, function names, or code) available: # Path: dhis2_core/src/dhis2/facility_list/mcsd_resources.py # def build_bundle(org_units: List[OrgUnit], base_url: str) -> Bundle: # bundle = Bundle() # bundle.type = "transaction" # bundle.entry = [] # # log.info(f"Building FHIR bundle from '{len(org_units)}' organisation units") # # for org_unit in org_units: # bundle.entry.append(build_location_bundle_entry(org_unit, base_url)) # bundle.entry.append(build_organization_bundle_entry(org_unit, base_url)) # # return bundle # # Path: dhis2_core/src/dhis2/facility_list/models/mcsd.py # class MCSDConfig(BaseModel): # id: str = Field(default_factory=lambda: str(uuid4())) # source: MCSDSource # target: MCSDTarget # # class OrgUnit(BaseEntity): # geometry: Optional[OrgUnitGeometry] # parent: Optional[BaseEntity] . Output only the next line.
build_bundle(org_units, host.baseUrl),
Predict the next line for this snippet: <|code_start|> return target_log elif "null://" == id: log.info("Creating 'null://' target") def target_null(data: Any): log.info("Doing nothing with result") return target_null host = resolve_one(id, inventory) if "dhis2" in host.type: log.error("'dhis2' target type is not currently supported") sys.exit(-1) log.info(f"Creating target from '{host.key}' with base url '{host.baseUrl}'") def target_push(data: Any): payload: Bundle = data[1] return BaseHttpRequest(host).post("", data=payload.as_json()) return target_push def transform(config: MCSDConfig, data: Any): host: HostResolved = data[0] payload: Dict[str, Any] = data[1] <|code_end|> with the help of current file imports: import json import logging import sys from typing import Any, Callable, Dict, List from dhis2.core.http import BaseHttpRequest from dhis2.core.inventory import HostResolved, Inventory, resolve_one from fhir.resources.bundle import Bundle from .mcsd_resources import build_bundle from .models.mcsd import MCSDConfig, OrgUnit and context from other files: # Path: dhis2_core/src/dhis2/facility_list/mcsd_resources.py # def build_bundle(org_units: List[OrgUnit], base_url: str) -> Bundle: # bundle = Bundle() # bundle.type = "transaction" # bundle.entry = [] # # log.info(f"Building FHIR bundle from '{len(org_units)}' organisation units") # # for org_unit in org_units: # bundle.entry.append(build_location_bundle_entry(org_unit, base_url)) # bundle.entry.append(build_organization_bundle_entry(org_unit, base_url)) # # return bundle # # Path: dhis2_core/src/dhis2/facility_list/models/mcsd.py # class MCSDConfig(BaseModel): # id: str = Field(default_factory=lambda: str(uuid4())) # source: MCSDSource # target: MCSDTarget # # class OrgUnit(BaseEntity): # geometry: Optional[OrgUnitGeometry] # parent: Optional[BaseEntity] , which may contain function names, class names, or code. Output only the next line.
org_units: List[OrgUnit] = []
Next line prediction: <|code_start|> defaultInventory = {"hosts": {}, "groups": {}} class CliContext(object): def __init__(self, inventory=None, debug=False): if inventory: self.inventory: Inventory = parse_file(os.path.abspath(inventory)) else: self.inventory: Inventory = parse_obj(defaultInventory) self.debug = debug @click.group() @click.version_option() @click.option("-i", "--inventory", metavar="INVENTORY") @click.option("-d", "--debug", is_flag=True) @click.pass_context def cli(ctx, inventory, debug): """ DHIS2 Tool for helping with import/export of various formats. """ ctx.obj = CliContext(inventory, debug) @cli.command("inspect") @click.argument("id") @click.pass_obj def cmd_inspect(ctx, id): """ Display basic dhis2 instance information """ hosts = resolve(id, ctx.inventory) <|code_end|> . Use current file imports: (import os import click import dhis2.code_list.cli as cli_code_list import dhis2.facility_list.cli as cli_facility_list import dhis2.generate.cli as cli_generator import dhis2.e2b.cli as cli_e2b from pkg_resources import iter_entry_points from .inspect import inspect from .inventory import Inventory, parse_file, parse_obj, resolve) and context including class names, function names, or small code snippets from other files: # Path: dhis2_core/src/dhis2/core/inspect.py # def inspect(hosts: List[HostResolved] = []): # for host in hosts: # if "dhis2" != host.type: # log.warning(f"Only 'dhis2' type is supported, ignoring host '{host.key}' with type '{host.type}'") # continue # # inspect_host(host) # # Path: dhis2_core/src/dhis2/core/inventory.py # class Inventory(BaseModel): # hosts: Dict[str, Host] # groups: Dict[str, List[str]] = Field(default_factory=dict) # # def get_many_by_id(self, ids) -> Dict[str, Host]: # if not isinstance(ids, (list, set, tuple)): # ids = [ids] # # hosts = {} # # for id in ids: # add from self.hosts first # if id in self.hosts: # hosts[id] = self.hosts[id] # # for id in ids: # if id in self.groups: # for gid in self.groups[id]: # if gid in self.hosts: # hosts[gid] = self.hosts.get(gid) # # return hosts # # def get_one_by_id(self, id) -> Host: # hosts = self.get_many_by_id(id) # # if not hosts: # log.info("Zero hosts found for id '{id}', expected one result") # sys.exit(-1) # # if len(hosts) > 1: # log.info("Many hosts found for id '{id}', expected one result") # sys.exit(-1) # # return hosts[0] # # def parse_file(filename: str) -> Inventory: # data: Dict[str, Any] = {} # # with open(filename) as f: # if filename.endswith(".yml"): # data = load(f, Loader=Loader) # elif filename.endswith(".json"): # data = json.load(f) # # return parse_obj(data) # # def parse_obj(data: Dict[str, Any]) -> Inventory: # _process_inventory_data(data) # # try: # data = Inventory.parse_obj(data) # except ValidationError as e: # log.error(e.json(indent=None)) # sys.exit(-1) # # return data # # def resolve(id: str, inventory: Inventory) -> List[HostResolved]: # id = normalize(id) # id_parsed = urlparse(id) # # hosts = inventory.get_many_by_id(id_parsed.hostname) # host_resolved = [] # # for host in hosts.items(): # key, value = host # auth = None # # if id_parsed.username in value.auth: # auth = value.auth[id_parsed.username] # # if not auth: # log.error(f"No auth block with id '{id_parsed.username}'' found for host '{key}''") # sys.exit(-1) # # hr = HostResolved( # type=value.type, # key=key, # baseUrl=value.baseUrl, # headers=value.headers, # params=value.params, # auth=auth, # ) # # host_resolved.append(hr) # # return host_resolved . Output only the next line.
inspect(hosts)
Based on the snippet: <|code_start|> defaultInventory = {"hosts": {}, "groups": {}} class CliContext(object): def __init__(self, inventory=None, debug=False): if inventory: <|code_end|> , predict the immediate next line with the help of imports: import os import click import dhis2.code_list.cli as cli_code_list import dhis2.facility_list.cli as cli_facility_list import dhis2.generate.cli as cli_generator import dhis2.e2b.cli as cli_e2b from pkg_resources import iter_entry_points from .inspect import inspect from .inventory import Inventory, parse_file, parse_obj, resolve and context (classes, functions, sometimes code) from other files: # Path: dhis2_core/src/dhis2/core/inspect.py # def inspect(hosts: List[HostResolved] = []): # for host in hosts: # if "dhis2" != host.type: # log.warning(f"Only 'dhis2' type is supported, ignoring host '{host.key}' with type '{host.type}'") # continue # # inspect_host(host) # # Path: dhis2_core/src/dhis2/core/inventory.py # class Inventory(BaseModel): # hosts: Dict[str, Host] # groups: Dict[str, List[str]] = Field(default_factory=dict) # # def get_many_by_id(self, ids) -> Dict[str, Host]: # if not isinstance(ids, (list, set, tuple)): # ids = [ids] # # hosts = {} # # for id in ids: # add from self.hosts first # if id in self.hosts: # hosts[id] = self.hosts[id] # # for id in ids: # if id in self.groups: # for gid in self.groups[id]: # if gid in self.hosts: # hosts[gid] = self.hosts.get(gid) # # return hosts # # def get_one_by_id(self, id) -> Host: # hosts = self.get_many_by_id(id) # # if not hosts: # log.info("Zero hosts found for id '{id}', expected one result") # sys.exit(-1) # # if len(hosts) > 1: # log.info("Many hosts found for id '{id}', expected one result") # sys.exit(-1) # # return hosts[0] # # def parse_file(filename: str) -> Inventory: # data: Dict[str, Any] = {} # # with open(filename) as f: # if filename.endswith(".yml"): # data = load(f, Loader=Loader) # elif filename.endswith(".json"): # data = json.load(f) # # return parse_obj(data) # # def parse_obj(data: Dict[str, Any]) -> Inventory: # _process_inventory_data(data) # # try: # data = Inventory.parse_obj(data) # except ValidationError as e: # log.error(e.json(indent=None)) # sys.exit(-1) # # return data # # def resolve(id: str, inventory: Inventory) -> List[HostResolved]: # id = normalize(id) # id_parsed = urlparse(id) # # hosts = inventory.get_many_by_id(id_parsed.hostname) # host_resolved = [] # # for host in hosts.items(): # key, value = host # auth = None # # if id_parsed.username in value.auth: # auth = value.auth[id_parsed.username] # # if not auth: # log.error(f"No auth block with id '{id_parsed.username}'' found for host '{key}''") # sys.exit(-1) # # hr = HostResolved( # type=value.type, # key=key, # baseUrl=value.baseUrl, # headers=value.headers, # params=value.params, # auth=auth, # ) # # host_resolved.append(hr) # # return host_resolved . Output only the next line.
self.inventory: Inventory = parse_file(os.path.abspath(inventory))
Predict the next line for this snippet: <|code_start|> defaultInventory = {"hosts": {}, "groups": {}} class CliContext(object): def __init__(self, inventory=None, debug=False): if inventory: <|code_end|> with the help of current file imports: import os import click import dhis2.code_list.cli as cli_code_list import dhis2.facility_list.cli as cli_facility_list import dhis2.generate.cli as cli_generator import dhis2.e2b.cli as cli_e2b from pkg_resources import iter_entry_points from .inspect import inspect from .inventory import Inventory, parse_file, parse_obj, resolve and context from other files: # Path: dhis2_core/src/dhis2/core/inspect.py # def inspect(hosts: List[HostResolved] = []): # for host in hosts: # if "dhis2" != host.type: # log.warning(f"Only 'dhis2' type is supported, ignoring host '{host.key}' with type '{host.type}'") # continue # # inspect_host(host) # # Path: dhis2_core/src/dhis2/core/inventory.py # class Inventory(BaseModel): # hosts: Dict[str, Host] # groups: Dict[str, List[str]] = Field(default_factory=dict) # # def get_many_by_id(self, ids) -> Dict[str, Host]: # if not isinstance(ids, (list, set, tuple)): # ids = [ids] # # hosts = {} # # for id in ids: # add from self.hosts first # if id in self.hosts: # hosts[id] = self.hosts[id] # # for id in ids: # if id in self.groups: # for gid in self.groups[id]: # if gid in self.hosts: # hosts[gid] = self.hosts.get(gid) # # return hosts # # def get_one_by_id(self, id) -> Host: # hosts = self.get_many_by_id(id) # # if not hosts: # log.info("Zero hosts found for id '{id}', expected one result") # sys.exit(-1) # # if len(hosts) > 1: # log.info("Many hosts found for id '{id}', expected one result") # sys.exit(-1) # # return hosts[0] # # def parse_file(filename: str) -> Inventory: # data: Dict[str, Any] = {} # # with open(filename) as f: # if filename.endswith(".yml"): # data = load(f, Loader=Loader) # elif filename.endswith(".json"): # data = json.load(f) # # return parse_obj(data) # # def parse_obj(data: Dict[str, Any]) -> Inventory: # _process_inventory_data(data) # # try: # data = Inventory.parse_obj(data) # except ValidationError as e: # log.error(e.json(indent=None)) # sys.exit(-1) # # return data # # def resolve(id: str, inventory: Inventory) -> List[HostResolved]: # id = normalize(id) # id_parsed = urlparse(id) # # hosts = inventory.get_many_by_id(id_parsed.hostname) # host_resolved = [] # # for host in hosts.items(): # key, value = host # auth = None # # if id_parsed.username in value.auth: # auth = value.auth[id_parsed.username] # # if not auth: # log.error(f"No auth block with id '{id_parsed.username}'' found for host '{key}''") # sys.exit(-1) # # hr = HostResolved( # type=value.type, # key=key, # baseUrl=value.baseUrl, # headers=value.headers, # params=value.params, # auth=auth, # ) # # host_resolved.append(hr) # # return host_resolved , which may contain function names, class names, or code. Output only the next line.
self.inventory: Inventory = parse_file(os.path.abspath(inventory))
Predict the next line for this snippet: <|code_start|> defaultInventory = {"hosts": {}, "groups": {}} class CliContext(object): def __init__(self, inventory=None, debug=False): if inventory: self.inventory: Inventory = parse_file(os.path.abspath(inventory)) else: <|code_end|> with the help of current file imports: import os import click import dhis2.code_list.cli as cli_code_list import dhis2.facility_list.cli as cli_facility_list import dhis2.generate.cli as cli_generator import dhis2.e2b.cli as cli_e2b from pkg_resources import iter_entry_points from .inspect import inspect from .inventory import Inventory, parse_file, parse_obj, resolve and context from other files: # Path: dhis2_core/src/dhis2/core/inspect.py # def inspect(hosts: List[HostResolved] = []): # for host in hosts: # if "dhis2" != host.type: # log.warning(f"Only 'dhis2' type is supported, ignoring host '{host.key}' with type '{host.type}'") # continue # # inspect_host(host) # # Path: dhis2_core/src/dhis2/core/inventory.py # class Inventory(BaseModel): # hosts: Dict[str, Host] # groups: Dict[str, List[str]] = Field(default_factory=dict) # # def get_many_by_id(self, ids) -> Dict[str, Host]: # if not isinstance(ids, (list, set, tuple)): # ids = [ids] # # hosts = {} # # for id in ids: # add from self.hosts first # if id in self.hosts: # hosts[id] = self.hosts[id] # # for id in ids: # if id in self.groups: # for gid in self.groups[id]: # if gid in self.hosts: # hosts[gid] = self.hosts.get(gid) # # return hosts # # def get_one_by_id(self, id) -> Host: # hosts = self.get_many_by_id(id) # # if not hosts: # log.info("Zero hosts found for id '{id}', expected one result") # sys.exit(-1) # # if len(hosts) > 1: # log.info("Many hosts found for id '{id}', expected one result") # sys.exit(-1) # # return hosts[0] # # def parse_file(filename: str) -> Inventory: # data: Dict[str, Any] = {} # # with open(filename) as f: # if filename.endswith(".yml"): # data = load(f, Loader=Loader) # elif filename.endswith(".json"): # data = json.load(f) # # return parse_obj(data) # # def parse_obj(data: Dict[str, Any]) -> Inventory: # _process_inventory_data(data) # # try: # data = Inventory.parse_obj(data) # except ValidationError as e: # log.error(e.json(indent=None)) # sys.exit(-1) # # return data # # def resolve(id: str, inventory: Inventory) -> List[HostResolved]: # id = normalize(id) # id_parsed = urlparse(id) # # hosts = inventory.get_many_by_id(id_parsed.hostname) # host_resolved = [] # # for host in hosts.items(): # key, value = host # auth = None # # if id_parsed.username in value.auth: # auth = value.auth[id_parsed.username] # # if not auth: # log.error(f"No auth block with id '{id_parsed.username}'' found for host '{key}''") # sys.exit(-1) # # hr = HostResolved( # type=value.type, # key=key, # baseUrl=value.baseUrl, # headers=value.headers, # params=value.params, # auth=auth, # ) # # host_resolved.append(hr) # # return host_resolved , which may contain function names, class names, or code. Output only the next line.
self.inventory: Inventory = parse_obj(defaultInventory)
Here is a snippet: <|code_start|> defaultInventory = {"hosts": {}, "groups": {}} class CliContext(object): def __init__(self, inventory=None, debug=False): if inventory: self.inventory: Inventory = parse_file(os.path.abspath(inventory)) else: self.inventory: Inventory = parse_obj(defaultInventory) self.debug = debug @click.group() @click.version_option() @click.option("-i", "--inventory", metavar="INVENTORY") @click.option("-d", "--debug", is_flag=True) @click.pass_context def cli(ctx, inventory, debug): """ DHIS2 Tool for helping with import/export of various formats. """ ctx.obj = CliContext(inventory, debug) @cli.command("inspect") @click.argument("id") @click.pass_obj def cmd_inspect(ctx, id): """ Display basic dhis2 instance information """ <|code_end|> . Write the next line using the current file imports: import os import click import dhis2.code_list.cli as cli_code_list import dhis2.facility_list.cli as cli_facility_list import dhis2.generate.cli as cli_generator import dhis2.e2b.cli as cli_e2b from pkg_resources import iter_entry_points from .inspect import inspect from .inventory import Inventory, parse_file, parse_obj, resolve and context from other files: # Path: dhis2_core/src/dhis2/core/inspect.py # def inspect(hosts: List[HostResolved] = []): # for host in hosts: # if "dhis2" != host.type: # log.warning(f"Only 'dhis2' type is supported, ignoring host '{host.key}' with type '{host.type}'") # continue # # inspect_host(host) # # Path: dhis2_core/src/dhis2/core/inventory.py # class Inventory(BaseModel): # hosts: Dict[str, Host] # groups: Dict[str, List[str]] = Field(default_factory=dict) # # def get_many_by_id(self, ids) -> Dict[str, Host]: # if not isinstance(ids, (list, set, tuple)): # ids = [ids] # # hosts = {} # # for id in ids: # add from self.hosts first # if id in self.hosts: # hosts[id] = self.hosts[id] # # for id in ids: # if id in self.groups: # for gid in self.groups[id]: # if gid in self.hosts: # hosts[gid] = self.hosts.get(gid) # # return hosts # # def get_one_by_id(self, id) -> Host: # hosts = self.get_many_by_id(id) # # if not hosts: # log.info("Zero hosts found for id '{id}', expected one result") # sys.exit(-1) # # if len(hosts) > 1: # log.info("Many hosts found for id '{id}', expected one result") # sys.exit(-1) # # return hosts[0] # # def parse_file(filename: str) -> Inventory: # data: Dict[str, Any] = {} # # with open(filename) as f: # if filename.endswith(".yml"): # data = load(f, Loader=Loader) # elif filename.endswith(".json"): # data = json.load(f) # # return parse_obj(data) # # def parse_obj(data: Dict[str, Any]) -> Inventory: # _process_inventory_data(data) # # try: # data = Inventory.parse_obj(data) # except ValidationError as e: # log.error(e.json(indent=None)) # sys.exit(-1) # # return data # # def resolve(id: str, inventory: Inventory) -> List[HostResolved]: # id = normalize(id) # id_parsed = urlparse(id) # # hosts = inventory.get_many_by_id(id_parsed.hostname) # host_resolved = [] # # for host in hosts.items(): # key, value = host # auth = None # # if id_parsed.username in value.auth: # auth = value.auth[id_parsed.username] # # if not auth: # log.error(f"No auth block with id '{id_parsed.username}'' found for host '{key}''") # sys.exit(-1) # # hr = HostResolved( # type=value.type, # key=key, # baseUrl=value.baseUrl, # headers=value.headers, # params=value.params, # auth=auth, # ) # # host_resolved.append(hr) # # return host_resolved , which may include functions, classes, or code. Output only the next line.
hosts = resolve(id, ctx.inventory)
Continue the code snippet: <|code_start|> log = logging.getLogger(__name__) @click.group("generate") def cli_generator(): """ Various commands for generating data/schemas """ pass @cli_generator.command("json_schemas") @click.argument("host-id") @click.pass_obj def cmd_json_schemas(ctx, host_id: str): """ Generate JSON Schemas from a dhis2 instance """ host = resolve_one(host_id, ctx.inventory) schemas = load_and_parse_schema(host) if schemas: <|code_end|> . Use current file imports: import json import logging import click from dhis2.core.inventory import resolve_one from dhis2.core.utils import load_and_parse_schema from .json_schema import generate_json_schema_metadata and context (classes, functions, or code) from other files: # Path: dhis2_core/src/dhis2/generate/json_schema.py # def generate_json_schema_metadata(dhis2_schemas: List[Schema]): # schema = { # "$id": "https://dhis2.org/schemas/metadata", # "$schema": "http://json-schema.org/draft-07/schema#", # "type": "object", # "definitions": { # "identifiableObject": { # "oneOf": [ # {"type": "object", "properties": {"id": {"type": "string"}}}, # {"type": "object", "properties": {"code": {"type": "string"}}}, # ] # } # }, # "properties": {}, # "required": [], # } # # for dhis2_schema in dhis2_schemas: # if not dhis2_schema.metadata: # continue # # property = {"type": "array", "items": {"$ref": f"#/definitions/{dhis2_schema.name}"}} # schema.get("properties")[dhis2_schema.plural] = property # # for dhis2_schema in dhis2_schemas: # if not dhis2_schema.metadata and not dhis2_schema.embeddedObject: # continue # # property = handle_object(dhis2_schema) # schema.get("definitions")[dhis2_schema.singular] = property # # return schema . Output only the next line.
click.echo(json.dumps(generate_json_schema_metadata(schemas), indent=2))
Here is a snippet: <|code_start|> dose: str, expiry: str, diluent_name: str, diluent_batch: str, diluent_expiry: str, diluent_dor: str, diluent_tor: str, ): drug = etree.SubElement(root, "drug") drug.append(E.drugcharacterization("1")) drug.append(E.medicinalproduct(f"{name} {brand}")) drug.append(E.drugbatchnumb(batch)) drugdosagetext = "" if dose: drugdosagetext += f"Dose number {dose}" if expiry: if drugdosagetext: drugdosagetext += f", Expiry date: {expiry}" else: drugdosagetext += f"Expiry date: {expiry}" if drugdosagetext: drug.append(E.drugdosagetext(drugdosagetext)) if date: dt = datetime.fromisoformat(f"{date}T{time}") drug.append(E.drugstartdateformat("102")) <|code_end|> . Write the next line using the current file imports: import logging from datetime import datetime from uuid import uuid4 from lxml import etree from lxml.builder import E from .common import ( date_format_102, date_format_203, date_format_204, get_attribute_value, get_data_value, get_patient_sex, get_reaction_outcome, get_yes_no, ) from .models.e2b import Enrollment, TrackedEntity and context from other files: # Path: dhis2_core/src/dhis2/e2b/common.py # def date_format_102(dt: datetime) -> str: # return dt.strftime("%Y%m%d") # # def date_format_203(dt: datetime) -> str: # return dt.strftime("%Y%m%d%H%M") # # def date_format_204(dt: datetime) -> str: # return dt.strftime("%Y%m%d%H%M%S") # # def get_attribute_value(at: str, te: TrackedEntity, defaultValue=None) -> Union[str, None]: # av = te.attributes.get(at, defaultValue) # # if not av: # return defaultValue # # if av.value: # return av.value # # return defaultValue # # def get_data_value(de: str, te: TrackedEntity, idx: int = 0, defaultValue=None) -> Union[str, None]: # en: Enrollment = te.enrollments[idx] # ev: Event = en.events["so8YZ9J3MeO"] # AEFI stage # # if de not in ev.dataValues: # return defaultValue # # dv: EventDataValue = ev.dataValues[de] # # if dv: # return dv.value # # return defaultValue # # def get_patient_sex(te: TrackedEntity) -> str: # value = get_attribute_value("CklPZdOd6H1", te) # # if not value: # value = get_attribute_value("oindugucx72", te) # # if "MALE" == value: # return "1" # elif "FEMALE" == value: # return "2" # # return "" # # def get_reaction_outcome(te: TrackedEntity): # value = get_data_value("yRrSDiR5v1M", te) # # if "Recovered/resolved" == value: # return "1" # elif "Recovering/resolving" == value: # return "2" # elif "Not recovered/not resolved" == value: # return "3" # elif "Recovered/resolved with sequelae" == value: # return "4" # elif "Died" == value or "Autopsy done" == value: # return "5" # elif "Unknown" == value: # return "6" # # return value # # def get_yes_no(de: str, te: TrackedEntity, idx: int = 0): # dv: EventDataValue = get_data_value(de, te, idx) # # if "true" == dv: # return "1" # # return "2" # # Path: dhis2_core/src/dhis2/e2b/models/e2b.py # class Enrollment(BaseModel): # created: datetime # lastUpdated: datetime # enrollment: str # trackedEntityInstance: str # orgUnit: str # storedBy: Optional[str] # status: str # completedDate: Optional[str] # events: List[Event] = [] # attributes: Union[Dict[str, AttributeValue], List[AttributeValue]] = [] # # class TrackedEntity(BaseModel): # created: datetime # lastUpdated: datetime # trackedEntityInstance: str # trackedEntityType: str # orgUnit: str # storedBy: Optional[str] # enrollments: List[Enrollment] = [] # attributes: Union[Dict[str, AttributeValue], List[AttributeValue]] = [] , which may include functions, classes, or code. Output only the next line.
drug.append(E.drugstartdate(date_format_102(dt)))
Based on the snippet: <|code_start|> if vaccine4_name: build_safetyreport_patient_drug( root, name=vaccine4_name, brand=vaccine4_brand, date=vaccine4_date, time=vaccine4_time, batch=vaccine4_batch or "", dose=vaccine4_dose, expiry=vaccine4_expiry, diluent_name=diluent4_name, diluent_batch=diluent4_batch, diluent_expiry=diluent4_expiry, diluent_dor=diluent4_dor, diluent_tor=diluent4_tor, ) def build_safetyreport_patient_reaction(root: etree.Element, te: TrackedEntity, reaction: str): p = etree.SubElement(root, "reaction") outcome = get_reaction_outcome(te) startdate = get_data_value("vNGUuAZA2C2", te) startTime = get_data_value("NyCB1VAOfJd", te, defaultValue="00:00") p.append(E.primarysourcereaction(reaction)) if startdate: datetime_startdate = datetime.fromisoformat(f"{startdate}T{startTime}") p.append(E.reactionstartdateformat("203")) <|code_end|> , predict the immediate next line with the help of imports: import logging from datetime import datetime from uuid import uuid4 from lxml import etree from lxml.builder import E from .common import ( date_format_102, date_format_203, date_format_204, get_attribute_value, get_data_value, get_patient_sex, get_reaction_outcome, get_yes_no, ) from .models.e2b import Enrollment, TrackedEntity and context (classes, functions, sometimes code) from other files: # Path: dhis2_core/src/dhis2/e2b/common.py # def date_format_102(dt: datetime) -> str: # return dt.strftime("%Y%m%d") # # def date_format_203(dt: datetime) -> str: # return dt.strftime("%Y%m%d%H%M") # # def date_format_204(dt: datetime) -> str: # return dt.strftime("%Y%m%d%H%M%S") # # def get_attribute_value(at: str, te: TrackedEntity, defaultValue=None) -> Union[str, None]: # av = te.attributes.get(at, defaultValue) # # if not av: # return defaultValue # # if av.value: # return av.value # # return defaultValue # # def get_data_value(de: str, te: TrackedEntity, idx: int = 0, defaultValue=None) -> Union[str, None]: # en: Enrollment = te.enrollments[idx] # ev: Event = en.events["so8YZ9J3MeO"] # AEFI stage # # if de not in ev.dataValues: # return defaultValue # # dv: EventDataValue = ev.dataValues[de] # # if dv: # return dv.value # # return defaultValue # # def get_patient_sex(te: TrackedEntity) -> str: # value = get_attribute_value("CklPZdOd6H1", te) # # if not value: # value = get_attribute_value("oindugucx72", te) # # if "MALE" == value: # return "1" # elif "FEMALE" == value: # return "2" # # return "" # # def get_reaction_outcome(te: TrackedEntity): # value = get_data_value("yRrSDiR5v1M", te) # # if "Recovered/resolved" == value: # return "1" # elif "Recovering/resolving" == value: # return "2" # elif "Not recovered/not resolved" == value: # return "3" # elif "Recovered/resolved with sequelae" == value: # return "4" # elif "Died" == value or "Autopsy done" == value: # return "5" # elif "Unknown" == value: # return "6" # # return value # # def get_yes_no(de: str, te: TrackedEntity, idx: int = 0): # dv: EventDataValue = get_data_value(de, te, idx) # # if "true" == dv: # return "1" # # return "2" # # Path: dhis2_core/src/dhis2/e2b/models/e2b.py # class Enrollment(BaseModel): # created: datetime # lastUpdated: datetime # enrollment: str # trackedEntityInstance: str # orgUnit: str # storedBy: Optional[str] # status: str # completedDate: Optional[str] # events: List[Event] = [] # attributes: Union[Dict[str, AttributeValue], List[AttributeValue]] = [] # # class TrackedEntity(BaseModel): # created: datetime # lastUpdated: datetime # trackedEntityInstance: str # trackedEntityType: str # orgUnit: str # storedBy: Optional[str] # enrollments: List[Enrollment] = [] # attributes: Union[Dict[str, AttributeValue], List[AttributeValue]] = [] . Output only the next line.
p.append(E.reactionstartdate(date_format_203(datetime_startdate)))
Predict the next line for this snippet: <|code_start|> log = logging.getLogger(__name__) def build_messageheader(root: etree.Element, sender_id: str, receiver_id: str): mh = E.ichicsrmessageheader( E.messagetype("ichicsr"), E.messageformatversion("2.1"), E.messageformatrelease("2.0"), E.messagenumb(str(uuid4())), E.messagesenderidentifier(sender_id), E.messagereceiveridentifier(receiver_id), E.messagedateformat("204"), <|code_end|> with the help of current file imports: import logging from datetime import datetime from uuid import uuid4 from lxml import etree from lxml.builder import E from .common import ( date_format_102, date_format_203, date_format_204, get_attribute_value, get_data_value, get_patient_sex, get_reaction_outcome, get_yes_no, ) from .models.e2b import Enrollment, TrackedEntity and context from other files: # Path: dhis2_core/src/dhis2/e2b/common.py # def date_format_102(dt: datetime) -> str: # return dt.strftime("%Y%m%d") # # def date_format_203(dt: datetime) -> str: # return dt.strftime("%Y%m%d%H%M") # # def date_format_204(dt: datetime) -> str: # return dt.strftime("%Y%m%d%H%M%S") # # def get_attribute_value(at: str, te: TrackedEntity, defaultValue=None) -> Union[str, None]: # av = te.attributes.get(at, defaultValue) # # if not av: # return defaultValue # # if av.value: # return av.value # # return defaultValue # # def get_data_value(de: str, te: TrackedEntity, idx: int = 0, defaultValue=None) -> Union[str, None]: # en: Enrollment = te.enrollments[idx] # ev: Event = en.events["so8YZ9J3MeO"] # AEFI stage # # if de not in ev.dataValues: # return defaultValue # # dv: EventDataValue = ev.dataValues[de] # # if dv: # return dv.value # # return defaultValue # # def get_patient_sex(te: TrackedEntity) -> str: # value = get_attribute_value("CklPZdOd6H1", te) # # if not value: # value = get_attribute_value("oindugucx72", te) # # if "MALE" == value: # return "1" # elif "FEMALE" == value: # return "2" # # return "" # # def get_reaction_outcome(te: TrackedEntity): # value = get_data_value("yRrSDiR5v1M", te) # # if "Recovered/resolved" == value: # return "1" # elif "Recovering/resolving" == value: # return "2" # elif "Not recovered/not resolved" == value: # return "3" # elif "Recovered/resolved with sequelae" == value: # return "4" # elif "Died" == value or "Autopsy done" == value: # return "5" # elif "Unknown" == value: # return "6" # # return value # # def get_yes_no(de: str, te: TrackedEntity, idx: int = 0): # dv: EventDataValue = get_data_value(de, te, idx) # # if "true" == dv: # return "1" # # return "2" # # Path: dhis2_core/src/dhis2/e2b/models/e2b.py # class Enrollment(BaseModel): # created: datetime # lastUpdated: datetime # enrollment: str # trackedEntityInstance: str # orgUnit: str # storedBy: Optional[str] # status: str # completedDate: Optional[str] # events: List[Event] = [] # attributes: Union[Dict[str, AttributeValue], List[AttributeValue]] = [] # # class TrackedEntity(BaseModel): # created: datetime # lastUpdated: datetime # trackedEntityInstance: str # trackedEntityType: str # orgUnit: str # storedBy: Optional[str] # enrollments: List[Enrollment] = [] # attributes: Union[Dict[str, AttributeValue], List[AttributeValue]] = [] , which may contain function names, class names, or code. Output only the next line.
E.messagedate(date_format_204(datetime.now())),
Continue the code snippet: <|code_start|> if get_data_value("OhHYABXmGGe", te): build_safetyreport_patient_reaction(root, te, "Fainting") if get_data_value("nKLO8ZNdR0B", te): build_safetyreport_patient_reaction(root, te, "Mild fever") if get_data_value("JaZ9yf1dDy3", te): build_safetyreport_patient_reaction(root, te, "Tiredness") if get_data_value("wWDenTQ5xBR", te): build_safetyreport_patient_reaction(root, te, "Nasal congestion") if get_data_value("GEkI9NzxTmM", te): build_safetyreport_patient_reaction(root, te, "Lymph node enlargement") if get_data_value("XluNAFG1wj6", te): build_safetyreport_patient_reaction(root, te, "Dizziness") if get_data_value("rjjRNU5yDhT", te): build_safetyreport_patient_reaction(root, te, "Drowsiness") other = get_data_value("iTm5wvq16iq", te) if other: build_safetyreport_patient_reaction(root, te, other) def build_safetyreport_patient(root: etree.Element, te: TrackedEntity): p = etree.SubElement(root, "patient") <|code_end|> . Use current file imports: import logging from datetime import datetime from uuid import uuid4 from lxml import etree from lxml.builder import E from .common import ( date_format_102, date_format_203, date_format_204, get_attribute_value, get_data_value, get_patient_sex, get_reaction_outcome, get_yes_no, ) from .models.e2b import Enrollment, TrackedEntity and context (classes, functions, or code) from other files: # Path: dhis2_core/src/dhis2/e2b/common.py # def date_format_102(dt: datetime) -> str: # return dt.strftime("%Y%m%d") # # def date_format_203(dt: datetime) -> str: # return dt.strftime("%Y%m%d%H%M") # # def date_format_204(dt: datetime) -> str: # return dt.strftime("%Y%m%d%H%M%S") # # def get_attribute_value(at: str, te: TrackedEntity, defaultValue=None) -> Union[str, None]: # av = te.attributes.get(at, defaultValue) # # if not av: # return defaultValue # # if av.value: # return av.value # # return defaultValue # # def get_data_value(de: str, te: TrackedEntity, idx: int = 0, defaultValue=None) -> Union[str, None]: # en: Enrollment = te.enrollments[idx] # ev: Event = en.events["so8YZ9J3MeO"] # AEFI stage # # if de not in ev.dataValues: # return defaultValue # # dv: EventDataValue = ev.dataValues[de] # # if dv: # return dv.value # # return defaultValue # # def get_patient_sex(te: TrackedEntity) -> str: # value = get_attribute_value("CklPZdOd6H1", te) # # if not value: # value = get_attribute_value("oindugucx72", te) # # if "MALE" == value: # return "1" # elif "FEMALE" == value: # return "2" # # return "" # # def get_reaction_outcome(te: TrackedEntity): # value = get_data_value("yRrSDiR5v1M", te) # # if "Recovered/resolved" == value: # return "1" # elif "Recovering/resolving" == value: # return "2" # elif "Not recovered/not resolved" == value: # return "3" # elif "Recovered/resolved with sequelae" == value: # return "4" # elif "Died" == value or "Autopsy done" == value: # return "5" # elif "Unknown" == value: # return "6" # # return value # # def get_yes_no(de: str, te: TrackedEntity, idx: int = 0): # dv: EventDataValue = get_data_value(de, te, idx) # # if "true" == dv: # return "1" # # return "2" # # Path: dhis2_core/src/dhis2/e2b/models/e2b.py # class Enrollment(BaseModel): # created: datetime # lastUpdated: datetime # enrollment: str # trackedEntityInstance: str # orgUnit: str # storedBy: Optional[str] # status: str # completedDate: Optional[str] # events: List[Event] = [] # attributes: Union[Dict[str, AttributeValue], List[AttributeValue]] = [] # # class TrackedEntity(BaseModel): # created: datetime # lastUpdated: datetime # trackedEntityInstance: str # trackedEntityType: str # orgUnit: str # storedBy: Optional[str] # enrollments: List[Enrollment] = [] # attributes: Union[Dict[str, AttributeValue], List[AttributeValue]] = [] . Output only the next line.
given_name = get_attribute_value("TfdH5KvFmMy", te)
Continue the code snippet: <|code_start|> dilutent = [] drug.append(etree.Comment("Diluent short name description:")) drug.append(etree.Comment("N = Name of diluent")) drug.append(etree.Comment("B = Dilutent batch/lot number")) drug.append(etree.Comment("EX = Dilutent expiry date")) drug.append(etree.Comment("DR = Dilutent date of reconstitution")) drug.append(etree.Comment("TR = Dilutent time of reconstitution")) if diluent_name: dilutent.append(f"N: {diluent_name}") if diluent_batch: dilutent.append(f"B: {diluent_batch}") if diluent_expiry: dilutent.append(f"EX: {diluent_expiry}") if diluent_dor: dilutent.append(f"DR: {diluent_dor}") if diluent_tor: dilutent.append(f"TR: {diluent_tor}") if dilutent: drug.append(E.drugadditional(", ".join(dilutent))) def build_safetyreport_patient_drugs(root: etree.Element, te: TrackedEntity): <|code_end|> . Use current file imports: import logging from datetime import datetime from uuid import uuid4 from lxml import etree from lxml.builder import E from .common import ( date_format_102, date_format_203, date_format_204, get_attribute_value, get_data_value, get_patient_sex, get_reaction_outcome, get_yes_no, ) from .models.e2b import Enrollment, TrackedEntity and context (classes, functions, or code) from other files: # Path: dhis2_core/src/dhis2/e2b/common.py # def date_format_102(dt: datetime) -> str: # return dt.strftime("%Y%m%d") # # def date_format_203(dt: datetime) -> str: # return dt.strftime("%Y%m%d%H%M") # # def date_format_204(dt: datetime) -> str: # return dt.strftime("%Y%m%d%H%M%S") # # def get_attribute_value(at: str, te: TrackedEntity, defaultValue=None) -> Union[str, None]: # av = te.attributes.get(at, defaultValue) # # if not av: # return defaultValue # # if av.value: # return av.value # # return defaultValue # # def get_data_value(de: str, te: TrackedEntity, idx: int = 0, defaultValue=None) -> Union[str, None]: # en: Enrollment = te.enrollments[idx] # ev: Event = en.events["so8YZ9J3MeO"] # AEFI stage # # if de not in ev.dataValues: # return defaultValue # # dv: EventDataValue = ev.dataValues[de] # # if dv: # return dv.value # # return defaultValue # # def get_patient_sex(te: TrackedEntity) -> str: # value = get_attribute_value("CklPZdOd6H1", te) # # if not value: # value = get_attribute_value("oindugucx72", te) # # if "MALE" == value: # return "1" # elif "FEMALE" == value: # return "2" # # return "" # # def get_reaction_outcome(te: TrackedEntity): # value = get_data_value("yRrSDiR5v1M", te) # # if "Recovered/resolved" == value: # return "1" # elif "Recovering/resolving" == value: # return "2" # elif "Not recovered/not resolved" == value: # return "3" # elif "Recovered/resolved with sequelae" == value: # return "4" # elif "Died" == value or "Autopsy done" == value: # return "5" # elif "Unknown" == value: # return "6" # # return value # # def get_yes_no(de: str, te: TrackedEntity, idx: int = 0): # dv: EventDataValue = get_data_value(de, te, idx) # # if "true" == dv: # return "1" # # return "2" # # Path: dhis2_core/src/dhis2/e2b/models/e2b.py # class Enrollment(BaseModel): # created: datetime # lastUpdated: datetime # enrollment: str # trackedEntityInstance: str # orgUnit: str # storedBy: Optional[str] # status: str # completedDate: Optional[str] # events: List[Event] = [] # attributes: Union[Dict[str, AttributeValue], List[AttributeValue]] = [] # # class TrackedEntity(BaseModel): # created: datetime # lastUpdated: datetime # trackedEntityInstance: str # trackedEntityType: str # orgUnit: str # storedBy: Optional[str] # enrollments: List[Enrollment] = [] # attributes: Union[Dict[str, AttributeValue], List[AttributeValue]] = [] . Output only the next line.
vaccine1_name = get_data_value("uSVcZzSM3zg", te)
Given snippet: <|code_start|> if other: build_safetyreport_patient_reaction(root, te, other) def build_safetyreport_patient(root: etree.Element, te: TrackedEntity): p = etree.SubElement(root, "patient") given_name = get_attribute_value("TfdH5KvFmMy", te) family_name = get_attribute_value("aW66s2QSosT", te) if given_name: name = given_name if family_name: name = f"{name} {family_name}" p.append(E.patientinitial(name)) # should we use name here or not? dt = get_attribute_value("BiTsLcJQ95V", te) if not dt: dt = get_attribute_value("NI0QRzJvQ0k", te) # MU if dt: dt = datetime.fromisoformat(dt) dob = dt.strftime("%Y%m%d") p.append(E.patientbirthdateformat("102")) p.append(E.patientbirthdate(dob)) <|code_end|> , continue by predicting the next line. Consider current file imports: import logging from datetime import datetime from uuid import uuid4 from lxml import etree from lxml.builder import E from .common import ( date_format_102, date_format_203, date_format_204, get_attribute_value, get_data_value, get_patient_sex, get_reaction_outcome, get_yes_no, ) from .models.e2b import Enrollment, TrackedEntity and context: # Path: dhis2_core/src/dhis2/e2b/common.py # def date_format_102(dt: datetime) -> str: # return dt.strftime("%Y%m%d") # # def date_format_203(dt: datetime) -> str: # return dt.strftime("%Y%m%d%H%M") # # def date_format_204(dt: datetime) -> str: # return dt.strftime("%Y%m%d%H%M%S") # # def get_attribute_value(at: str, te: TrackedEntity, defaultValue=None) -> Union[str, None]: # av = te.attributes.get(at, defaultValue) # # if not av: # return defaultValue # # if av.value: # return av.value # # return defaultValue # # def get_data_value(de: str, te: TrackedEntity, idx: int = 0, defaultValue=None) -> Union[str, None]: # en: Enrollment = te.enrollments[idx] # ev: Event = en.events["so8YZ9J3MeO"] # AEFI stage # # if de not in ev.dataValues: # return defaultValue # # dv: EventDataValue = ev.dataValues[de] # # if dv: # return dv.value # # return defaultValue # # def get_patient_sex(te: TrackedEntity) -> str: # value = get_attribute_value("CklPZdOd6H1", te) # # if not value: # value = get_attribute_value("oindugucx72", te) # # if "MALE" == value: # return "1" # elif "FEMALE" == value: # return "2" # # return "" # # def get_reaction_outcome(te: TrackedEntity): # value = get_data_value("yRrSDiR5v1M", te) # # if "Recovered/resolved" == value: # return "1" # elif "Recovering/resolving" == value: # return "2" # elif "Not recovered/not resolved" == value: # return "3" # elif "Recovered/resolved with sequelae" == value: # return "4" # elif "Died" == value or "Autopsy done" == value: # return "5" # elif "Unknown" == value: # return "6" # # return value # # def get_yes_no(de: str, te: TrackedEntity, idx: int = 0): # dv: EventDataValue = get_data_value(de, te, idx) # # if "true" == dv: # return "1" # # return "2" # # Path: dhis2_core/src/dhis2/e2b/models/e2b.py # class Enrollment(BaseModel): # created: datetime # lastUpdated: datetime # enrollment: str # trackedEntityInstance: str # orgUnit: str # storedBy: Optional[str] # status: str # completedDate: Optional[str] # events: List[Event] = [] # attributes: Union[Dict[str, AttributeValue], List[AttributeValue]] = [] # # class TrackedEntity(BaseModel): # created: datetime # lastUpdated: datetime # trackedEntityInstance: str # trackedEntityType: str # orgUnit: str # storedBy: Optional[str] # enrollments: List[Enrollment] = [] # attributes: Union[Dict[str, AttributeValue], List[AttributeValue]] = [] which might include code, classes, or functions. Output only the next line.
p.append(E.patientsex(get_patient_sex(te)))
Predict the next line after this snippet: <|code_start|> batch=vaccine3_batch or "", dose=vaccine3_dose, expiry=vaccine3_expiry, diluent_name=diluent3_name, diluent_batch=diluent3_batch, diluent_expiry=diluent3_expiry, diluent_dor=diluent3_dor, diluent_tor=diluent3_tor, ) if vaccine4_name: build_safetyreport_patient_drug( root, name=vaccine4_name, brand=vaccine4_brand, date=vaccine4_date, time=vaccine4_time, batch=vaccine4_batch or "", dose=vaccine4_dose, expiry=vaccine4_expiry, diluent_name=diluent4_name, diluent_batch=diluent4_batch, diluent_expiry=diluent4_expiry, diluent_dor=diluent4_dor, diluent_tor=diluent4_tor, ) def build_safetyreport_patient_reaction(root: etree.Element, te: TrackedEntity, reaction: str): p = etree.SubElement(root, "reaction") <|code_end|> using the current file's imports: import logging from datetime import datetime from uuid import uuid4 from lxml import etree from lxml.builder import E from .common import ( date_format_102, date_format_203, date_format_204, get_attribute_value, get_data_value, get_patient_sex, get_reaction_outcome, get_yes_no, ) from .models.e2b import Enrollment, TrackedEntity and any relevant context from other files: # Path: dhis2_core/src/dhis2/e2b/common.py # def date_format_102(dt: datetime) -> str: # return dt.strftime("%Y%m%d") # # def date_format_203(dt: datetime) -> str: # return dt.strftime("%Y%m%d%H%M") # # def date_format_204(dt: datetime) -> str: # return dt.strftime("%Y%m%d%H%M%S") # # def get_attribute_value(at: str, te: TrackedEntity, defaultValue=None) -> Union[str, None]: # av = te.attributes.get(at, defaultValue) # # if not av: # return defaultValue # # if av.value: # return av.value # # return defaultValue # # def get_data_value(de: str, te: TrackedEntity, idx: int = 0, defaultValue=None) -> Union[str, None]: # en: Enrollment = te.enrollments[idx] # ev: Event = en.events["so8YZ9J3MeO"] # AEFI stage # # if de not in ev.dataValues: # return defaultValue # # dv: EventDataValue = ev.dataValues[de] # # if dv: # return dv.value # # return defaultValue # # def get_patient_sex(te: TrackedEntity) -> str: # value = get_attribute_value("CklPZdOd6H1", te) # # if not value: # value = get_attribute_value("oindugucx72", te) # # if "MALE" == value: # return "1" # elif "FEMALE" == value: # return "2" # # return "" # # def get_reaction_outcome(te: TrackedEntity): # value = get_data_value("yRrSDiR5v1M", te) # # if "Recovered/resolved" == value: # return "1" # elif "Recovering/resolving" == value: # return "2" # elif "Not recovered/not resolved" == value: # return "3" # elif "Recovered/resolved with sequelae" == value: # return "4" # elif "Died" == value or "Autopsy done" == value: # return "5" # elif "Unknown" == value: # return "6" # # return value # # def get_yes_no(de: str, te: TrackedEntity, idx: int = 0): # dv: EventDataValue = get_data_value(de, te, idx) # # if "true" == dv: # return "1" # # return "2" # # Path: dhis2_core/src/dhis2/e2b/models/e2b.py # class Enrollment(BaseModel): # created: datetime # lastUpdated: datetime # enrollment: str # trackedEntityInstance: str # orgUnit: str # storedBy: Optional[str] # status: str # completedDate: Optional[str] # events: List[Event] = [] # attributes: Union[Dict[str, AttributeValue], List[AttributeValue]] = [] # # class TrackedEntity(BaseModel): # created: datetime # lastUpdated: datetime # trackedEntityInstance: str # trackedEntityType: str # orgUnit: str # storedBy: Optional[str] # enrollments: List[Enrollment] = [] # attributes: Union[Dict[str, AttributeValue], List[AttributeValue]] = [] . Output only the next line.
outcome = get_reaction_outcome(te)
Continue the code snippet: <|code_start|> build_safetyreport_patient_reaction(root, te, other) def build_safetyreport_patient(root: etree.Element, te: TrackedEntity): p = etree.SubElement(root, "patient") given_name = get_attribute_value("TfdH5KvFmMy", te) family_name = get_attribute_value("aW66s2QSosT", te) if given_name: name = given_name if family_name: name = f"{name} {family_name}" p.append(E.patientinitial(name)) # should we use name here or not? dt = get_attribute_value("BiTsLcJQ95V", te) if not dt: dt = get_attribute_value("NI0QRzJvQ0k", te) # MU if dt: dt = datetime.fromisoformat(dt) dob = dt.strftime("%Y%m%d") p.append(E.patientbirthdateformat("102")) p.append(E.patientbirthdate(dob)) p.append(E.patientsex(get_patient_sex(te))) <|code_end|> . Use current file imports: import logging from datetime import datetime from uuid import uuid4 from lxml import etree from lxml.builder import E from .common import ( date_format_102, date_format_203, date_format_204, get_attribute_value, get_data_value, get_patient_sex, get_reaction_outcome, get_yes_no, ) from .models.e2b import Enrollment, TrackedEntity and context (classes, functions, or code) from other files: # Path: dhis2_core/src/dhis2/e2b/common.py # def date_format_102(dt: datetime) -> str: # return dt.strftime("%Y%m%d") # # def date_format_203(dt: datetime) -> str: # return dt.strftime("%Y%m%d%H%M") # # def date_format_204(dt: datetime) -> str: # return dt.strftime("%Y%m%d%H%M%S") # # def get_attribute_value(at: str, te: TrackedEntity, defaultValue=None) -> Union[str, None]: # av = te.attributes.get(at, defaultValue) # # if not av: # return defaultValue # # if av.value: # return av.value # # return defaultValue # # def get_data_value(de: str, te: TrackedEntity, idx: int = 0, defaultValue=None) -> Union[str, None]: # en: Enrollment = te.enrollments[idx] # ev: Event = en.events["so8YZ9J3MeO"] # AEFI stage # # if de not in ev.dataValues: # return defaultValue # # dv: EventDataValue = ev.dataValues[de] # # if dv: # return dv.value # # return defaultValue # # def get_patient_sex(te: TrackedEntity) -> str: # value = get_attribute_value("CklPZdOd6H1", te) # # if not value: # value = get_attribute_value("oindugucx72", te) # # if "MALE" == value: # return "1" # elif "FEMALE" == value: # return "2" # # return "" # # def get_reaction_outcome(te: TrackedEntity): # value = get_data_value("yRrSDiR5v1M", te) # # if "Recovered/resolved" == value: # return "1" # elif "Recovering/resolving" == value: # return "2" # elif "Not recovered/not resolved" == value: # return "3" # elif "Recovered/resolved with sequelae" == value: # return "4" # elif "Died" == value or "Autopsy done" == value: # return "5" # elif "Unknown" == value: # return "6" # # return value # # def get_yes_no(de: str, te: TrackedEntity, idx: int = 0): # dv: EventDataValue = get_data_value(de, te, idx) # # if "true" == dv: # return "1" # # return "2" # # Path: dhis2_core/src/dhis2/e2b/models/e2b.py # class Enrollment(BaseModel): # created: datetime # lastUpdated: datetime # enrollment: str # trackedEntityInstance: str # orgUnit: str # storedBy: Optional[str] # status: str # completedDate: Optional[str] # events: List[Event] = [] # attributes: Union[Dict[str, AttributeValue], List[AttributeValue]] = [] # # class TrackedEntity(BaseModel): # created: datetime # lastUpdated: datetime # trackedEntityInstance: str # trackedEntityType: str # orgUnit: str # storedBy: Optional[str] # enrollments: List[Enrollment] = [] # attributes: Union[Dict[str, AttributeValue], List[AttributeValue]] = [] . Output only the next line.
if get_yes_no("VXdRoWQOBxG", te):
Based on the snippet: <|code_start|> else: autopsyyesno = "2" datetime_of_death = None if date_of_death: datetime_of_death = datetime.fromisoformat(date_of_death) if datetime_of_death: p.append( E.patientdeath( E.patientdeathdateformat("102"), E.patientdeathdate(date_format_102(datetime_of_death)), E.patientautopsyyesno(autopsyyesno), ) ) build_safetyreport_patient_reactions(p, te) build_safetyreport_patient_drugs(p, te) p.append( E.summary( E.reportercomment(get_data_value("IV9W7YXh939", te, 0, "")), ) ) def build_safetyreport( root: etree.Element, te: TrackedEntity, <|code_end|> , predict the immediate next line with the help of imports: import logging from datetime import datetime from uuid import uuid4 from lxml import etree from lxml.builder import E from .common import ( date_format_102, date_format_203, date_format_204, get_attribute_value, get_data_value, get_patient_sex, get_reaction_outcome, get_yes_no, ) from .models.e2b import Enrollment, TrackedEntity and context (classes, functions, sometimes code) from other files: # Path: dhis2_core/src/dhis2/e2b/common.py # def date_format_102(dt: datetime) -> str: # return dt.strftime("%Y%m%d") # # def date_format_203(dt: datetime) -> str: # return dt.strftime("%Y%m%d%H%M") # # def date_format_204(dt: datetime) -> str: # return dt.strftime("%Y%m%d%H%M%S") # # def get_attribute_value(at: str, te: TrackedEntity, defaultValue=None) -> Union[str, None]: # av = te.attributes.get(at, defaultValue) # # if not av: # return defaultValue # # if av.value: # return av.value # # return defaultValue # # def get_data_value(de: str, te: TrackedEntity, idx: int = 0, defaultValue=None) -> Union[str, None]: # en: Enrollment = te.enrollments[idx] # ev: Event = en.events["so8YZ9J3MeO"] # AEFI stage # # if de not in ev.dataValues: # return defaultValue # # dv: EventDataValue = ev.dataValues[de] # # if dv: # return dv.value # # return defaultValue # # def get_patient_sex(te: TrackedEntity) -> str: # value = get_attribute_value("CklPZdOd6H1", te) # # if not value: # value = get_attribute_value("oindugucx72", te) # # if "MALE" == value: # return "1" # elif "FEMALE" == value: # return "2" # # return "" # # def get_reaction_outcome(te: TrackedEntity): # value = get_data_value("yRrSDiR5v1M", te) # # if "Recovered/resolved" == value: # return "1" # elif "Recovering/resolving" == value: # return "2" # elif "Not recovered/not resolved" == value: # return "3" # elif "Recovered/resolved with sequelae" == value: # return "4" # elif "Died" == value or "Autopsy done" == value: # return "5" # elif "Unknown" == value: # return "6" # # return value # # def get_yes_no(de: str, te: TrackedEntity, idx: int = 0): # dv: EventDataValue = get_data_value(de, te, idx) # # if "true" == dv: # return "1" # # return "2" # # Path: dhis2_core/src/dhis2/e2b/models/e2b.py # class Enrollment(BaseModel): # created: datetime # lastUpdated: datetime # enrollment: str # trackedEntityInstance: str # orgUnit: str # storedBy: Optional[str] # status: str # completedDate: Optional[str] # events: List[Event] = [] # attributes: Union[Dict[str, AttributeValue], List[AttributeValue]] = [] # # class TrackedEntity(BaseModel): # created: datetime # lastUpdated: datetime # trackedEntityInstance: str # trackedEntityType: str # orgUnit: str # storedBy: Optional[str] # enrollments: List[Enrollment] = [] # attributes: Union[Dict[str, AttributeValue], List[AttributeValue]] = [] . Output only the next line.
en: Enrollment,
Predict the next line for this snippet: <|code_start|> drug.append(E.drugenddate(date_format_102(dt))) dilutent = [] drug.append(etree.Comment("Diluent short name description:")) drug.append(etree.Comment("N = Name of diluent")) drug.append(etree.Comment("B = Dilutent batch/lot number")) drug.append(etree.Comment("EX = Dilutent expiry date")) drug.append(etree.Comment("DR = Dilutent date of reconstitution")) drug.append(etree.Comment("TR = Dilutent time of reconstitution")) if diluent_name: dilutent.append(f"N: {diluent_name}") if diluent_batch: dilutent.append(f"B: {diluent_batch}") if diluent_expiry: dilutent.append(f"EX: {diluent_expiry}") if diluent_dor: dilutent.append(f"DR: {diluent_dor}") if diluent_tor: dilutent.append(f"TR: {diluent_tor}") if dilutent: drug.append(E.drugadditional(", ".join(dilutent))) <|code_end|> with the help of current file imports: import logging from datetime import datetime from uuid import uuid4 from lxml import etree from lxml.builder import E from .common import ( date_format_102, date_format_203, date_format_204, get_attribute_value, get_data_value, get_patient_sex, get_reaction_outcome, get_yes_no, ) from .models.e2b import Enrollment, TrackedEntity and context from other files: # Path: dhis2_core/src/dhis2/e2b/common.py # def date_format_102(dt: datetime) -> str: # return dt.strftime("%Y%m%d") # # def date_format_203(dt: datetime) -> str: # return dt.strftime("%Y%m%d%H%M") # # def date_format_204(dt: datetime) -> str: # return dt.strftime("%Y%m%d%H%M%S") # # def get_attribute_value(at: str, te: TrackedEntity, defaultValue=None) -> Union[str, None]: # av = te.attributes.get(at, defaultValue) # # if not av: # return defaultValue # # if av.value: # return av.value # # return defaultValue # # def get_data_value(de: str, te: TrackedEntity, idx: int = 0, defaultValue=None) -> Union[str, None]: # en: Enrollment = te.enrollments[idx] # ev: Event = en.events["so8YZ9J3MeO"] # AEFI stage # # if de not in ev.dataValues: # return defaultValue # # dv: EventDataValue = ev.dataValues[de] # # if dv: # return dv.value # # return defaultValue # # def get_patient_sex(te: TrackedEntity) -> str: # value = get_attribute_value("CklPZdOd6H1", te) # # if not value: # value = get_attribute_value("oindugucx72", te) # # if "MALE" == value: # return "1" # elif "FEMALE" == value: # return "2" # # return "" # # def get_reaction_outcome(te: TrackedEntity): # value = get_data_value("yRrSDiR5v1M", te) # # if "Recovered/resolved" == value: # return "1" # elif "Recovering/resolving" == value: # return "2" # elif "Not recovered/not resolved" == value: # return "3" # elif "Recovered/resolved with sequelae" == value: # return "4" # elif "Died" == value or "Autopsy done" == value: # return "5" # elif "Unknown" == value: # return "6" # # return value # # def get_yes_no(de: str, te: TrackedEntity, idx: int = 0): # dv: EventDataValue = get_data_value(de, te, idx) # # if "true" == dv: # return "1" # # return "2" # # Path: dhis2_core/src/dhis2/e2b/models/e2b.py # class Enrollment(BaseModel): # created: datetime # lastUpdated: datetime # enrollment: str # trackedEntityInstance: str # orgUnit: str # storedBy: Optional[str] # status: str # completedDate: Optional[str] # events: List[Event] = [] # attributes: Union[Dict[str, AttributeValue], List[AttributeValue]] = [] # # class TrackedEntity(BaseModel): # created: datetime # lastUpdated: datetime # trackedEntityInstance: str # trackedEntityType: str # orgUnit: str # storedBy: Optional[str] # enrollments: List[Enrollment] = [] # attributes: Union[Dict[str, AttributeValue], List[AttributeValue]] = [] , which may contain function names, class names, or code. Output only the next line.
def build_safetyreport_patient_drugs(root: etree.Element, te: TrackedEntity):
Based on the snippet: <|code_start|> return target_log elif "null://" == id: log.info("Creating 'null://' target") def target_null(data: Any): log.info("Doing nothing with result") return target_null host = resolve_one(id, inventory) if "dhis2" in host.type: log.error("'dhis2' target type is not currently supported") sys.exit(-1) log.info(f"Creating target from '{host.key}' with base url '{host.baseUrl}'") def target_push(data: Any): payload: Bundle = data[1] return BaseHttpRequest(host).post("", data=payload.as_json()) return target_push def transform(config: SVCMConfig, data: Any): host: HostResolved = data[0] payload: Dict[str, Any] = data[1] <|code_end|> , predict the immediate next line with the help of imports: import json import logging import sys from typing import Any, Callable, Dict, List from dhis2.core.http import BaseHttpRequest from dhis2.core.inventory import HostResolved, Inventory, resolve_one from fhir.resources.bundle import Bundle from .models.svcm import CodeList, SVCMConfig from .svcm_resources import build_bundle and context (classes, functions, sometimes code) from other files: # Path: dhis2_core/src/dhis2/code_list/models/svcm.py # class CodeList(BaseEntity): # type: Literal["optionSets", "categories"] = "optionSets" # version: Union[str, int] = "1" # codes: List[Code] = [] # # class SVCMConfig(BaseModel): # id: str = Field(default_factory=lambda: str(uuid4())) # source: SVCMSource # target: SVCMTarget # # Path: dhis2_core/src/dhis2/code_list/svcm_resources.py # def build_bundle(code_lists: List[CodeList], base_url: str) -> Bundle: # bundle = Bundle() # bundle.type = "transaction" # bundle.entry = [] # # log.info(f"Building FHIR bundle from '{len(code_lists)}' DHIS2 code lists") # # for code_list in code_lists: # bundle.entry.append(build_value_set_bundle_entry(code_list, base_url)) # bundle.entry.append(build_code_system_bundle_entry(code_list, base_url)) # # return bundle . Output only the next line.
code_lists: List[CodeList] = []
Given the code snippet: <|code_start|> if "dhis2" in host.type: log.error("'dhis2' target type is not currently supported") sys.exit(-1) log.info(f"Creating target from '{host.key}' with base url '{host.baseUrl}'") def target_push(data: Any): payload: Bundle = data[1] return BaseHttpRequest(host).post("", data=payload.as_json()) return target_push def transform(config: SVCMConfig, data: Any): host: HostResolved = data[0] payload: Dict[str, Any] = data[1] code_lists: List[CodeList] = [] option_sets = payload.get("optionSets", []) categories = payload.get("categories", []) for option_set in option_sets: code_lists.append(CodeList(**option_set)) for category in categories: code_lists.append(CodeList(**category, type="categories")) return ( host, <|code_end|> , generate the next line using the imports in this file: import json import logging import sys from typing import Any, Callable, Dict, List from dhis2.core.http import BaseHttpRequest from dhis2.core.inventory import HostResolved, Inventory, resolve_one from fhir.resources.bundle import Bundle from .models.svcm import CodeList, SVCMConfig from .svcm_resources import build_bundle and context (functions, classes, or occasionally code) from other files: # Path: dhis2_core/src/dhis2/code_list/models/svcm.py # class CodeList(BaseEntity): # type: Literal["optionSets", "categories"] = "optionSets" # version: Union[str, int] = "1" # codes: List[Code] = [] # # class SVCMConfig(BaseModel): # id: str = Field(default_factory=lambda: str(uuid4())) # source: SVCMSource # target: SVCMTarget # # Path: dhis2_core/src/dhis2/code_list/svcm_resources.py # def build_bundle(code_lists: List[CodeList], base_url: str) -> Bundle: # bundle = Bundle() # bundle.type = "transaction" # bundle.entry = [] # # log.info(f"Building FHIR bundle from '{len(code_lists)}' DHIS2 code lists") # # for code_list in code_lists: # bundle.entry.append(build_value_set_bundle_entry(code_list, base_url)) # bundle.entry.append(build_code_system_bundle_entry(code_list, base_url)) # # return bundle . Output only the next line.
build_bundle(code_lists, host.baseUrl),
Here is a snippet: <|code_start|> class Schema(BaseModel): klass: str shareable: bool metadata: bool relativeApiEndpoint: Optional[str] plural: str displayName: str singular: str secondaryMetadata: bool collectionName: Optional[str] implicitPrivateAuthority: bool nameableObject: bool href: str subscribable: bool order: int translatable: bool identifiableObject: bool favoritable: bool subscribableObject: bool dataShareable: bool apiEndpoint: Optional[str] embeddedObject: bool defaultPrivate: str name: str namespace: Optional[str] persisted: bool references: List[str] = [] authorities: List[Authority] = [] <|code_end|> . Write the next line using the current file imports: from typing import List, Optional from pydantic import BaseModel from .property import Property and context from other files: # Path: dhis2_core/src/dhis2/core/metadata/models/property.py # class Property(BaseModel): # fieldName: Optional[str] # description: Optional[str] # simple: bool # required: bool # writable: bool # collectionName: Optional[str] # min: Optional[int] # nameableObject: bool # klass: str # propertyType: str # oneToOne: bool # propertyTransformer: bool # attribute: bool # owner: bool # readable: bool # ordered: bool # identifiableObject: bool # max: Optional[int] # manyToMany: bool # collection: bool # itemPropertyType: Optional[str] # collectionWrapping: Optional[bool] # itemKlass: Optional[str] # analyticalObject: bool # embeddedObject: bool # unique: bool # name: str # namespace: Optional[str] # persisted: bool # manyToOne: bool # constants: List[str] = [] , which may include functions, classes, or code. Output only the next line.
properties: List[Property] = []
Given the following code snippet before the placeholder: <|code_start|> log = logging.getLogger(__name__) def inspect_host(host: HostResolved): req = BaseHttpRequest(host) data = req.get("api/system/info") if not data: return <|code_end|> , predict the next line using imports from the current file: import logging from typing import List from .http import BaseHttpRequest from .inventory import HostResolved from .metadata.models.system_info import SystemInfo and context including class names, function names, and sometimes code from other files: # Path: dhis2_core/src/dhis2/core/http.py # class BaseHttpRequest: # def __init__(self, host: HostResolved, format: Union[MediaFormat, str] = MediaFormat.json): # self.host = host # self.format = format # # def get( # self, # path, # params={}, # headers={}, # ): # url = self._get_url(path) # headers = self._get_headers(headers) # auth = self._get_auth() # params = self._get_params(params) # # log.info(f"Starting GET request '{url}' with params='{params}'") # # response = requests.get( # url=url, # headers=headers, # params=params, # auth=auth, # ) # # log.info(f"Finished GET request '{response.request.url}'' with status code '{response.status_code}''") # # if not response.ok: # return self._handle_errors(response) # # data = None # # if MediaFormat.json == self.format: # data = response.json() # else: # data = response.text # # return data # # def post( # self, # path, # data, # params={}, # headers={}, # ): # url = self._get_url(path) # headers = self._get_headers(headers) # auth = self._get_auth() # params = self._get_params(params) # # if not isinstance(data, str): # data = json.dumps(data) # # if log.isEnabledFor(logging.DEBUG): # log.info(f"Starting POST request '{url}' with params='{params}' and data={data}") # else: # log.info(f"Starting POST request '{url} with params={params}'") # # response = requests.post( # url=url, # headers=headers, # params=params, # auth=auth, # data=data, # ) # # log.info(f"Finished POST request '{response.request.url}'' with status code '{response.status_code}''") # # if not response.ok: # return self._handle_errors(response) # # if MediaFormat.json == self.format: # data = response.json() # else: # data = response.text # # return data # # def _handle_errors(self, response: Response): # if 401 == response.status_code: # log.error(f"Invalid login credentials for '{self.host.key}''") # if 404 == response.status_code: # log.error(f"Invalid url '{response.request.url}', please check 'baseUrl' for '{self.host.key}'") # else: # log.error(f"Unhandled status code {response.status_code}={response.text}") # # sys.exit(-1) # # def _get_auth(self) -> Union[Tuple[str], None]: # if "http-basic" == self.host.auth.type: # return (self.host.auth.username, self.host.auth.password) # # return None # # def _get_headers(self, headers: Dict[str, str] = {}) -> Dict[str, str]: # headers = deepcopy(headers) # # if isinstance(self.format, MediaFormat): # headers["Content-Type"] = self.format.value # headers["Accept"] = self.format.value # else: # headers["Content-Type"] = self.format # headers["Accept"] = self.format # # headers["X-Requested-With"] = "XMLHttpRequest" # # headers.update(self.host.headers) # # return headers # # def _get_params(self, params={}) -> Dict[str, str]: # params = deepcopy(params) # params.update(self.host.params) # # return params # # def _get_url(self, path="") -> str: # return f"{self.host.baseUrl}/{path}" # # Path: dhis2_core/src/dhis2/core/inventory.py # class HostResolved(BaseModel): # type: Union[HostType, str] = HostType.dhis2 # key: str # baseUrl: str # headers: Mapping[str, str] = {} # params: Mapping[str, str] = {} # auth: Union[NoopAuthtype, BasicAuthtype] # # Path: dhis2_core/src/dhis2/core/metadata/models/system_info.py # class SystemInfo(BaseModel): # contextPath: str # userAgent: str # calendar: str # dateFormat: str # serverDate: str # lastAnalyticsTableSuccess: str # intervalSinceLastAnalyticsTableSuccess: str # lastAnalyticsTableRuntime: str # lastSystemMonitoringSuccess: str # version: str # revision: str # buildTime: str # jasperReportsVersion: str # environmentVariable: str # environmentVariable: str # readOnlyMode: Optional[str] # nodeId: Optional[str] # javaVersion: Optional[str] # javaVendor: Optional[str] # javaOpts: Optional[str] # osName: Optional[str] # osArchitecture: Optional[str] # osVersion: Optional[str] # externalDirectory: Optional[str] # databaseInfo: Optional[DatabaseInfo] # readReplicaCount: Optional[int] # memoryInfo: Optional[str] # cpuCores: Optional[int] # encryption: bool # emailConfigured: bool # redisEnabled: bool # systemId: str # systemName: str # instanceBaseUrl: str # clusterHostname: str # isMetadataVersionEnabled: bool # isMetadataVersionEnabled: bool . Output only the next line.
info = SystemInfo(**data)
Given snippet: <|code_start|> log = logging.getLogger(__name__) def _icd10_fetch( host: HostResolved, release_id: str, language: str, id: str, ): req = BaseHttpRequest(host) url = f"icd/release/10/{release_id}" if id: url = f"icd/release/10/{release_id}/{id}" data = req.get( url, headers={ "Accept-Language": language, "API-Version": "v2", }, ) <|code_end|> , continue by predicting the next line. Consider current file imports: import logging from typing import List from dhis2.core.http import BaseHttpRequest from dhis2.core.inventory import HostResolved from .models.icd10 import ICD10Entity and context: # Path: dhis2_core/src/dhis2/code_list/models/icd10.py # class ICD10Entity(BaseModel): # id: str = Field(alias="@id") # context: str = Field(alias="@context") # title: Optional[LanguageSpecificText] # definition: Optional[LanguageSpecificText] # longDefinition: Optional[LanguageSpecificText] # fullySpecifiedName: Optional[LanguageSpecificText] # source: Optional[str] # code: Optional[str] # note: Optional[List[LanguageSpecificText]] # codeRange: Optional[str] # # # chapter : if the entity is a chapter. (i.e. at the top level of the classification # # block : higher level entity which don't have codes # # category : An ICD entity that bears a code # # classKind: Optional[Literal["chapter", "block", "category", "modifiedcategory"]] # child: Union[List[str], List["ICD10Entity"]] = [] # parent: Union[List[str], List["ICD10Entity"]] = [] # browserUrl: Optional[str] which might include code, classes, or functions. Output only the next line.
return ICD10Entity(**data)
Based on the snippet: <|code_start|> log = logging.getLogger(__name__) class MediaFormat(str, Enum): json = "application/json" text = "text/plain" class BaseHttpRequest: <|code_end|> , predict the immediate next line with the help of imports: import json import logging import sys import requests from copy import deepcopy from enum import Enum from typing import Dict, Tuple, Union from requests.models import Response # noqa from .inventory import HostResolved and context (classes, functions, sometimes code) from other files: # Path: dhis2_core/src/dhis2/core/inventory.py # class HostResolved(BaseModel): # type: Union[HostType, str] = HostType.dhis2 # key: str # baseUrl: str # headers: Mapping[str, str] = {} # params: Mapping[str, str] = {} # auth: Union[NoopAuthtype, BasicAuthtype] . Output only the next line.
def __init__(self, host: HostResolved, format: Union[MediaFormat, str] = MediaFormat.json):
Based on the snippet: <|code_start|> class TestGenerator(TestCase): def setUp(self): super().setUp() self.patch_fs = patch('email_parser.placeholder.fs') self.mock_fs = self.patch_fs.start() self.mock_fs.read_file.return_value = 'test' self.patch_reader = patch('email_parser.placeholder.reader') self.mock_reader = self.patch_reader.start() def tearDown(self): super().tearDown() self.patch_fs.stop() self.patch_reader.stop() def test_happy_path(self): self.mock_fs.emails.return_value = iter([Email('test_name', 'en', 'path')]) self.mock_reader.read.return_value = ('', {'segment': Placeholder('segment', '{{placeholder}}')}) <|code_end|> , predict the immediate next line with the help of imports: from unittest import TestCase from unittest.mock import patch from collections import Counter from email_parser import placeholder, fs from email_parser.model import * and context (classes, functions, sometimes code) from other files: # Path: email_parser/placeholder.py # def _extract_placeholders(text): # def expected_placeholders_file(root_path): # def _email_placeholders(root_path, email): # def get_email_validation(root_path, email): # def generate_config(root_path): # # Path: email_parser/fs.py # def _parse_params(pattern): # def _has_correct_ext(path, pattern): # def _emails(root_path, pattern, params): # def get_email_filepath(email_name, locale): # def get_template_filepath(root_path, template_name, template_type): # def get_template_resources_filepaths(root_path, template): # def emails(root_path, email_name=None, locale=None): # def email(root_path, email_name, locale): # def global_email(root_path, locale): # def read_file(*path_parts): # def save_file(content, *path_parts): # def delete_file(*path_parts): # def save_email(root_path, content, email_name, locale): # def save_template(root_path, template_filename, template_type, template_content): # def save_parsed_email(root_path, email, subject, text, html): # def resources(root_path): # def get_html_sections_map(root_path): . Output only the next line.
config = placeholder.generate_config('.')
Continue the code snippet: <|code_start|>class TestGenerator(TestCase): def setUp(self): super().setUp() self.patch_fs = patch('email_parser.placeholder.fs') self.mock_fs = self.patch_fs.start() self.mock_fs.read_file.return_value = 'test' self.patch_reader = patch('email_parser.placeholder.reader') self.mock_reader = self.patch_reader.start() def tearDown(self): super().tearDown() self.patch_fs.stop() self.patch_reader.stop() def test_happy_path(self): self.mock_fs.emails.return_value = iter([Email('test_name', 'en', 'path')]) self.mock_reader.read.return_value = ('', {'segment': Placeholder('segment', '{{placeholder}}')}) config = placeholder.generate_config('.') self.assertEqual(config, {'test_name': Counter({'placeholder': 1})}) def test_no_emails(self): self.mock_fs.emails.return_value = iter([]) config = placeholder.generate_config('.') self.assertEqual(config, {}) class TestValidate(TestCase): def setUp(self): <|code_end|> . Use current file imports: from unittest import TestCase from unittest.mock import patch from collections import Counter from email_parser import placeholder, fs from email_parser.model import * and context (classes, functions, or code) from other files: # Path: email_parser/placeholder.py # def _extract_placeholders(text): # def expected_placeholders_file(root_path): # def _email_placeholders(root_path, email): # def get_email_validation(root_path, email): # def generate_config(root_path): # # Path: email_parser/fs.py # def _parse_params(pattern): # def _has_correct_ext(path, pattern): # def _emails(root_path, pattern, params): # def get_email_filepath(email_name, locale): # def get_template_filepath(root_path, template_name, template_type): # def get_template_resources_filepaths(root_path, template): # def emails(root_path, email_name=None, locale=None): # def email(root_path, email_name, locale): # def global_email(root_path, locale): # def read_file(*path_parts): # def save_file(content, *path_parts): # def delete_file(*path_parts): # def save_email(root_path, content, email_name, locale): # def save_template(root_path, template_filename, template_type, template_content): # def save_parsed_email(root_path, email, subject, text, html): # def resources(root_path): # def get_html_sections_map(root_path): . Output only the next line.
self.email = fs.Email('test_name', 'en', 'path')
Based on the snippet: <|code_start|> """ self.globals_xml = etree.fromstring(""" <resources> <string name="content">dummy global</string> <string name="order" type="attribute">asc</string> </resources> """) self.template_str = '<html><head></head><body>{{content}}{{global_content}}</body></html>' self.patch_parse = patch('email_parser.reader.etree.parse') self.mock_parse = self.patch_parse.start() self.mock_parse.return_value = etree.ElementTree(self.globals_xml).getroot() self.patch_fs = patch('email_parser.reader.fs') self.mock_fs = self.patch_fs.start() self.mock_fs.read_file.return_value = 'test' def tearDown(self): super().tearDown() self.patch_fs.stop() self.patch_parse.stop() def test_template(self): self.mock_fs.read_file.side_effect = iter([self.email_content, self.template_str, 'test']) expected_placeholders = { 'content': MetaPlaceholder('content'), 'global_content': MetaPlaceholder('global_content') } expected_template = Template('dummy_template.html', ['dummy_template.css'], '<style>test</style>', self.template_str, expected_placeholders, EmailType.transactional.value) <|code_end|> , predict the immediate next line with the help of imports: import os.path from unittest import TestCase from unittest.mock import patch from lxml import etree from email_parser import reader from email_parser.model import * and context (classes, functions, sometimes code) from other files: # Path: email_parser/reader.py # def parse_placeholder(placeholder_str): # def _placeholders(tree, prefix=''): # def get_template_parts(root_path, template_filename, template_type): # def get_inline_style(root_path, styles_names): # def _template(root_path, tree): # def _handle_xml_parse_error(file_path, exception): # def _read_xml(path): # def _read_xml_from_content(content): # def _sort_from_template(root_path, template_filename, template_type, placeholders): # def create_email_content(root_path, template_name, styles, placeholders, email_type): # def get_global_placeholders(root_path, locale): # def get_inferred_placeholders(meta_placeholders, placeholders): # def read_from_content(root_path, email_content, locale): # def read(root_path, email): # def get_email_type(root_path, email): . Output only the next line.
template, _ = reader.read('.', self.email)
Predict the next line for this snippet: <|code_start|> class TestTextRenderer(TestCase): def setUp(self): self.email_locale = 'locale' self.template = Template('dummy', [], '<style>body {}</style>', '<body>{{content1}}</body>', ['content', 'content1', 'content2'], None) <|code_end|> with the help of current file imports: from unittest import TestCase from unittest.mock import patch from email_parser.model import * from email_parser import renderer, const, config and context from other files: # Path: email_parser/renderer.py # def _md_to_html(text, base_url=None): # def _split_subject(placeholders): # def _transform_extended_tags(content): # def __init__(self, template, email_locale): # def _inline_css(self, html, css): # def _wrap_with_text_direction(self, html): # def _wrap_with_highlight(self, html, highlight): # def _render_placeholder(self, placeholder, variant=None, highlight=None): # def _concat_parts(self, subject, parts, variant): # def render(self, placeholders, variant=None, highlight=None): # def __init__(self, template, email_locale): # def _html_to_text(self, html): # def _md_to_text(self, text, base_url=None): # def render(self, placeholders, variant=None): # def render(self, placeholders, variant=None): # def render(email_locale, template, placeholders, variant=None, highlight=None): # class HtmlRenderer(object): # class TextRenderer(object): # class SubjectRenderer(object): # # Path: email_parser/const.py # SUBJECT_EXTENSION = '.subject' # TEXT_EXTENSION = '.text' # HTML_EXTENSION = '.html' # CSS_EXTENSION = '.css' # SOURCE_EXTENSION = '.xml' # SUBJECT_PLACEHOLDER = 'subject' # GLOBALS_EMAIL_NAME = 'global' # GLOBALS_PLACEHOLDER_PREFIX = 'global_' # REPO_SRC_PATH = 'src' # PLACEHOLDERS_FILENAME = 'placeholders_config.json' # INLINE_TEXT_PATTERN = r'\[{2}(.+)\]{2}' # IMAGE_PATTERN = '![{}]({}/{})' # SEGMENT_REGEX = r'\<string[^>]*>' # SEGMENT_NAME_REGEX = r' name="([^"]+)"' # TEXT_EMAIL_PLACEHOLDER_SEPARATOR = '\n\n' # HTML_PARSER = 'lxml' # LOCALE_PLACEHOLDER = '{link_locale}' # DEFAULT_LOCALE = 'en' # DEFAULT_WORKER_POOL = 10 # JSON_INDENT = 4 # # Path: email_parser/config.py # def init(*, # _paths=_default_paths, # _pattern=_default_pattern, # _base_img_path=_default_base_img_path, # _rtl_locales=_default_rtl, # _lang_mappings=_default_lang_mappings): , which may contain function names, class names, or code. Output only the next line.
self.r = renderer.TextRenderer(self.template, self.email_locale)
Continue the code snippet: <|code_start|> class TestTextRenderer(TestCase): def setUp(self): self.email_locale = 'locale' self.template = Template('dummy', [], '<style>body {}</style>', '<body>{{content1}}</body>', ['content', 'content1', 'content2'], None) self.r = renderer.TextRenderer(self.template, self.email_locale) def test_happy_path(self): placeholders = {'content': Placeholder('content', 'dummy content')} actual = self.r.render(placeholders) self.assertEqual('dummy content', actual) def test_render_variant(self): placeholders = {'content': Placeholder('content', 'dummy content', variants={'B': 'awesome content'})} actual = self.r.render(placeholders, variant='B') self.assertEqual('awesome content', actual) def test_concat_multiple_placeholders(self): placeholders = { 'content1': Placeholder('content', 'dummy content'), 'content2': Placeholder('content2', 'dummy content') } <|code_end|> . Use current file imports: from unittest import TestCase from unittest.mock import patch from email_parser.model import * from email_parser import renderer, const, config and context (classes, functions, or code) from other files: # Path: email_parser/renderer.py # def _md_to_html(text, base_url=None): # def _split_subject(placeholders): # def _transform_extended_tags(content): # def __init__(self, template, email_locale): # def _inline_css(self, html, css): # def _wrap_with_text_direction(self, html): # def _wrap_with_highlight(self, html, highlight): # def _render_placeholder(self, placeholder, variant=None, highlight=None): # def _concat_parts(self, subject, parts, variant): # def render(self, placeholders, variant=None, highlight=None): # def __init__(self, template, email_locale): # def _html_to_text(self, html): # def _md_to_text(self, text, base_url=None): # def render(self, placeholders, variant=None): # def render(self, placeholders, variant=None): # def render(email_locale, template, placeholders, variant=None, highlight=None): # class HtmlRenderer(object): # class TextRenderer(object): # class SubjectRenderer(object): # # Path: email_parser/const.py # SUBJECT_EXTENSION = '.subject' # TEXT_EXTENSION = '.text' # HTML_EXTENSION = '.html' # CSS_EXTENSION = '.css' # SOURCE_EXTENSION = '.xml' # SUBJECT_PLACEHOLDER = 'subject' # GLOBALS_EMAIL_NAME = 'global' # GLOBALS_PLACEHOLDER_PREFIX = 'global_' # REPO_SRC_PATH = 'src' # PLACEHOLDERS_FILENAME = 'placeholders_config.json' # INLINE_TEXT_PATTERN = r'\[{2}(.+)\]{2}' # IMAGE_PATTERN = '![{}]({}/{})' # SEGMENT_REGEX = r'\<string[^>]*>' # SEGMENT_NAME_REGEX = r' name="([^"]+)"' # TEXT_EMAIL_PLACEHOLDER_SEPARATOR = '\n\n' # HTML_PARSER = 'lxml' # LOCALE_PLACEHOLDER = '{link_locale}' # DEFAULT_LOCALE = 'en' # DEFAULT_WORKER_POOL = 10 # JSON_INDENT = 4 # # Path: email_parser/config.py # def init(*, # _paths=_default_paths, # _pattern=_default_pattern, # _base_img_path=_default_base_img_path, # _rtl_locales=_default_rtl, # _lang_mappings=_default_lang_mappings): . Output only the next line.
expected = const.TEXT_EMAIL_PLACEHOLDER_SEPARATOR.join(['dummy content', 'dummy content'])
Using the snippet: <|code_start|> 'subject': Placeholder('subject', 'dummy subject', variants={'B': 'experiment subject'}) } def test_happy_path(self): actual = self.r.render(self.placeholders) self.assertEqual('dummy subject', actual) def test_variant(self): actual = self.r.render(self.placeholders, variant='B') self.assertEqual('experiment subject', actual) def test_raise_error_for_missing_subject(self): placeholders = {'content': 'dummy content'} with self.assertRaises(MissingSubjectError): self.r.render(placeholders) class TestHtmlRenderer(TestCase): def _get_renderer(self, template_html, template_placeholders, **kwargs): template = Template( name='template_name', styles_names=['template_style.css', 'template_style2.css'], styles='', content=template_html, placeholders=template_placeholders, type=None) return renderer.HtmlRenderer(template, kwargs.get('email_locale', const.DEFAULT_LOCALE)) def setUp(self): self.email_locale = 'locale' <|code_end|> , determine the next line of code. You have imports: from unittest import TestCase from unittest.mock import patch from email_parser.model import * from email_parser import renderer, const, config and context (class names, function names, or code) available: # Path: email_parser/renderer.py # def _md_to_html(text, base_url=None): # def _split_subject(placeholders): # def _transform_extended_tags(content): # def __init__(self, template, email_locale): # def _inline_css(self, html, css): # def _wrap_with_text_direction(self, html): # def _wrap_with_highlight(self, html, highlight): # def _render_placeholder(self, placeholder, variant=None, highlight=None): # def _concat_parts(self, subject, parts, variant): # def render(self, placeholders, variant=None, highlight=None): # def __init__(self, template, email_locale): # def _html_to_text(self, html): # def _md_to_text(self, text, base_url=None): # def render(self, placeholders, variant=None): # def render(self, placeholders, variant=None): # def render(email_locale, template, placeholders, variant=None, highlight=None): # class HtmlRenderer(object): # class TextRenderer(object): # class SubjectRenderer(object): # # Path: email_parser/const.py # SUBJECT_EXTENSION = '.subject' # TEXT_EXTENSION = '.text' # HTML_EXTENSION = '.html' # CSS_EXTENSION = '.css' # SOURCE_EXTENSION = '.xml' # SUBJECT_PLACEHOLDER = 'subject' # GLOBALS_EMAIL_NAME = 'global' # GLOBALS_PLACEHOLDER_PREFIX = 'global_' # REPO_SRC_PATH = 'src' # PLACEHOLDERS_FILENAME = 'placeholders_config.json' # INLINE_TEXT_PATTERN = r'\[{2}(.+)\]{2}' # IMAGE_PATTERN = '![{}]({}/{})' # SEGMENT_REGEX = r'\<string[^>]*>' # SEGMENT_NAME_REGEX = r' name="([^"]+)"' # TEXT_EMAIL_PLACEHOLDER_SEPARATOR = '\n\n' # HTML_PARSER = 'lxml' # LOCALE_PLACEHOLDER = '{link_locale}' # DEFAULT_LOCALE = 'en' # DEFAULT_WORKER_POOL = 10 # JSON_INDENT = 4 # # Path: email_parser/config.py # def init(*, # _paths=_default_paths, # _pattern=_default_pattern, # _base_img_path=_default_base_img_path, # _rtl_locales=_default_rtl, # _lang_mappings=_default_lang_mappings): . Output only the next line.
config.init(_base_img_path='images_base')
Given the code snippet: <|code_start|> def read_fixture(filename): with open(os.path.join('tests/fixtures', filename)) as fp: return fp.read() class TestParser(TestCase): def setUp(self): self.parser = email_parser.Parser('./tests') self.maxDiff = None def tearDown(self): <|code_end|> , generate the next line using the imports in this file: import os import email_parser from unittest import TestCase from unittest.mock import patch from email_parser import config from email_parser.model import EmailType and context (functions, classes, or occasionally code) from other files: # Path: email_parser/config.py # def init(*, # _paths=_default_paths, # _pattern=_default_pattern, # _base_img_path=_default_base_img_path, # _rtl_locales=_default_rtl, # _lang_mappings=_default_lang_mappings): # # Path: email_parser/model.py # class EmailType(Enum): # marketing = 'marketing' # transactional = 'transactional' . Output only the next line.
config.init()
Given the code snippet: <|code_start|> # are templates separated by type? self.assertIn('marketing', actual_templates.keys()) self.assertIn('transactional', actual_templates.keys()) # are templates assigned to correct type? self.assertIn('basic_marketing_template.html', actual_templates['marketing'].keys()) self.assertIn('basic_template.html', actual_templates['transactional'].keys()) # are placeholders assigned to correct template? template_html__keys = actual_templates['transactional']['basic_template.html'].keys() self.assertEqual(basic_template_placeholders, list(template_html__keys)) template_html__keys = actual_templates['marketing']['globale_template.html'].keys() self.assertEqual(globale_template_placeholders, list(template_html__keys)) self.assertIn('header-with-background.html', sections.keys()) self.assertIn('basic_template.css', styles) def test_get_email_filepaths_all_locale(self): expected = ['src/ar/email.xml', 'src/en/email.xml', 'src/fr/email.xml'] actual = self.parser.get_email_filepaths('email') self.assertEqual(actual, expected) def test_get_email_filepaths_single_locale(self): expected = ['src/ar/email.xml'] actual = self.parser.get_email_filepaths('email', 'ar') self.assertEqual(actual, expected) def test_equality(self): parserA = email_parser.Parser('./tests') parserB = email_parser.Parser('./tests') self.assertEqual(parserA, parserB) def test_get_email_components(self): <|code_end|> , generate the next line using the imports in this file: import os import email_parser from unittest import TestCase from unittest.mock import patch from email_parser import config from email_parser.model import EmailType and context (functions, classes, or occasionally code) from other files: # Path: email_parser/config.py # def init(*, # _paths=_default_paths, # _pattern=_default_pattern, # _base_img_path=_default_base_img_path, # _rtl_locales=_default_rtl, # _lang_mappings=_default_lang_mappings): # # Path: email_parser/model.py # class EmailType(Enum): # marketing = 'marketing' # transactional = 'transactional' . Output only the next line.
expected = ('basic_template.html', EmailType.transactional.value, ['basic_template.css'],
Predict the next line for this snippet: <|code_start|> def read_fixture(filename): with open(os.path.join('tests/fixtures', filename)) as fp: return fp.read() class TestParser(TestCase): maxDiff = None @classmethod def setUpClass(cls): cls.root_path = tempfile.mkdtemp() shutil.copytree(os.path.join('./tests', config.paths.source), os.path.join(cls.root_path, config.paths.source)) shutil.copytree( os.path.join('./tests', config.paths.templates), os.path.join(cls.root_path, config.paths.templates)) cmd.parse_emails(cls.root_path) @classmethod def tearDownClass(cls): shutil.rmtree(cls.root_path) def _run_and_assert(self, actual_filename, expected_filename=None, locale='en'): expected_filename = expected_filename or actual_filename expected = read_fixture(expected_filename).strip() <|code_end|> with the help of current file imports: import os import tempfile import shutil from unittest import TestCase from email_parser import fs, cmd, config and context from other files: # Path: email_parser/fs.py # def _parse_params(pattern): # def _has_correct_ext(path, pattern): # def _emails(root_path, pattern, params): # def get_email_filepath(email_name, locale): # def get_template_filepath(root_path, template_name, template_type): # def get_template_resources_filepaths(root_path, template): # def emails(root_path, email_name=None, locale=None): # def email(root_path, email_name, locale): # def global_email(root_path, locale): # def read_file(*path_parts): # def save_file(content, *path_parts): # def delete_file(*path_parts): # def save_email(root_path, content, email_name, locale): # def save_template(root_path, template_filename, template_type, template_content): # def save_parsed_email(root_path, email, subject, text, html): # def resources(root_path): # def get_html_sections_map(root_path): # # Path: email_parser/cmd.py # class ProgressConsoleHandler(logging.StreamHandler): # def __init__(self, err_queue, warn_queue, *args, **kwargs): # def _store_msg(self, msg, loglevel): # def error_msgs(self): # def warning_msgs(self): # def _print_msg(self, stream, msg, record): # def _flush_store(self, stream, msgs, header): # def _flush_errors(self, stream): # def _write_msg(self, stream, msg, record): # def emit(self, record): # def read_args(argsargs=argparse.ArgumentParser): # def _parse_and_save(email, parser): # def _parse_emails_batch(emails, parser): # def _parse_emails(loop, root_path): # def parse_emails(root_path): # def print_version(): # def generate_config(root_path): # def execute_command(args): # def init_log(verbose): # def init_loop(): # def main(): # # Path: email_parser/config.py # def init(*, # _paths=_default_paths, # _pattern=_default_pattern, # _base_img_path=_default_base_img_path, # _rtl_locales=_default_rtl, # _lang_mappings=_default_lang_mappings): , which may contain function names, class names, or code. Output only the next line.
actual = fs.read_file(TestParser.root_path, config.paths.destination, locale, actual_filename).strip()
Given snippet: <|code_start|> def read_fixture(filename): with open(os.path.join('tests/fixtures', filename)) as fp: return fp.read() class TestParser(TestCase): maxDiff = None @classmethod def setUpClass(cls): cls.root_path = tempfile.mkdtemp() shutil.copytree(os.path.join('./tests', config.paths.source), os.path.join(cls.root_path, config.paths.source)) shutil.copytree( os.path.join('./tests', config.paths.templates), os.path.join(cls.root_path, config.paths.templates)) <|code_end|> , continue by predicting the next line. Consider current file imports: import os import tempfile import shutil from unittest import TestCase from email_parser import fs, cmd, config and context: # Path: email_parser/fs.py # def _parse_params(pattern): # def _has_correct_ext(path, pattern): # def _emails(root_path, pattern, params): # def get_email_filepath(email_name, locale): # def get_template_filepath(root_path, template_name, template_type): # def get_template_resources_filepaths(root_path, template): # def emails(root_path, email_name=None, locale=None): # def email(root_path, email_name, locale): # def global_email(root_path, locale): # def read_file(*path_parts): # def save_file(content, *path_parts): # def delete_file(*path_parts): # def save_email(root_path, content, email_name, locale): # def save_template(root_path, template_filename, template_type, template_content): # def save_parsed_email(root_path, email, subject, text, html): # def resources(root_path): # def get_html_sections_map(root_path): # # Path: email_parser/cmd.py # class ProgressConsoleHandler(logging.StreamHandler): # def __init__(self, err_queue, warn_queue, *args, **kwargs): # def _store_msg(self, msg, loglevel): # def error_msgs(self): # def warning_msgs(self): # def _print_msg(self, stream, msg, record): # def _flush_store(self, stream, msgs, header): # def _flush_errors(self, stream): # def _write_msg(self, stream, msg, record): # def emit(self, record): # def read_args(argsargs=argparse.ArgumentParser): # def _parse_and_save(email, parser): # def _parse_emails_batch(emails, parser): # def _parse_emails(loop, root_path): # def parse_emails(root_path): # def print_version(): # def generate_config(root_path): # def execute_command(args): # def init_log(verbose): # def init_loop(): # def main(): # # Path: email_parser/config.py # def init(*, # _paths=_default_paths, # _pattern=_default_pattern, # _base_img_path=_default_base_img_path, # _rtl_locales=_default_rtl, # _lang_mappings=_default_lang_mappings): which might include code, classes, or functions. Output only the next line.
cmd.parse_emails(cls.root_path)
Given the following code snippet before the placeholder: <|code_start|> def read_fixture(filename): with open(os.path.join('tests/fixtures', filename)) as fp: return fp.read() class TestParser(TestCase): maxDiff = None @classmethod def setUpClass(cls): cls.root_path = tempfile.mkdtemp() <|code_end|> , predict the next line using imports from the current file: import os import tempfile import shutil from unittest import TestCase from email_parser import fs, cmd, config and context including class names, function names, and sometimes code from other files: # Path: email_parser/fs.py # def _parse_params(pattern): # def _has_correct_ext(path, pattern): # def _emails(root_path, pattern, params): # def get_email_filepath(email_name, locale): # def get_template_filepath(root_path, template_name, template_type): # def get_template_resources_filepaths(root_path, template): # def emails(root_path, email_name=None, locale=None): # def email(root_path, email_name, locale): # def global_email(root_path, locale): # def read_file(*path_parts): # def save_file(content, *path_parts): # def delete_file(*path_parts): # def save_email(root_path, content, email_name, locale): # def save_template(root_path, template_filename, template_type, template_content): # def save_parsed_email(root_path, email, subject, text, html): # def resources(root_path): # def get_html_sections_map(root_path): # # Path: email_parser/cmd.py # class ProgressConsoleHandler(logging.StreamHandler): # def __init__(self, err_queue, warn_queue, *args, **kwargs): # def _store_msg(self, msg, loglevel): # def error_msgs(self): # def warning_msgs(self): # def _print_msg(self, stream, msg, record): # def _flush_store(self, stream, msgs, header): # def _flush_errors(self, stream): # def _write_msg(self, stream, msg, record): # def emit(self, record): # def read_args(argsargs=argparse.ArgumentParser): # def _parse_and_save(email, parser): # def _parse_emails_batch(emails, parser): # def _parse_emails(loop, root_path): # def parse_emails(root_path): # def print_version(): # def generate_config(root_path): # def execute_command(args): # def init_log(verbose): # def init_loop(): # def main(): # # Path: email_parser/config.py # def init(*, # _paths=_default_paths, # _pattern=_default_pattern, # _base_img_path=_default_base_img_path, # _rtl_locales=_default_rtl, # _lang_mappings=_default_lang_mappings): . Output only the next line.
shutil.copytree(os.path.join('./tests', config.paths.source), os.path.join(cls.root_path, config.paths.source))
Predict the next line after this snippet: <|code_start|> def is_dir(self): return self._is_dir def is_file(self): return not self._is_dir def resolve(self): return self.path def relative_to(self, base): return MockPath(self.path, is_dir=self._is_dir, parent=self._parent) def __str__(self): return self.path class TestFs(TestCase): def setUp(self): self.patch_path = patch('email_parser.fs.Path') self.mock_path = self.patch_path.start() self.showDiff = True def tearDown(self): super().tearDown() self.patch_path.stop() def test_emails_happy_path(self): expected = Email('name1', 'locale1', 'locale1/name1.xml') self.mock_path.return_value.glob.return_value = [MockPath(expected.path)] <|code_end|> using the current file's imports: from unittest import TestCase from unittest.mock import patch from email_parser import fs from email_parser.model import * and any relevant context from other files: # Path: email_parser/fs.py # def _parse_params(pattern): # def _has_correct_ext(path, pattern): # def _emails(root_path, pattern, params): # def get_email_filepath(email_name, locale): # def get_template_filepath(root_path, template_name, template_type): # def get_template_resources_filepaths(root_path, template): # def emails(root_path, email_name=None, locale=None): # def email(root_path, email_name, locale): # def global_email(root_path, locale): # def read_file(*path_parts): # def save_file(content, *path_parts): # def delete_file(*path_parts): # def save_email(root_path, content, email_name, locale): # def save_template(root_path, template_filename, template_type, template_content): # def save_parsed_email(root_path, email, subject, text, html): # def resources(root_path): # def get_html_sections_map(root_path): . Output only the next line.
actual = list(fs.emails('.'))
Given snippet: <|code_start|>def run_major_axis_anisotropy_calculations(submit=True): """ Perform static calculations with the magnetic axis along 100, 010, and 001. Kwargs: submit (bool): Whether or not to submit the job. """ if not os.path.isdir('MAE'): os.mkdir('MAE') os.chdir('MAE') for d in ['100', '010', '001']: if not os.path.isdir(d): os.path.mkdir(d) os.chdir(d) os.system('cp ../CONTCAR POSCAR') os.system('cp ../POTCAR .') axis = [float(char) for char in d] # Small positive number, see vasp manual if d in ['001', '010']: axis[0] = 0.00000001 else: axis[1] = 0.00000001 saxis = ' '.join(axis) incar_dict = INCAR_DICT incar_dict.update({'EDIFF': 1e-8, 'GGA_COMPAT': False, 'ISMEAR': -5, 'LORBIT': 11, 'LSORBIT': True, 'LWAVE': False, 'LCHARG': False, 'LAECHG': False, <|code_end|> , continue by predicting the next line. Consider current file imports: import os from pymatgen.io.vasp.inputs import Incar from twod_materials.stability.startup import get_magmom_string, INCAR_DICT and context: # Path: twod_materials/stability/startup.py # PACKAGE_PATH = twod_materials.__file__.replace('__init__.pyc', '') # PACKAGE_PATH = PACKAGE_PATH.replace('__init__.py', '') # PACKAGE_PATH = '/'.join(PACKAGE_PATH.split('/')[:-2]) # INCAR_DICT = { # '@class': 'Incar', '@module': 'pymatgen.io.vasp.inputs', 'AGGAC': 0.0, # 'EDIFF': 1e-04, 'GGA': 'Bo', 'IBRION': 2, 'ISIF': 3, 'ISMEAR': 1, # 'LAECHG': True, 'LCHARG': True, 'LREAL': 'Auto', 'LUSE_VDW': True, # 'NPAR': 4, 'NSW': 50, 'PARAM1': 0.1833333333, 'PARAM2': 0.22, # 'PREC': 'Accurate', 'ENCUT': 500, 'SIGMA': 0.1, 'LVTOT': True, # 'LVHAR': True, 'ALGO': 'Fast', 'ISPIN': 2 # } # MPR = MPRester(os.environ['MP_API']) # MPR = MPRester(config_vars['mp_api']) # VASP = config_vars['normal_binary'] # VASP_2D = config_vars['twod_binary'] # VDW_KERNEL = config_vars['vdw_kernel'] # QUEUE = config_vars['queue_system'].lower() # QUEUE = 'slurm' # QUEUE = 'pbs' # def relax(dim=2, submit=True, force_overwrite=False): which might include code, classes, or functions. Output only the next line.
'MAGMOM': get_magmom_string(), 'SAXIS': saxis})
Here is a snippet: <|code_start|> def run_major_axis_anisotropy_calculations(submit=True): """ Perform static calculations with the magnetic axis along 100, 010, and 001. Kwargs: submit (bool): Whether or not to submit the job. """ if not os.path.isdir('MAE'): os.mkdir('MAE') os.chdir('MAE') for d in ['100', '010', '001']: if not os.path.isdir(d): os.path.mkdir(d) os.chdir(d) os.system('cp ../CONTCAR POSCAR') os.system('cp ../POTCAR .') axis = [float(char) for char in d] # Small positive number, see vasp manual if d in ['001', '010']: axis[0] = 0.00000001 else: axis[1] = 0.00000001 saxis = ' '.join(axis) <|code_end|> . Write the next line using the current file imports: import os from pymatgen.io.vasp.inputs import Incar from twod_materials.stability.startup import get_magmom_string, INCAR_DICT and context from other files: # Path: twod_materials/stability/startup.py # PACKAGE_PATH = twod_materials.__file__.replace('__init__.pyc', '') # PACKAGE_PATH = PACKAGE_PATH.replace('__init__.py', '') # PACKAGE_PATH = '/'.join(PACKAGE_PATH.split('/')[:-2]) # INCAR_DICT = { # '@class': 'Incar', '@module': 'pymatgen.io.vasp.inputs', 'AGGAC': 0.0, # 'EDIFF': 1e-04, 'GGA': 'Bo', 'IBRION': 2, 'ISIF': 3, 'ISMEAR': 1, # 'LAECHG': True, 'LCHARG': True, 'LREAL': 'Auto', 'LUSE_VDW': True, # 'NPAR': 4, 'NSW': 50, 'PARAM1': 0.1833333333, 'PARAM2': 0.22, # 'PREC': 'Accurate', 'ENCUT': 500, 'SIGMA': 0.1, 'LVTOT': True, # 'LVHAR': True, 'ALGO': 'Fast', 'ISPIN': 2 # } # MPR = MPRester(os.environ['MP_API']) # MPR = MPRester(config_vars['mp_api']) # VASP = config_vars['normal_binary'] # VASP_2D = config_vars['twod_binary'] # VDW_KERNEL = config_vars['vdw_kernel'] # QUEUE = config_vars['queue_system'].lower() # QUEUE = 'slurm' # QUEUE = 'pbs' # def relax(dim=2, submit=True, force_overwrite=False): , which may include functions, classes, or code. Output only the next line.
incar_dict = INCAR_DICT