Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Predict the next line for this snippet: <|code_start|># 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 ThreadCapability(BaseCapability): def __init__(self, node_id, petition_id, daemons=['wpantund', 'otbr-agent'], rcp=False): self.thread_endpoint = ThreadSimPipe(node_id, petition_id, rcp) self.thread_endpoint.open() self.logger = CirqueLog.get_cirque_logger(self.__class__.__name__) self.daemons = daemons for daemon in daemons: if daemon not in {'wpantund', 'otbr-agent'}: self.logger.warning( 'using unkown thread daemon mode: {}'.format(daemon)) @property def name(self): return 'Thread' <|code_end|> with the help of current file imports: from cirque.capabilities.basecapability import BaseCapability from cirque.connectivity.threadsimpipe import ThreadSimPipe from cirque.common.cirquelog import CirqueLog and context from other files: # Path: cirque/capabilities/basecapability.py # class BaseCapability: # # @property # def name(self): # return '' # # def get_docker_run_args(self, docker_node): # return {} # # def enable_capability(self, docker_node): # pass # # def disable_capability(self, docker_node): # pass # # @property # def description(self): # return {} # # Path: cirque/connectivity/threadsimpipe.py # class ThreadSimPipe: # __next_petition_id = 0 # __THREAD_GROUP_SIZE = 34 # __petition_mutex = Lock() # # @classmethod # def get_next_petition(cls): # with cls.__petition_mutex: # cls.__next_petition_id += 1 # return cls.__next_petition_id # # def __init__(self, node_id, petition_id=0, rcp=False): # self._socat_pipe = SocatPipePair() # self.pipe_path_for_user = None # self.pipe_path_for_ncp = None # self.node_id = node_id # self.radio_fd = None # self.radio_process = None # self.petition_id = petition_id # if rcp: # self.radio_command = 'ot-rcp' # else: # self.radio_command = 'ot-ncp-ftd' # # def open(self): # self._socat_pipe.open() # self.pipe_path_for_user = self._socat_pipe.pipe0 # self.pipe_path_for_ncp = self._socat_pipe.pipe1 # self.radio_fd = os.open(self.pipe_path_for_ncp, os.O_RDWR) # env = os.environ # env['PORT_OFFSET'] = str(self.petition_id * self.__THREAD_GROUP_SIZE) # self.radio_process = subprocess.Popen( # [self.radio_command, '{}'.format(self.node_id)], # env=env, # stdout=self.radio_fd, # stdin=self.radio_fd) # # def close(self): # if self.radio_fd is not None: # os.close(self.radio_fd) # self.radio_fd = None # if self.radio_process is not None: # self.radio_process.terminate() # self.radio_process = None # if self._socat_pipe is not None: # self._socat_pipe.close() # self._socat_pipe = None # if os.path.exists('./tmp'): # shutil.rmtree('./tmp') # # def __del__(self): # self.close() # # Path: cirque/common/cirquelog.py # class CirqueLog: # # logger = None # # @classmethod # def setup_cirque_logger(cls, level=logging.INFO): # if cls.logger: # return # cls.logger = logging.getLogger('cirque') # cls.logger.setLevel(level) # sh = logging.StreamHandler() # sh.setFormatter( # logging.Formatter('%(asctime)s [%(name)s] %(levelname)s %(message)s')) # cls.logger.addHandler(sh) # # @classmethod # def get_cirque_logger(cls, name=None): # name = 'cirque' if not name else 'cirque.{}'.format(name) # return logging.getLogger(name) , which may contain function names, class names, or code. Output only the next line.
def get_docker_run_args(self, dockernode):
Based on the snippet: <|code_start|> node_id, petition_id, daemons=['wpantund', 'otbr-agent'], rcp=False): self.thread_endpoint = ThreadSimPipe(node_id, petition_id, rcp) self.thread_endpoint.open() self.logger = CirqueLog.get_cirque_logger(self.__class__.__name__) self.daemons = daemons for daemon in daemons: if daemon not in {'wpantund', 'otbr-agent'}: self.logger.warning( 'using unkown thread daemon mode: {}'.format(daemon)) @property def name(self): return 'Thread' def get_docker_run_args(self, dockernode): return { 'devices': [ '{}:/dev/ttyUSB0'.format(self.thread_endpoint.pipe_path_for_user) ], 'volumes': [ '{}:/dev/ttyUSB0'.format(self.thread_endpoint.pipe_path_for_user) ], 'sysctls': { 'net.ipv6.conf.all.disable_ipv6': 0, 'net.ipv4.conf.all.forwarding': 1, 'net.ipv6.conf.all.forwarding': 1, }, <|code_end|> , predict the immediate next line with the help of imports: from cirque.capabilities.basecapability import BaseCapability from cirque.connectivity.threadsimpipe import ThreadSimPipe from cirque.common.cirquelog import CirqueLog and context (classes, functions, sometimes code) from other files: # Path: cirque/capabilities/basecapability.py # class BaseCapability: # # @property # def name(self): # return '' # # def get_docker_run_args(self, docker_node): # return {} # # def enable_capability(self, docker_node): # pass # # def disable_capability(self, docker_node): # pass # # @property # def description(self): # return {} # # Path: cirque/connectivity/threadsimpipe.py # class ThreadSimPipe: # __next_petition_id = 0 # __THREAD_GROUP_SIZE = 34 # __petition_mutex = Lock() # # @classmethod # def get_next_petition(cls): # with cls.__petition_mutex: # cls.__next_petition_id += 1 # return cls.__next_petition_id # # def __init__(self, node_id, petition_id=0, rcp=False): # self._socat_pipe = SocatPipePair() # self.pipe_path_for_user = None # self.pipe_path_for_ncp = None # self.node_id = node_id # self.radio_fd = None # self.radio_process = None # self.petition_id = petition_id # if rcp: # self.radio_command = 'ot-rcp' # else: # self.radio_command = 'ot-ncp-ftd' # # def open(self): # self._socat_pipe.open() # self.pipe_path_for_user = self._socat_pipe.pipe0 # self.pipe_path_for_ncp = self._socat_pipe.pipe1 # self.radio_fd = os.open(self.pipe_path_for_ncp, os.O_RDWR) # env = os.environ # env['PORT_OFFSET'] = str(self.petition_id * self.__THREAD_GROUP_SIZE) # self.radio_process = subprocess.Popen( # [self.radio_command, '{}'.format(self.node_id)], # env=env, # stdout=self.radio_fd, # stdin=self.radio_fd) # # def close(self): # if self.radio_fd is not None: # os.close(self.radio_fd) # self.radio_fd = None # if self.radio_process is not None: # self.radio_process.terminate() # self.radio_process = None # if self._socat_pipe is not None: # self._socat_pipe.close() # self._socat_pipe = None # if os.path.exists('./tmp'): # shutil.rmtree('./tmp') # # def __del__(self): # self.close() # # Path: cirque/common/cirquelog.py # class CirqueLog: # # logger = None # # @classmethod # def setup_cirque_logger(cls, level=logging.INFO): # if cls.logger: # return # cls.logger = logging.getLogger('cirque') # cls.logger.setLevel(level) # sh = logging.StreamHandler() # sh.setFormatter( # logging.Formatter('%(asctime)s [%(name)s] %(levelname)s %(message)s')) # cls.logger.addHandler(sh) # # @classmethod # def get_cirque_logger(cls, name=None): # name = 'cirque' if not name else 'cirque.{}'.format(name) # return logging.getLogger(name) . Output only the next line.
'privileged': True,
Continue the code snippet: <|code_start|># Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class DockerNetworkCapability(BaseCapability): def __init__(self, network_name, network_type): self.network_name = network_name self.network_type = network_type <|code_end|> . Use current file imports: from cirque.capabilities.basecapability import BaseCapability and context (classes, functions, or code) from other files: # Path: cirque/capabilities/basecapability.py # class BaseCapability: # # @property # def name(self): # return '' # # def get_docker_run_args(self, docker_node): # return {} # # def enable_capability(self, docker_node): # pass # # def disable_capability(self, docker_node): # pass # # @property # def description(self): # return {} . Output only the next line.
@property
Using the snippet: <|code_start|> self.logger.error('Fail to setup ipv6 external access in ip6tables') def __inspect_network_properties(self): ret = host_run(self.logger, ['docker', 'network', 'inspect', self.__name]) if ret.returncode != 0: self.logger.error('Failed to inspect home lan %s' % self.__name) return network_info = json.loads(ret.stdout.decode()) if not network_info: self.logger.error('Failed to inspect home lan %s' % self.__name) return network_configs = network_info[0]['IPAM']['Config'] if 'ipv6' not in self.__name and len(network_configs) != 1: self.logger.error('Unexpected network behavior on home lan %s' % self.__name) self.subnet = network_configs[0]['Subnet'] self.gateway = network_configs[0]['Gateway'] def close(self): if not self.subnet: return cmd = ['docker', 'network', 'rm', self.__name] if host_run(self.logger, cmd).returncode != 0: self.logger.error('Failed to remove home lan %s', self.__name) if self.__ipv6: self.__disable_ipv6_external_access() if all(nwk not in self.__name for nwk in ('ipv6', 'ipvlan')): manipulate_iptable_src_dst_rule( self.logger, self.subnet, self.subnet, 'DROP', add=False) manipulate_iptable_src_dst_rule( <|code_end|> , determine the next line of code. You have imports: import ipaddress import json from cirque.common.cirquelog import CirqueLog from cirque.common.utils import host_run, manipulate_iptable_src_dst_rule and context (class names, function names, or code) available: # Path: cirque/common/cirquelog.py # class CirqueLog: # # logger = None # # @classmethod # def setup_cirque_logger(cls, level=logging.INFO): # if cls.logger: # return # cls.logger = logging.getLogger('cirque') # cls.logger.setLevel(level) # sh = logging.StreamHandler() # sh.setFormatter( # logging.Formatter('%(asctime)s [%(name)s] %(levelname)s %(message)s')) # cls.logger.addHandler(sh) # # @classmethod # def get_cirque_logger(cls, name=None): # name = 'cirque' if not name else 'cirque.{}'.format(name) # return logging.getLogger(name) # # Path: cirque/common/utils.py # def host_run(logger, # command, # namespace=None, # stdin=None, # stdout=subprocess.PIPE, # stderr=subprocess.PIPE): # if not isinstance(command, (list, str)): # logger.error( # 'unable to parse desired commands..Supporting only list or str!') # return -1 # exec_command = ' '.join(command) if isinstance(command, list) else command # # logger.debug('CMD RUN: {}'.format(exec_command)) # # if namespace and 'ip netns exec' not in exec_command: # exec_command = 'ip netns exec {} '.format(namespace) + exec_command # # process = None # for command in exec_command.split('|'): # stdin = process.stdout if process else None # process = subprocess.Popen( # shlex.split(command), stdin=stdin, stdout=stdout, stderr=stderr) # stdout, stderr = process.communicate() # returncode = process.returncode # logger.debug('CMD RESULT: \n' # 'ReturnCode: {},\nStdout: {},\nStdin: {}'.format( # returncode, stdout, stderr)) # # return Return(returncode, stdout, stderr) # # def manipulate_iptable_src_dst_rule(logger, src, dst, action, add=True): # chain = 'DOCKER-USER' # manipulate_action = '-I' if add else '-D' # ret = host_run(logger, 'iptables -L DOCKER-USER') # if b'No chain/target/match by that name' in ret.stderr: # chain = 'INPUT' # cmd = [ # 'iptables', manipulate_action, chain, '-s', src, '-d', dst, '-j', action # ] # ret = host_run(logger, cmd) # if ret.returncode != 0: # logger.error('Failed to add iptables rule %s', ' '.join(cmd)) . Output only the next line.
self.logger, self.gateway, self.subnet, 'ACCEPT', add=False)
Based on the snippet: <|code_start|> ret = host_run(self.logger, ['docker', 'network', 'inspect', self.__name]) if ret.returncode != 0: self.logger.error('Failed to inspect home lan %s' % self.__name) return network_info = json.loads(ret.stdout.decode()) if not network_info: self.logger.error('Failed to inspect home lan %s' % self.__name) return network_configs = network_info[0]['IPAM']['Config'] if 'ipv6' not in self.__name and len(network_configs) != 1: self.logger.error('Unexpected network behavior on home lan %s' % self.__name) self.subnet = network_configs[0]['Subnet'] self.gateway = network_configs[0]['Gateway'] def close(self): if not self.subnet: return cmd = ['docker', 'network', 'rm', self.__name] if host_run(self.logger, cmd).returncode != 0: self.logger.error('Failed to remove home lan %s', self.__name) if self.__ipv6: self.__disable_ipv6_external_access() if all(nwk not in self.__name for nwk in ('ipv6', 'ipvlan')): manipulate_iptable_src_dst_rule( self.logger, self.subnet, self.subnet, 'DROP', add=False) manipulate_iptable_src_dst_rule( self.logger, self.gateway, self.subnet, 'ACCEPT', add=False) manipulate_iptable_src_dst_rule( self.logger, self.subnet, self.gateway, 'ACCEPT', add=False) <|code_end|> , predict the immediate next line with the help of imports: import ipaddress import json from cirque.common.cirquelog import CirqueLog from cirque.common.utils import host_run, manipulate_iptable_src_dst_rule and context (classes, functions, sometimes code) from other files: # Path: cirque/common/cirquelog.py # class CirqueLog: # # logger = None # # @classmethod # def setup_cirque_logger(cls, level=logging.INFO): # if cls.logger: # return # cls.logger = logging.getLogger('cirque') # cls.logger.setLevel(level) # sh = logging.StreamHandler() # sh.setFormatter( # logging.Formatter('%(asctime)s [%(name)s] %(levelname)s %(message)s')) # cls.logger.addHandler(sh) # # @classmethod # def get_cirque_logger(cls, name=None): # name = 'cirque' if not name else 'cirque.{}'.format(name) # return logging.getLogger(name) # # Path: cirque/common/utils.py # def host_run(logger, # command, # namespace=None, # stdin=None, # stdout=subprocess.PIPE, # stderr=subprocess.PIPE): # if not isinstance(command, (list, str)): # logger.error( # 'unable to parse desired commands..Supporting only list or str!') # return -1 # exec_command = ' '.join(command) if isinstance(command, list) else command # # logger.debug('CMD RUN: {}'.format(exec_command)) # # if namespace and 'ip netns exec' not in exec_command: # exec_command = 'ip netns exec {} '.format(namespace) + exec_command # # process = None # for command in exec_command.split('|'): # stdin = process.stdout if process else None # process = subprocess.Popen( # shlex.split(command), stdin=stdin, stdout=stdout, stderr=stderr) # stdout, stderr = process.communicate() # returncode = process.returncode # logger.debug('CMD RESULT: \n' # 'ReturnCode: {},\nStdout: {},\nStdin: {}'.format( # returncode, stdout, stderr)) # # return Return(returncode, stdout, stderr) # # def manipulate_iptable_src_dst_rule(logger, src, dst, action, add=True): # chain = 'DOCKER-USER' # manipulate_action = '-I' if add else '-D' # ret = host_run(logger, 'iptables -L DOCKER-USER') # if b'No chain/target/match by that name' in ret.stderr: # chain = 'INPUT' # cmd = [ # 'iptables', manipulate_action, chain, '-s', src, '-d', dst, '-j', action # ] # ret = host_run(logger, cmd) # if ret.returncode != 0: # logger.error('Failed to add iptables rule %s', ' '.join(cmd)) . Output only the next line.
self.gateway = None
Predict the next line for this snippet: <|code_start|> def __init__(self, name, internal=False, ipv6=False): self.logger = CirqueLog.get_cirque_logger('lan_{}'.format(name)) self.__name = name self.__internal = internal self.__ipv6 = ipv6 self.subnet = None self.gateway = None if 'ipvlan' in self.__name: self.__create_ipvlan_network() else: self.__create_docker_network() # bypass disable mutual access for ipv4 # in ipv6 feature. if 'ipv6' not in self.__name: self.__disable_container_mutual_access() def __create_docker_network(self): # The docker-py library will add a weird route which disconnects # the host when creating networks. The `docker network inspect`isn't # supported neither so we use bash commands directly. cmd = ['docker', 'network', 'create', self.__name] if self.__internal: cmd.append('--internal') elif self.__ipv6: cmd.append('--subnet="{}"'.format(IPV6_SUBNET)) cmd.append('--gateway="{}"'.format(IPV6_GATEWAY)) cmd.append('--ipv6') ret = host_run(self.logger, cmd) if ret.returncode != 0: self.logger.error('Failed to create home lan %s', self.__name) <|code_end|> with the help of current file imports: import ipaddress import json from cirque.common.cirquelog import CirqueLog from cirque.common.utils import host_run, manipulate_iptable_src_dst_rule and context from other files: # Path: cirque/common/cirquelog.py # class CirqueLog: # # logger = None # # @classmethod # def setup_cirque_logger(cls, level=logging.INFO): # if cls.logger: # return # cls.logger = logging.getLogger('cirque') # cls.logger.setLevel(level) # sh = logging.StreamHandler() # sh.setFormatter( # logging.Formatter('%(asctime)s [%(name)s] %(levelname)s %(message)s')) # cls.logger.addHandler(sh) # # @classmethod # def get_cirque_logger(cls, name=None): # name = 'cirque' if not name else 'cirque.{}'.format(name) # return logging.getLogger(name) # # Path: cirque/common/utils.py # def host_run(logger, # command, # namespace=None, # stdin=None, # stdout=subprocess.PIPE, # stderr=subprocess.PIPE): # if not isinstance(command, (list, str)): # logger.error( # 'unable to parse desired commands..Supporting only list or str!') # return -1 # exec_command = ' '.join(command) if isinstance(command, list) else command # # logger.debug('CMD RUN: {}'.format(exec_command)) # # if namespace and 'ip netns exec' not in exec_command: # exec_command = 'ip netns exec {} '.format(namespace) + exec_command # # process = None # for command in exec_command.split('|'): # stdin = process.stdout if process else None # process = subprocess.Popen( # shlex.split(command), stdin=stdin, stdout=stdout, stderr=stderr) # stdout, stderr = process.communicate() # returncode = process.returncode # logger.debug('CMD RESULT: \n' # 'ReturnCode: {},\nStdout: {},\nStdin: {}'.format( # returncode, stdout, stderr)) # # return Return(returncode, stdout, stderr) # # def manipulate_iptable_src_dst_rule(logger, src, dst, action, add=True): # chain = 'DOCKER-USER' # manipulate_action = '-I' if add else '-D' # ret = host_run(logger, 'iptables -L DOCKER-USER') # if b'No chain/target/match by that name' in ret.stderr: # chain = 'INPUT' # cmd = [ # 'iptables', manipulate_action, chain, '-s', src, '-d', dst, '-j', action # ] # ret = host_run(logger, cmd) # if ret.returncode != 0: # logger.error('Failed to add iptables rule %s', ' '.join(cmd)) , which may contain function names, class names, or code. Output only the next line.
if self.__ipv6:
Predict the next line after this snippet: <|code_start|># Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class InteractiveCapability(BaseCapability): def __init__(self): pass @property <|code_end|> using the current file's imports: from cirque.capabilities.basecapability import BaseCapability and any relevant context from other files: # Path: cirque/capabilities/basecapability.py # class BaseCapability: # # @property # def name(self): # return '' # # def get_docker_run_args(self, docker_node): # return {} # # def enable_capability(self, docker_node): # pass # # def disable_capability(self, docker_node): # pass # # @property # def description(self): # return {} . Output only the next line.
def name(self):
Next line prediction: <|code_start|> service_pb2.ListCirqueHomeDevicesRequest(home_id=home_id)) device_ids = [ device.device_id for device in devices.devices if device.device_specification.device_type != 'wifi_ap' ] ssid, psk = [(device.device_description.ssid, device.device_description.psk) for device in devices.devices if device.device_specification.device_type == 'wifi_ap'][0] self.logger.info('\nwifi ap ssid: {}, psk: {}'.format(ssid, psk)) for device_id in device_ids: self.logger.info('\ndevice: {}\n connecting to desired ssid: {}'.format( device_id, ssid)) write_psk_to_wpa_supplicant_config(self.logger, self.stub, home_id, device_id, ssid, psk) kill_existing_wpa_supplicant(self.logger, self.stub, home_id, device_id) start_wpa_supplicant(self.logger, self.stub, home_id, device_id) time.sleep(5) def test_006_device_connectivity(self): home_id = self.stub.ListCirqueHomes( service_pb2.ListCirqueHomesRequest()).home_id[0] <|code_end|> . Use current file imports: (import logging import unittest import os import re import time import grpc import cirque.proto.capability_pb2 as capability_pb2 import cirque.proto.device_pb2 as device_pb2 import cirque.proto.service_pb2 as service_pb2 import cirque.proto.service_pb2_grpc as service_pb2_grpc from google.rpc import code_pb2, status_pb2 from cirque.proto.device_pb2 import DeviceSpecification from cirque.common.cirquelog import CirqueLog from cirque.common.utils import sleep_time from cirque.proto.capability_pb2 import (WeaveCapability, ThreadCapability, WiFiCapability, XvncCapability, InteractiveCapability, LanAccessCapability)) and context including class names, function names, or small code snippets from other files: # Path: cirque/common/cirquelog.py # class CirqueLog: # # logger = None # # @classmethod # def setup_cirque_logger(cls, level=logging.INFO): # if cls.logger: # return # cls.logger = logging.getLogger('cirque') # cls.logger.setLevel(level) # sh = logging.StreamHandler() # sh.setFormatter( # logging.Formatter('%(asctime)s [%(name)s] %(levelname)s %(message)s')) # cls.logger.addHandler(sh) # # @classmethod # def get_cirque_logger(cls, name=None): # name = 'cirque' if not name else 'cirque.{}'.format(name) # return logging.getLogger(name) # # Path: cirque/common/utils.py # def sleep_time(logger, seconds, reason=None): # if reason: # reason = 'for ' + reason # logger.debug('sleeps {}s {}'.format(seconds, reason)) # time.sleep(seconds) . Output only the next line.
devices = self.stub.ListCirqueHomeDevices(
Given the code snippet: <|code_start|># Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. def client_sample(weave_cert_path): CirqueLog.setup_cirque_logger() logger = CirqueLog.get_cirque_logger() with grpc.insecure_channel('localhost:50051') as channel: stub = service_pb2_grpc.CirqueServiceStub(channel) home_id = stub.CreateCirqueHome( service_pb2.CreateCirqueHomeRequest()).home_id mount_capability = MountCapability() mount_capability.mount_pairs.append( MountPair( <|code_end|> , generate the next line using the imports in this file: import argparse import time import logging import os import grpc import cirque.proto.capability_pb2 as capability_pb2 import cirque.proto.device_pb2 as device_pb2 import cirque.proto.service_pb2_grpc as service_pb2_grpc import cirque.proto.service_pb2 as service_pb2 from google.rpc import code_pb2, status_pb2 from cirque.proto.device_pb2 import DeviceSpecification from cirque.common.cirquelog import CirqueLog from cirque.common.utils import sleep_time from cirque.proto.capability_pb2 import (WeaveCapability, ThreadCapability, WiFiCapability, XvncCapability, InteractiveCapability, LanAccessCapability, MountPair, MountCapability, TrafficControlCapability) and context (functions, classes, or occasionally code) from other files: # Path: cirque/common/cirquelog.py # class CirqueLog: # # logger = None # # @classmethod # def setup_cirque_logger(cls, level=logging.INFO): # if cls.logger: # return # cls.logger = logging.getLogger('cirque') # cls.logger.setLevel(level) # sh = logging.StreamHandler() # sh.setFormatter( # logging.Formatter('%(asctime)s [%(name)s] %(levelname)s %(message)s')) # cls.logger.addHandler(sh) # # @classmethod # def get_cirque_logger(cls, name=None): # name = 'cirque' if not name else 'cirque.{}'.format(name) # return logging.getLogger(name) # # Path: cirque/common/utils.py # def sleep_time(logger, seconds, reason=None): # if reason: # reason = 'for ' + reason # logger.debug('sleeps {}s {}'.format(seconds, reason)) # time.sleep(seconds) . Output only the next line.
host_path=os.path.abspath(os.path.relpath(__file__)),
Predict the next line after this snippet: <|code_start|> mount_capability = MountCapability() mount_capability.mount_pairs.append( MountPair( host_path=os.path.abspath(os.path.relpath(__file__)), target_path='/tmp/test')) device_0_id = stub.CreateCirqueDevice( service_pb2.CreateCirqueDeviceRequest( home_id=home_id, specification=device_pb2.DeviceSpecification( device_type='test', base_image='sdk_border_router', weave_capability=WeaveCapability( weave_certificate_path=weave_cert_path), thread_capability=ThreadCapability(), wifi_capability=WiFiCapability(), xvnc_capability=XvncCapability(localhost=True), mount_capability=mount_capability))).device.device_id device_1_id = stub.CreateCirqueDevice( service_pb2.CreateCirqueDeviceRequest( home_id=home_id, specification=device_pb2.DeviceSpecification( device_type='mobile', base_image='mobile_node_image', interactive_capability=InteractiveCapability(), lan_access_capability=LanAccessCapability(), ))).device.device_id device_info = stub.QueryCirqueDevice( service_pb2.QueryCirqueDeviceRequest( home_id=home_id, device_id=device_1_id)) logger.info(device_info) <|code_end|> using the current file's imports: import argparse import time import logging import os import grpc import cirque.proto.capability_pb2 as capability_pb2 import cirque.proto.device_pb2 as device_pb2 import cirque.proto.service_pb2_grpc as service_pb2_grpc import cirque.proto.service_pb2 as service_pb2 from google.rpc import code_pb2, status_pb2 from cirque.proto.device_pb2 import DeviceSpecification from cirque.common.cirquelog import CirqueLog from cirque.common.utils import sleep_time from cirque.proto.capability_pb2 import (WeaveCapability, ThreadCapability, WiFiCapability, XvncCapability, InteractiveCapability, LanAccessCapability, MountPair, MountCapability, TrafficControlCapability) and any relevant context from other files: # Path: cirque/common/cirquelog.py # class CirqueLog: # # logger = None # # @classmethod # def setup_cirque_logger(cls, level=logging.INFO): # if cls.logger: # return # cls.logger = logging.getLogger('cirque') # cls.logger.setLevel(level) # sh = logging.StreamHandler() # sh.setFormatter( # logging.Formatter('%(asctime)s [%(name)s] %(levelname)s %(message)s')) # cls.logger.addHandler(sh) # # @classmethod # def get_cirque_logger(cls, name=None): # name = 'cirque' if not name else 'cirque.{}'.format(name) # return logging.getLogger(name) # # Path: cirque/common/utils.py # def sleep_time(logger, seconds, reason=None): # if reason: # reason = 'for ' + reason # logger.debug('sleeps {}s {}'.format(seconds, reason)) # time.sleep(seconds) . Output only the next line.
logger.info('Waiting for device to fully launch')
Next line prediction: <|code_start|> len(os.listdir(self.X_SOCKET_PATH)) == 0: return 0 x_server_ids = glob.glob(os.path.join(self.X_SOCKET_PATH, 'X*')) x_server_ids = [int(os.path.basename(f)[1:]) for f in x_server_ids] return max(x_server_ids) + 1 @property def name(self): return 'Xvnc' @property def description(self): return { 'localhost': self.localhost, 'display_id': self.__display_id, } def get_docker_run_args(self, dockernode): return { 'environment': ['DISPLAY=:{}'.format(self.__docker_display_id)], 'volumes': [ '{}/X{}:{}/X{}'.format(self.X_SOCKET_PATH, self.__display_id, self.X_SOCKET_PATH, self.__docker_display_id) ] } def enable_capability(self, docker_node): pass def disable_capability(self, docker_node): <|code_end|> . Use current file imports: (import os import glob import subprocess from threading import Lock from cirque.capabilities.basecapability import BaseCapability) and context including class names, function names, or small code snippets from other files: # Path: cirque/capabilities/basecapability.py # class BaseCapability: # # @property # def name(self): # return '' # # def get_docker_run_args(self, docker_node): # return {} # # def enable_capability(self, docker_node): # pass # # def disable_capability(self, docker_node): # pass # # @property # def description(self): # return {} . Output only the next line.
if self.__xvnc_process:
Predict the next line for this snippet: <|code_start|># # 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 WiFiCapability(BaseCapability): DEFAULT_RADIOS = 16 RUNTIME_NAMESPACE = "/var/run/netns" def __init__(self): self.logger = CirqueLog.get_cirque_logger(self.__class__.__name__) @property def name(self): return "WiFi" def get_docker_run_args(self, docker_node): return { "privileged": True, } def enable_capability(self, docker_node): if not WiFiCapability.is_mac80211_hwsim_loaded(): WiFiCapability.load_kernel_mac80211_hwsim() <|code_end|> with the help of current file imports: import os import time import cirque.common.utils as utils from subprocess import PIPE from pyroute2 import NetNS from cirque.capabilities.basecapability import BaseCapability from cirque.common.cirquelog import CirqueLog from cirque.common.exceptions import ( ConnectivityError, ContainerExecError, IpNetnsExecError, LoadKernelError, NameSpaceOperatingError, PHYDeviceError, ) and context from other files: # Path: cirque/capabilities/basecapability.py # class BaseCapability: # # @property # def name(self): # return '' # # def get_docker_run_args(self, docker_node): # return {} # # def enable_capability(self, docker_node): # pass # # def disable_capability(self, docker_node): # pass # # @property # def description(self): # return {} # # Path: cirque/common/cirquelog.py # class CirqueLog: # # logger = None # # @classmethod # def setup_cirque_logger(cls, level=logging.INFO): # if cls.logger: # return # cls.logger = logging.getLogger('cirque') # cls.logger.setLevel(level) # sh = logging.StreamHandler() # sh.setFormatter( # logging.Formatter('%(asctime)s [%(name)s] %(levelname)s %(message)s')) # cls.logger.addHandler(sh) # # @classmethod # def get_cirque_logger(cls, name=None): # name = 'cirque' if not name else 'cirque.{}'.format(name) # return logging.getLogger(name) # # Path: cirque/common/exceptions.py # class ConnectivityError(BaseException): # pass # # class ContainerExecError(BaseException): # pass # # class IpNetnsExecError(BaseException): # pass # # class LoadKernelError(BaseException): # pass # # class NameSpaceOperatingError(BaseException): # pass # # class PHYDeviceError(BaseException): # pass , which may contain function names, class names, or code. Output only the next line.
try:
Here is a snippet: <|code_start|> commands = [ "ip addr flush dev wlan0", "ip link set wlan0 down", "ip link set wlan0 name {}".format(docker_node.wlan_interface), ] for command in commands: ret = utils.netns_run(docker_node.logger, command, docker_node.name) if ret.returncode != 0: raise IpNetnsExecError("Error: {} on command: {}".format( ret.stderr, command)) self.logger.debug("moving out {} device from namespace:{}".format( phy_device, docker_node.name)) ret = utils.netns_run(docker_node.logger, "iw phy {} set netns 1".format(phy_device), docker_node.name) if ret.returncode != 0: raise IpNetnsExecError( "Error: {} on removing {} out of namespace".format( ret.stderr, phy_device)) # del created namespace self.logger.debug("removing explored namespace: {}".format( docker_node.name)) ret = utils.host_run(docker_node.logger, "ip netns del {}".format(docker_node.name)) if ret.returncode != 0: raise NameSpaceOperatingError("Error: {} on delete netns: {}".format( ret.stderr, docker_node.name)) @staticmethod <|code_end|> . Write the next line using the current file imports: import os import time import cirque.common.utils as utils from subprocess import PIPE from pyroute2 import NetNS from cirque.capabilities.basecapability import BaseCapability from cirque.common.cirquelog import CirqueLog from cirque.common.exceptions import ( ConnectivityError, ContainerExecError, IpNetnsExecError, LoadKernelError, NameSpaceOperatingError, PHYDeviceError, ) and context from other files: # Path: cirque/capabilities/basecapability.py # class BaseCapability: # # @property # def name(self): # return '' # # def get_docker_run_args(self, docker_node): # return {} # # def enable_capability(self, docker_node): # pass # # def disable_capability(self, docker_node): # pass # # @property # def description(self): # return {} # # Path: cirque/common/cirquelog.py # class CirqueLog: # # logger = None # # @classmethod # def setup_cirque_logger(cls, level=logging.INFO): # if cls.logger: # return # cls.logger = logging.getLogger('cirque') # cls.logger.setLevel(level) # sh = logging.StreamHandler() # sh.setFormatter( # logging.Formatter('%(asctime)s [%(name)s] %(levelname)s %(message)s')) # cls.logger.addHandler(sh) # # @classmethod # def get_cirque_logger(cls, name=None): # name = 'cirque' if not name else 'cirque.{}'.format(name) # return logging.getLogger(name) # # Path: cirque/common/exceptions.py # class ConnectivityError(BaseException): # pass # # class ContainerExecError(BaseException): # pass # # class IpNetnsExecError(BaseException): # pass # # class LoadKernelError(BaseException): # pass # # class NameSpaceOperatingError(BaseException): # pass # # class PHYDeviceError(BaseException): # pass , which may include functions, classes, or code. Output only the next line.
def is_mac80211_hwsim_loaded():
Predict the next line after this snippet: <|code_start|> docker_node.wlan_interface = interface self.logger.info("container {}: phy device {} interface {}".format( docker_node.name, docker_node.wlan_phy_device, docker_node.wlan_interface)) def __phy_namespace_setup(self, docker_node): try: self.__mount_container_namespace_to_host(docker_node) self.__add_phy_device_to_container_namespace(docker_node) self.__bring_up_wifi_interface(docker_node) except Exception as e: docker_node.logger.exception("{!r}".format(e)) self.__phy_namespace_restore(docker_node) raise NameSpaceOperatingError("{!r}".format(e)) def start_wpa_supplicant_service(self, docker_node): command = "wpa_supplicant -B -i wlan0 \ -c /etc/wpa_supplicant/wpa_supplicant.conf \ -f /var/log/wpa_supplicant.log -t -dd" return docker_node.container.exec_run(command) def __mount_container_namespace_to_host(self, docker_node): if not os.path.isdir(self.RUNTIME_NAMESPACE): os.makedirs(self.RUNTIME_NAMESPACE) if not os.path.isdir(self.RUNTIME_NAMESPACE): raise RuntimeError("unable to create target folder: {}".format( self.RUNTIME_NAMESPACE)) pid = docker_node.get_container_pid() <|code_end|> using the current file's imports: import os import time import cirque.common.utils as utils from subprocess import PIPE from pyroute2 import NetNS from cirque.capabilities.basecapability import BaseCapability from cirque.common.cirquelog import CirqueLog from cirque.common.exceptions import ( ConnectivityError, ContainerExecError, IpNetnsExecError, LoadKernelError, NameSpaceOperatingError, PHYDeviceError, ) and any relevant context from other files: # Path: cirque/capabilities/basecapability.py # class BaseCapability: # # @property # def name(self): # return '' # # def get_docker_run_args(self, docker_node): # return {} # # def enable_capability(self, docker_node): # pass # # def disable_capability(self, docker_node): # pass # # @property # def description(self): # return {} # # Path: cirque/common/cirquelog.py # class CirqueLog: # # logger = None # # @classmethod # def setup_cirque_logger(cls, level=logging.INFO): # if cls.logger: # return # cls.logger = logging.getLogger('cirque') # cls.logger.setLevel(level) # sh = logging.StreamHandler() # sh.setFormatter( # logging.Formatter('%(asctime)s [%(name)s] %(levelname)s %(message)s')) # cls.logger.addHandler(sh) # # @classmethod # def get_cirque_logger(cls, name=None): # name = 'cirque' if not name else 'cirque.{}'.format(name) # return logging.getLogger(name) # # Path: cirque/common/exceptions.py # class ConnectivityError(BaseException): # pass # # class ContainerExecError(BaseException): # pass # # class IpNetnsExecError(BaseException): # pass # # class LoadKernelError(BaseException): # pass # # class NameSpaceOperatingError(BaseException): # pass # # class PHYDeviceError(BaseException): # pass . Output only the next line.
sym_src = "/proc/{}/ns/net".format(pid)
Given the following code snippet before the placeholder: <|code_start|> @property def name(self): return "WiFi" def get_docker_run_args(self, docker_node): return { "privileged": True, } def enable_capability(self, docker_node): if not WiFiCapability.is_mac80211_hwsim_loaded(): WiFiCapability.load_kernel_mac80211_hwsim() try: self.__get_available_phy_device(docker_node) self.__phy_namespace_setup(docker_node) if docker_node.type != "wifi_ap": self.start_wpa_supplicant_service(docker_node) except Exception as e: self.logger.exception("{!r}".format(e)) return -1 self.logger.info("Node: {} successfully enabled wifi capability".format( docker_node.name)) def disable_capability(self, docker_node): try: docker_node.container.exec_run("killall wpa_supplicant") self.__phy_namespace_restore(docker_node) except Exception as e: self.logger.exception("{!r}".format(e)) self.logger.info("Node: {} successfully disabled wifi capablility".format( <|code_end|> , predict the next line using imports from the current file: import os import time import cirque.common.utils as utils from subprocess import PIPE from pyroute2 import NetNS from cirque.capabilities.basecapability import BaseCapability from cirque.common.cirquelog import CirqueLog from cirque.common.exceptions import ( ConnectivityError, ContainerExecError, IpNetnsExecError, LoadKernelError, NameSpaceOperatingError, PHYDeviceError, ) and context including class names, function names, and sometimes code from other files: # Path: cirque/capabilities/basecapability.py # class BaseCapability: # # @property # def name(self): # return '' # # def get_docker_run_args(self, docker_node): # return {} # # def enable_capability(self, docker_node): # pass # # def disable_capability(self, docker_node): # pass # # @property # def description(self): # return {} # # Path: cirque/common/cirquelog.py # class CirqueLog: # # logger = None # # @classmethod # def setup_cirque_logger(cls, level=logging.INFO): # if cls.logger: # return # cls.logger = logging.getLogger('cirque') # cls.logger.setLevel(level) # sh = logging.StreamHandler() # sh.setFormatter( # logging.Formatter('%(asctime)s [%(name)s] %(levelname)s %(message)s')) # cls.logger.addHandler(sh) # # @classmethod # def get_cirque_logger(cls, name=None): # name = 'cirque' if not name else 'cirque.{}'.format(name) # return logging.getLogger(name) # # Path: cirque/common/exceptions.py # class ConnectivityError(BaseException): # pass # # class ContainerExecError(BaseException): # pass # # class IpNetnsExecError(BaseException): # pass # # class LoadKernelError(BaseException): # pass # # class NameSpaceOperatingError(BaseException): # pass # # class PHYDeviceError(BaseException): # pass . Output only the next line.
docker_node.name))
Predict the next line for this snippet: <|code_start|> devices = [(l1, l2.split()[-1]) for l1, l2 in zip(lines, lines[1:]) if l1.startswith("phy")] phy_device, interface = devices.pop() phy_device = "".join(phy_device.split("#")) docker_node.wlan_phy_device = phy_device docker_node.wlan_interface = interface self.logger.info("container {}: phy device {} interface {}".format( docker_node.name, docker_node.wlan_phy_device, docker_node.wlan_interface)) def __phy_namespace_setup(self, docker_node): try: self.__mount_container_namespace_to_host(docker_node) self.__add_phy_device_to_container_namespace(docker_node) self.__bring_up_wifi_interface(docker_node) except Exception as e: docker_node.logger.exception("{!r}".format(e)) self.__phy_namespace_restore(docker_node) raise NameSpaceOperatingError("{!r}".format(e)) def start_wpa_supplicant_service(self, docker_node): command = "wpa_supplicant -B -i wlan0 \ -c /etc/wpa_supplicant/wpa_supplicant.conf \ -f /var/log/wpa_supplicant.log -t -dd" return docker_node.container.exec_run(command) def __mount_container_namespace_to_host(self, docker_node): if not os.path.isdir(self.RUNTIME_NAMESPACE): <|code_end|> with the help of current file imports: import os import time import cirque.common.utils as utils from subprocess import PIPE from pyroute2 import NetNS from cirque.capabilities.basecapability import BaseCapability from cirque.common.cirquelog import CirqueLog from cirque.common.exceptions import ( ConnectivityError, ContainerExecError, IpNetnsExecError, LoadKernelError, NameSpaceOperatingError, PHYDeviceError, ) and context from other files: # Path: cirque/capabilities/basecapability.py # class BaseCapability: # # @property # def name(self): # return '' # # def get_docker_run_args(self, docker_node): # return {} # # def enable_capability(self, docker_node): # pass # # def disable_capability(self, docker_node): # pass # # @property # def description(self): # return {} # # Path: cirque/common/cirquelog.py # class CirqueLog: # # logger = None # # @classmethod # def setup_cirque_logger(cls, level=logging.INFO): # if cls.logger: # return # cls.logger = logging.getLogger('cirque') # cls.logger.setLevel(level) # sh = logging.StreamHandler() # sh.setFormatter( # logging.Formatter('%(asctime)s [%(name)s] %(levelname)s %(message)s')) # cls.logger.addHandler(sh) # # @classmethod # def get_cirque_logger(cls, name=None): # name = 'cirque' if not name else 'cirque.{}'.format(name) # return logging.getLogger(name) # # Path: cirque/common/exceptions.py # class ConnectivityError(BaseException): # pass # # class ContainerExecError(BaseException): # pass # # class IpNetnsExecError(BaseException): # pass # # class LoadKernelError(BaseException): # pass # # class NameSpaceOperatingError(BaseException): # pass # # class PHYDeviceError(BaseException): # pass , which may contain function names, class names, or code. Output only the next line.
os.makedirs(self.RUNTIME_NAMESPACE)
Next line prediction: <|code_start|># # 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 WiFiCapability(BaseCapability): DEFAULT_RADIOS = 16 RUNTIME_NAMESPACE = "/var/run/netns" def __init__(self): self.logger = CirqueLog.get_cirque_logger(self.__class__.__name__) @property def name(self): return "WiFi" def get_docker_run_args(self, docker_node): return { "privileged": True, } def enable_capability(self, docker_node): if not WiFiCapability.is_mac80211_hwsim_loaded(): WiFiCapability.load_kernel_mac80211_hwsim() <|code_end|> . Use current file imports: (import os import time import cirque.common.utils as utils from subprocess import PIPE from pyroute2 import NetNS from cirque.capabilities.basecapability import BaseCapability from cirque.common.cirquelog import CirqueLog from cirque.common.exceptions import ( ConnectivityError, ContainerExecError, IpNetnsExecError, LoadKernelError, NameSpaceOperatingError, PHYDeviceError, )) and context including class names, function names, or small code snippets from other files: # Path: cirque/capabilities/basecapability.py # class BaseCapability: # # @property # def name(self): # return '' # # def get_docker_run_args(self, docker_node): # return {} # # def enable_capability(self, docker_node): # pass # # def disable_capability(self, docker_node): # pass # # @property # def description(self): # return {} # # Path: cirque/common/cirquelog.py # class CirqueLog: # # logger = None # # @classmethod # def setup_cirque_logger(cls, level=logging.INFO): # if cls.logger: # return # cls.logger = logging.getLogger('cirque') # cls.logger.setLevel(level) # sh = logging.StreamHandler() # sh.setFormatter( # logging.Formatter('%(asctime)s [%(name)s] %(levelname)s %(message)s')) # cls.logger.addHandler(sh) # # @classmethod # def get_cirque_logger(cls, name=None): # name = 'cirque' if not name else 'cirque.{}'.format(name) # return logging.getLogger(name) # # Path: cirque/common/exceptions.py # class ConnectivityError(BaseException): # pass # # class ContainerExecError(BaseException): # pass # # class IpNetnsExecError(BaseException): # pass # # class LoadKernelError(BaseException): # pass # # class NameSpaceOperatingError(BaseException): # pass # # class PHYDeviceError(BaseException): # pass . Output only the next line.
try:
Next line prediction: <|code_start|> def type(self): return self.node_type @property def base_image(self): return self.image_name @property def description(self): inspection = self.inspect() network_info = inspection['NetworkSettings']['Networks'] if network_info: network_name = next(iter(network_info.keys())) description = { 'ipv4_addr': network_info[network_name]['IPAddress'], } if network_info[network_name].get('IPv6Gateway', None): description.update({ 'ipv6_addr': network_info[network_name]['GlobalIPv6Address'], }) for capability in self.capabilities: description.update(capability.description) return description def get_container_pid(self): if self.container is None: return None return self.inspect()['State']['Pid'] def get_device_log(self, tail='all'): <|code_end|> . Use current file imports: (from functools import reduce from cirque.common.cirquelog import CirqueLog from cirque.common.utils import sleep_time import docker) and context including class names, function names, or small code snippets from other files: # Path: cirque/common/cirquelog.py # class CirqueLog: # # logger = None # # @classmethod # def setup_cirque_logger(cls, level=logging.INFO): # if cls.logger: # return # cls.logger = logging.getLogger('cirque') # cls.logger.setLevel(level) # sh = logging.StreamHandler() # sh.setFormatter( # logging.Formatter('%(asctime)s [%(name)s] %(levelname)s %(message)s')) # cls.logger.addHandler(sh) # # @classmethod # def get_cirque_logger(cls, name=None): # name = 'cirque' if not name else 'cirque.{}'.format(name) # return logging.getLogger(name) # # Path: cirque/common/utils.py # def sleep_time(logger, seconds, reason=None): # if reason: # reason = 'for ' + reason # logger.debug('sleeps {}s {}'.format(seconds, reason)) # time.sleep(seconds) . Output only the next line.
if self.container is not None:
Given the following code snippet before the placeholder: <|code_start|> class TrafficControlCapability(BaseCapability): def __init__(self, latencyMs=0, loss=0): self.latencyMs = latencyMs self.loss = loss @property def name(self): return "TrafficControl" @property def description(self): return { "latency": self.latencyMs, "loss": self.loss, } def get_docker_run_args(self, dockernode): return {"cap_add": ["NET_ADMIN"]} def enable_capability(self, docker_node): command = [] if self.latencyMs > 0: command += ["delay", "{}ms".format(self.latencyMs)] if self.loss > 0: command += ["loss", "{}%".format(self.loss)] if command: docker_node.container.exec_run( " ".join(["tc", "qdisc", "add", "dev", "eth0", "root", "netem"] + <|code_end|> , predict the next line using imports from the current file: import os import glob import subprocess from threading import Lock from cirque.capabilities.basecapability import BaseCapability and context including class names, function names, and sometimes code from other files: # Path: cirque/capabilities/basecapability.py # class BaseCapability: # # @property # def name(self): # return '' # # def get_docker_run_args(self, docker_node): # return {} # # def enable_capability(self, docker_node): # pass # # def disable_capability(self, docker_node): # pass # # @property # def description(self): # return {} . Output only the next line.
command))
Predict the next line for this snippet: <|code_start|># Copyright 2016 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Log entries within the Google Cloud Logging API.""" # import officially supported proto definitions _GLOBAL_RESOURCE = Resource(type="global", labels={}) _LOGGER_TEMPLATE = re.compile( r""" projects/ # static prefix (?P<project>[^/]+) # initial letter, wordchars + hyphen /logs/ # static midfix <|code_end|> with the help of current file imports: import collections import json import re import google.cloud.audit.audit_log_pb2 # noqa: F401 import google.cloud.appengine_logging # noqa: F401 from google.protobuf.any_pb2 import Any from google.protobuf.json_format import MessageToDict from google.protobuf.json_format import Parse from google.cloud.logging_v2.resource import Resource from google.cloud._helpers import _name_from_project_path from google.cloud._helpers import _rfc3339_nanos_to_datetime from google.cloud._helpers import _datetime_to_rfc3339 from google.iam.v1.logging import audit_data_pb2 # noqa: F401 and context from other files: # Path: google/cloud/logging_v2/resource.py # class Resource(collections.namedtuple("Resource", "type labels")): # """A monitored resource identified by specifying values for all labels. # # Attributes: # type (str): The resource type name. # labels (dict): A mapping from label names to values for all labels # enumerated in the associated :class:`ResourceDescriptor`. # """ # # __slots__ = () # # @classmethod # def _from_dict(cls, info): # """Construct a resource object from the parsed JSON representation. # # Args: # info (dict): A ``dict`` parsed from the JSON wire-format representation. # # Returns: # Resource: A resource object. # """ # return cls(type=info["type"], labels=info.get("labels", {})) # # def _to_dict(self): # """Build a dictionary ready to be serialized to the JSON format. # # Returns: # dict: # A dict representation of the object that can be written to # the API. # """ # return {"type": self.type, "labels": self.labels} , which may contain function names, class names, or code. Output only the next line.
(?P<name>[^/]+) # initial letter, wordchars + allowed punc
Given the following code snippet before the placeholder: <|code_start|># Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. _GAE_SERVICE_ENV = "GAE_SERVICE" _GAE_VERSION_ENV = "GAE_VERSION" _GAE_INSTANCE_ENV = "GAE_INSTANCE" <|code_end|> , predict the next line using imports from the current file: import os from google.cloud.logging_v2.resource import Resource from google.cloud.logging_v2._helpers import retrieve_metadata_server and context including class names, function names, and sometimes code from other files: # Path: google/cloud/logging_v2/resource.py # class Resource(collections.namedtuple("Resource", "type labels")): # """A monitored resource identified by specifying values for all labels. # # Attributes: # type (str): The resource type name. # labels (dict): A mapping from label names to values for all labels # enumerated in the associated :class:`ResourceDescriptor`. # """ # # __slots__ = () # # @classmethod # def _from_dict(cls, info): # """Construct a resource object from the parsed JSON representation. # # Args: # info (dict): A ``dict`` parsed from the JSON wire-format representation. # # Returns: # Resource: A resource object. # """ # return cls(type=info["type"], labels=info.get("labels", {})) # # def _to_dict(self): # """Build a dictionary ready to be serialized to the JSON format. # # Returns: # dict: # A dict representation of the object that can be written to # the API. # """ # return {"type": self.type, "labels": self.labels} # # Path: google/cloud/logging_v2/_helpers.py # def retrieve_metadata_server(metadata_key, timeout=5): # """Retrieve the metadata key in the metadata server. # # See: https://cloud.google.com/compute/docs/storing-retrieving-metadata # # Args: # metadata_key (str): # Key of the metadata which will form the url. You can # also supply query parameters after the metadata key. # e.g. "tags?alt=json" # timeout (number): number of seconds to wait for the HTTP request # # Returns: # str: The value of the metadata key returned by the metadata server. # """ # url = METADATA_URL + metadata_key # # try: # response = requests.get(url, headers=METADATA_HEADERS, timeout=timeout) # # if response.status_code == requests.codes.ok: # return response.text # # except requests.exceptions.RequestException: # # Ignore the exception, connection failed means the attribute does not # # exist in the metadata server. # pass # # return None . Output only the next line.
_GAE_ENV_VARS = [_GAE_SERVICE_ENV, _GAE_VERSION_ENV, _GAE_INSTANCE_ENV]
Given the code snippet: <|code_start|># 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 TestCloudLoggingFilter(unittest.TestCase): PROJECT = "PROJECT" @staticmethod def _get_target_class(): return CloudLoggingFilter def _make_one(self, *args, **kw): return self._get_target_class()(*args, **kw) @staticmethod def create_app(): app = flask.Flask(__name__) @app.route("/") def index(): <|code_end|> , generate the next line using the imports in this file: import logging import unittest import mock import json import flask import logging import logging import logging import logging import logging import sys import io from unittest.mock import patch from google.cloud.logging_v2.handlers._monitored_resources import ( _FUNCTION_ENV_VARS, _GAE_ENV_VARS, ) from google.cloud.logging.handlers import CloudLoggingFilter from google.cloud.logging.handlers import CloudLoggingHandler from google.cloud.logging_v2.handlers._monitored_resources import ( _create_global_resource, ) from google.cloud.logging_v2.handlers.handlers import DEFAULT_LOGGER_NAME from google.cloud.logging import Resource from google.cloud.logging_v2.logger import _GLOBAL_RESOURCE from google.cloud.logging_v2.logger import _GLOBAL_RESOURCE from google.cloud.logging_v2.logger import _GLOBAL_RESOURCE from google.cloud.logging_v2.resource import Resource from google.cloud.logging_v2.logger import _GLOBAL_RESOURCE from google.cloud.logging_v2.logger import _GLOBAL_RESOURCE from google.cloud.logging_v2.logger import _GLOBAL_RESOURCE from google.cloud.logging_v2.logger import _GLOBAL_RESOURCE from google.cloud.logging_v2.logger import _GLOBAL_RESOURCE from google.cloud.logging_v2.handlers.handlers import _format_and_parse_message from google.cloud.logging_v2.handlers.handlers import _format_and_parse_message from google.cloud.logging_v2.handlers.handlers import _format_and_parse_message from google.cloud.logging_v2.handlers.handlers import _format_and_parse_message from google.cloud.logging_v2.handlers.handlers import _format_and_parse_message from google.cloud.logging_v2.handlers.handlers import _format_and_parse_message from google.cloud.logging_v2.handlers.handlers import _format_and_parse_message from google.cloud.logging_v2.handlers.handlers import _format_and_parse_message from google.cloud.logging_v2.handlers.handlers import _format_and_parse_message from google.cloud.logging_v2.handlers.handlers import _format_and_parse_message from google.cloud.logging_v2.handlers.handlers import _format_and_parse_message from google.cloud.logging_v2.handlers.handlers import _format_and_parse_message from google.cloud.logging.handlers import setup_logging and context (functions, classes, or occasionally code) from other files: # Path: google/cloud/logging_v2/handlers/_monitored_resources.py # _FUNCTION_ENV_VARS = [_FUNCTION_TARGET, _FUNCTION_SIGNATURE, _CLOUD_RUN_SERVICE_ID] # # _GAE_ENV_VARS = [_GAE_SERVICE_ENV, _GAE_VERSION_ENV, _GAE_INSTANCE_ENV] . Output only the next line.
return "test flask trace" # pragma: NO COVER
Given the code snippet: <|code_start|> pre_commit(AddNumberOneTimePreCommitCallable(numbers_list=numbers_list, number=3)) assert_equal(len(numbers_list), 0) assert_equal(len(numbers_list), 0) assert_equal(numbers_list, [1]) def test_pre_commit_should_called_with_the_right_order(self): data = [] def pre_commit_fn_a(): pre_commit(pre_commit_fn_c) data.append('a') def pre_commit_fn_b(): data.append('b') def pre_commit_fn_c(): data.append('c') with transaction.atomic(): pre_commit(pre_commit_fn_a) with transaction.atomic(): pre_commit(pre_commit_fn_b) assert_equal(data, ['a', 'b', 'c']) def test_chamber_atomic_should_ignore_errors(self): with assert_raises(RuntimeError): with smart_atomic(): <|code_end|> , generate the next line using the imports in this file: from django.test import TransactionTestCase from django.db import transaction from django.db.transaction import on_commit from chamber.utils.transaction import UniquePreCommitCallable, in_atomic_block, pre_commit, smart_atomic from test_chamber.models import TestSmartModel from germanium.tools import assert_equal, assert_raises, assert_true, assert_false and context (functions, classes, or occasionally code) from other files: # Path: chamber/utils/transaction.py # class UniquePreCommitCallable: # """ # One time callable class that is used for performing on success operations. # Handler is callable only once, but data of all calls are stored inside list (kwargs_list). # """ # # def __init__(self, **kwargs): # self.kwargs_list = (kwargs,) # # def join(self, callable): # """ # Joins two unique callable. # """ # self.kwargs_list += callable.kwargs_list # # def _get_unique_id(self): # """ # Callable instance hash is generated from class name and the return value of this method. # The method returns None by default, therefore the class init data doesn't have impact. # You should implement this method to distinguish callable according to its # input data (for example Django model instance) # :return: # """ # return None # # def __hash__(self): # return hash((self.__class__, self._get_unique_id())) # # def _get_kwargs(self): # return self.kwargs_list[-1] # # def __call__(self): # self.handle() # # def handle(self): # raise NotImplementedError # # def in_atomic_block(using=None): # """Check if connection is in atomic block""" # # connection = get_connection(using) # return connection.in_atomic_block # # def pre_commit(func, using=None): # connection = get_connection(using) # # if connection.in_atomic_block: # # Transaction in progress; save for execution on commit. # func_hash = hash(func) if isinstance(func, UniquePreCommitCallable) else None # if (func_hash is None # or func_hash not in {func_hash for sids, func_hash, func in connection.run_pre_commit}): # connection.run_pre_commit.append((set(connection.savepoint_ids), func_hash, func)) # # elif not connection.get_autocommit(): # raise TransactionManagementError('pre_commit() cannot be used in manual transaction management') # else: # # No transaction in progress and in autocommit mode; execute immediately. # func() # # def smart_atomic(using=None, savepoint=True, ignore_errors=None, reversion=True, reversion_using=None): # """ # Decorator and context manager that overrides django atomic decorator and automatically adds create revision. # The _atomic closure is required to achieve save ContextDecorator that nest more inner context decorator. # More here https://stackoverflow.com/questions/45589718/combine-two-context-managers-into-one # """ # # ignore_errors = () if ignore_errors is None else ignore_errors # # @contextmanager # def _atomic(using=None, savepoint=True, reversion=True, reversion_using=None): # try: # from reversion.revisions import create_revision # except ImportError: # reversion = False # # if not reversion: # @contextmanager # noqa: F811 # def create_revision(*args, **kwargs): # noqa: F811 # yield # # error = None # with transaction.atomic(using, savepoint), create_revision(using=reversion_using): # try: # yield # except ignore_errors as ex: # error = ex # # if error: # raise error # pylint: disable=E0702 # # if callable(using): # return _atomic(DEFAULT_DB_ALIAS, savepoint, reversion, reversion_using)(using) # else: # return _atomic(using, savepoint, reversion, reversion_using) . Output only the next line.
TestSmartModel.objects.create(name='test')
Based on the snippet: <|code_start|> __all__ = ( 'TransactionsTestCase', ) def add_number(numbers_list, number): numbers_list.append(number) class TransactionsTestCase(TransactionTestCase): <|code_end|> , predict the immediate next line with the help of imports: from django.test import TransactionTestCase from django.db import transaction from django.db.transaction import on_commit from chamber.utils.transaction import UniquePreCommitCallable, in_atomic_block, pre_commit, smart_atomic from test_chamber.models import TestSmartModel from germanium.tools import assert_equal, assert_raises, assert_true, assert_false and context (classes, functions, sometimes code) from other files: # Path: chamber/utils/transaction.py # class UniquePreCommitCallable: # """ # One time callable class that is used for performing on success operations. # Handler is callable only once, but data of all calls are stored inside list (kwargs_list). # """ # # def __init__(self, **kwargs): # self.kwargs_list = (kwargs,) # # def join(self, callable): # """ # Joins two unique callable. # """ # self.kwargs_list += callable.kwargs_list # # def _get_unique_id(self): # """ # Callable instance hash is generated from class name and the return value of this method. # The method returns None by default, therefore the class init data doesn't have impact. # You should implement this method to distinguish callable according to its # input data (for example Django model instance) # :return: # """ # return None # # def __hash__(self): # return hash((self.__class__, self._get_unique_id())) # # def _get_kwargs(self): # return self.kwargs_list[-1] # # def __call__(self): # self.handle() # # def handle(self): # raise NotImplementedError # # def in_atomic_block(using=None): # """Check if connection is in atomic block""" # # connection = get_connection(using) # return connection.in_atomic_block # # def pre_commit(func, using=None): # connection = get_connection(using) # # if connection.in_atomic_block: # # Transaction in progress; save for execution on commit. # func_hash = hash(func) if isinstance(func, UniquePreCommitCallable) else None # if (func_hash is None # or func_hash not in {func_hash for sids, func_hash, func in connection.run_pre_commit}): # connection.run_pre_commit.append((set(connection.savepoint_ids), func_hash, func)) # # elif not connection.get_autocommit(): # raise TransactionManagementError('pre_commit() cannot be used in manual transaction management') # else: # # No transaction in progress and in autocommit mode; execute immediately. # func() # # def smart_atomic(using=None, savepoint=True, ignore_errors=None, reversion=True, reversion_using=None): # """ # Decorator and context manager that overrides django atomic decorator and automatically adds create revision. # The _atomic closure is required to achieve save ContextDecorator that nest more inner context decorator. # More here https://stackoverflow.com/questions/45589718/combine-two-context-managers-into-one # """ # # ignore_errors = () if ignore_errors is None else ignore_errors # # @contextmanager # def _atomic(using=None, savepoint=True, reversion=True, reversion_using=None): # try: # from reversion.revisions import create_revision # except ImportError: # reversion = False # # if not reversion: # @contextmanager # noqa: F811 # def create_revision(*args, **kwargs): # noqa: F811 # yield # # error = None # with transaction.atomic(using, savepoint), create_revision(using=reversion_using): # try: # yield # except ignore_errors as ex: # error = ex # # if error: # raise error # pylint: disable=E0702 # # if callable(using): # return _atomic(DEFAULT_DB_ALIAS, savepoint, reversion, reversion_using)(using) # else: # return _atomic(using, savepoint, reversion, reversion_using) . Output only the next line.
def test_pre_commit_without_atomic_should_be_called_immediately(self):
Continue the code snippet: <|code_start|> class AddNumberOneTimePreCommitCallable(UniquePreCommitCallable): def handle(self): self.kwargs_list[-1]['numbers_list'].append(3) with transaction.atomic(): for i in range(5): pre_commit(AddNumberOneTimePreCommitCallable(numbers_list=numbers_list, number=i)) assert_equal(len(numbers_list), 0) assert_equal(numbers_list, [3]) def test_pre_commit_should_call_one_time_callable_only_once_for_not_failed_blocks(self): numbers_list = [] class AddNumberOneTimePreCommitCallable(UniquePreCommitCallable): def handle(self): for kwargs in self.kwargs_list: self.kwargs_list[-1]['numbers_list'].append(kwargs['number']) with transaction.atomic(): pre_commit(AddNumberOneTimePreCommitCallable(numbers_list=numbers_list, number=1)) with assert_raises(RuntimeError): with transaction.atomic(): pre_commit(AddNumberOneTimePreCommitCallable(numbers_list=numbers_list, number=2)) assert_equal(len(numbers_list), 0) raise RuntimeError <|code_end|> . Use current file imports: from django.test import TransactionTestCase from django.db import transaction from django.db.transaction import on_commit from chamber.utils.transaction import UniquePreCommitCallable, in_atomic_block, pre_commit, smart_atomic from test_chamber.models import TestSmartModel from germanium.tools import assert_equal, assert_raises, assert_true, assert_false and context (classes, functions, or code) from other files: # Path: chamber/utils/transaction.py # class UniquePreCommitCallable: # """ # One time callable class that is used for performing on success operations. # Handler is callable only once, but data of all calls are stored inside list (kwargs_list). # """ # # def __init__(self, **kwargs): # self.kwargs_list = (kwargs,) # # def join(self, callable): # """ # Joins two unique callable. # """ # self.kwargs_list += callable.kwargs_list # # def _get_unique_id(self): # """ # Callable instance hash is generated from class name and the return value of this method. # The method returns None by default, therefore the class init data doesn't have impact. # You should implement this method to distinguish callable according to its # input data (for example Django model instance) # :return: # """ # return None # # def __hash__(self): # return hash((self.__class__, self._get_unique_id())) # # def _get_kwargs(self): # return self.kwargs_list[-1] # # def __call__(self): # self.handle() # # def handle(self): # raise NotImplementedError # # def in_atomic_block(using=None): # """Check if connection is in atomic block""" # # connection = get_connection(using) # return connection.in_atomic_block # # def pre_commit(func, using=None): # connection = get_connection(using) # # if connection.in_atomic_block: # # Transaction in progress; save for execution on commit. # func_hash = hash(func) if isinstance(func, UniquePreCommitCallable) else None # if (func_hash is None # or func_hash not in {func_hash for sids, func_hash, func in connection.run_pre_commit}): # connection.run_pre_commit.append((set(connection.savepoint_ids), func_hash, func)) # # elif not connection.get_autocommit(): # raise TransactionManagementError('pre_commit() cannot be used in manual transaction management') # else: # # No transaction in progress and in autocommit mode; execute immediately. # func() # # def smart_atomic(using=None, savepoint=True, ignore_errors=None, reversion=True, reversion_using=None): # """ # Decorator and context manager that overrides django atomic decorator and automatically adds create revision. # The _atomic closure is required to achieve save ContextDecorator that nest more inner context decorator. # More here https://stackoverflow.com/questions/45589718/combine-two-context-managers-into-one # """ # # ignore_errors = () if ignore_errors is None else ignore_errors # # @contextmanager # def _atomic(using=None, savepoint=True, reversion=True, reversion_using=None): # try: # from reversion.revisions import create_revision # except ImportError: # reversion = False # # if not reversion: # @contextmanager # noqa: F811 # def create_revision(*args, **kwargs): # noqa: F811 # yield # # error = None # with transaction.atomic(using, savepoint), create_revision(using=reversion_using): # try: # yield # except ignore_errors as ex: # error = ex # # if error: # raise error # pylint: disable=E0702 # # if callable(using): # return _atomic(DEFAULT_DB_ALIAS, savepoint, reversion, reversion_using)(using) # else: # return _atomic(using, savepoint, reversion, reversion_using) . Output only the next line.
with transaction.atomic():
Next line prediction: <|code_start|> super().__init__(*args, **kwargs) self.placeholder = currency class PriceField(DecimalField): widget = PriceNumberInput def __init__(self, *args, **kwargs): currency = kwargs.pop('currency', ugettext('CZK')) kwargs.setdefault('max_digits', 10) kwargs.setdefault('decimal_places', 2) if 'widget' not in kwargs: kwargs['widget'] = PriceNumberInput(currency) super().__init__(*args, **kwargs) class RestrictedFileField(forms.FileField): def __init__(self, *args, **kwargs): max_upload_size = kwargs.pop('max_upload_size', settings.MAX_FILE_UPLOAD_SIZE) * 1024 * 1024 allowed_content_types = kwargs.pop('allowed_content_types', None) validators = tuple(kwargs.pop('validators', [])) + ( RestrictedFileValidator(max_upload_size), ) if allowed_content_types: validators += ( AllowedContentTypesByFilenameFileValidator(allowed_content_types), AllowedContentTypesByContentFileValidator(allowed_content_types), <|code_end|> . Use current file imports: (from django import forms from django.utils.translation import ugettext from chamber.config import settings from .validators import ( RestrictedFileValidator, AllowedContentTypesByFilenameFileValidator, AllowedContentTypesByContentFileValidator )) and context including class names, function names, or small code snippets from other files: # Path: chamber/config.py # DEFAULTS = { # 'MAX_FILE_UPLOAD_SIZE': 20, # 'MULTIDOMAINS_OVERTAKER_AUTH_COOKIE_NAME': None, # 'DEFAULT_IMAGE_ALLOWED_CONTENT_TYPES': {'image/jpeg', 'image/png', 'image/gif'}, # 'PRIVATE_S3_STORAGE_URL_EXPIRATION': 3600, # 'AWS_S3_ON': getattr(django_settings, 'AWS_S3_ON', False), # 'AWS_REGION': getattr(django_settings, 'AWS_REGION', None), # } # class Settings: # def __getattr__(self, attr): # # Path: chamber/forms/validators.py # class RestrictedFileValidator: # # def __init__(self, max_upload_size): # self.max_upload_size = max_upload_size # # def __call__(self, data): # if data.size > self.max_upload_size: # raise ValidationError( # ugettext('Please keep filesize under {max}. Current filesize {current}').format( # max=filesizeformat(self.max_upload_size), # current=filesizeformat(data.size) # ) # ) # else: # return data # # class AllowedContentTypesByFilenameFileValidator: # # def __init__(self, content_types): # self.content_types = content_types # # def __call__(self, data): # extension_mime_type = mimetypes.guess_type(data.name)[0] # # if extension_mime_type not in self.content_types: # raise ValidationError(ugettext('Extension of file name is not allowed')) # # return data # # class AllowedContentTypesByContentFileValidator: # # def __init__(self, content_types): # self.content_types = content_types # # def __call__(self, data): # data.open() # with magic.Magic(flags=magic.MAGIC_MIME_TYPE) as m: # mime_type = m.id_buffer(data.read(2048)) # data.seek(0) # if mime_type not in self.content_types: # raise ValidationError(ugettext('File content was evaluated as not supported file type')) # # return data . Output only the next line.
)
Here is a snippet: <|code_start|> attrs['min'] = self.min if self.max is not None: attrs['max'] = self.max return attrs class PriceNumberInput(forms.NumberInput): def __init__(self, currency, *args, **kwargs): super().__init__(*args, **kwargs) self.placeholder = currency class PriceField(DecimalField): widget = PriceNumberInput def __init__(self, *args, **kwargs): currency = kwargs.pop('currency', ugettext('CZK')) kwargs.setdefault('max_digits', 10) kwargs.setdefault('decimal_places', 2) if 'widget' not in kwargs: kwargs['widget'] = PriceNumberInput(currency) super().__init__(*args, **kwargs) class RestrictedFileField(forms.FileField): def __init__(self, *args, **kwargs): max_upload_size = kwargs.pop('max_upload_size', settings.MAX_FILE_UPLOAD_SIZE) * 1024 * 1024 <|code_end|> . Write the next line using the current file imports: from django import forms from django.utils.translation import ugettext from chamber.config import settings from .validators import ( RestrictedFileValidator, AllowedContentTypesByFilenameFileValidator, AllowedContentTypesByContentFileValidator ) and context from other files: # Path: chamber/config.py # DEFAULTS = { # 'MAX_FILE_UPLOAD_SIZE': 20, # 'MULTIDOMAINS_OVERTAKER_AUTH_COOKIE_NAME': None, # 'DEFAULT_IMAGE_ALLOWED_CONTENT_TYPES': {'image/jpeg', 'image/png', 'image/gif'}, # 'PRIVATE_S3_STORAGE_URL_EXPIRATION': 3600, # 'AWS_S3_ON': getattr(django_settings, 'AWS_S3_ON', False), # 'AWS_REGION': getattr(django_settings, 'AWS_REGION', None), # } # class Settings: # def __getattr__(self, attr): # # Path: chamber/forms/validators.py # class RestrictedFileValidator: # # def __init__(self, max_upload_size): # self.max_upload_size = max_upload_size # # def __call__(self, data): # if data.size > self.max_upload_size: # raise ValidationError( # ugettext('Please keep filesize under {max}. Current filesize {current}').format( # max=filesizeformat(self.max_upload_size), # current=filesizeformat(data.size) # ) # ) # else: # return data # # class AllowedContentTypesByFilenameFileValidator: # # def __init__(self, content_types): # self.content_types = content_types # # def __call__(self, data): # extension_mime_type = mimetypes.guess_type(data.name)[0] # # if extension_mime_type not in self.content_types: # raise ValidationError(ugettext('Extension of file name is not allowed')) # # return data # # class AllowedContentTypesByContentFileValidator: # # def __init__(self, content_types): # self.content_types = content_types # # def __call__(self, data): # data.open() # with magic.Magic(flags=magic.MAGIC_MIME_TYPE) as m: # mime_type = m.id_buffer(data.read(2048)) # data.seek(0) # if mime_type not in self.content_types: # raise ValidationError(ugettext('File content was evaluated as not supported file type')) # # return data , which may include functions, classes, or code. Output only the next line.
allowed_content_types = kwargs.pop('allowed_content_types', None)
Based on the snippet: <|code_start|> class DecimalField(forms.DecimalField): def __init__(self, *args, **kwargs): self.step = kwargs.pop('step', 'any') self.min = kwargs.pop('min', None) self.max = kwargs.pop('max', None) super().__init__(*args, **kwargs) def widget_attrs(self, widget): attrs = super().widget_attrs(widget) attrs['step'] = self.step if self.min is not None: attrs['min'] = self.min if self.max is not None: attrs['max'] = self.max return attrs class PriceNumberInput(forms.NumberInput): def __init__(self, currency, *args, **kwargs): super().__init__(*args, **kwargs) self.placeholder = currency <|code_end|> , predict the immediate next line with the help of imports: from django import forms from django.utils.translation import ugettext from chamber.config import settings from .validators import ( RestrictedFileValidator, AllowedContentTypesByFilenameFileValidator, AllowedContentTypesByContentFileValidator ) and context (classes, functions, sometimes code) from other files: # Path: chamber/config.py # DEFAULTS = { # 'MAX_FILE_UPLOAD_SIZE': 20, # 'MULTIDOMAINS_OVERTAKER_AUTH_COOKIE_NAME': None, # 'DEFAULT_IMAGE_ALLOWED_CONTENT_TYPES': {'image/jpeg', 'image/png', 'image/gif'}, # 'PRIVATE_S3_STORAGE_URL_EXPIRATION': 3600, # 'AWS_S3_ON': getattr(django_settings, 'AWS_S3_ON', False), # 'AWS_REGION': getattr(django_settings, 'AWS_REGION', None), # } # class Settings: # def __getattr__(self, attr): # # Path: chamber/forms/validators.py # class RestrictedFileValidator: # # def __init__(self, max_upload_size): # self.max_upload_size = max_upload_size # # def __call__(self, data): # if data.size > self.max_upload_size: # raise ValidationError( # ugettext('Please keep filesize under {max}. Current filesize {current}').format( # max=filesizeformat(self.max_upload_size), # current=filesizeformat(data.size) # ) # ) # else: # return data # # class AllowedContentTypesByFilenameFileValidator: # # def __init__(self, content_types): # self.content_types = content_types # # def __call__(self, data): # extension_mime_type = mimetypes.guess_type(data.name)[0] # # if extension_mime_type not in self.content_types: # raise ValidationError(ugettext('Extension of file name is not allowed')) # # return data # # class AllowedContentTypesByContentFileValidator: # # def __init__(self, content_types): # self.content_types = content_types # # def __call__(self, data): # data.open() # with magic.Magic(flags=magic.MAGIC_MIME_TYPE) as m: # mime_type = m.id_buffer(data.read(2048)) # data.seek(0) # if mime_type not in self.content_types: # raise ValidationError(ugettext('File content was evaluated as not supported file type')) # # return data . Output only the next line.
class PriceField(DecimalField):
Continue the code snippet: <|code_start|> class S3StorageTestCase(TestCase): TEST_DATA = ( ('Hello, this is str content.', b'Hello, this is str content.', True), (b'Hello, this is bytes content.', b'Hello, this is bytes content.', False), ) @data_provider(TEST_DATA) def test_s3storage_casts_content_to_bytes_if_needed(self, content, content_result, should_cast): file = ContentFile(content) result, casted = force_bytes_content(file) <|code_end|> . Use current file imports: from django.core.files.base import ContentFile from django.test import TestCase from chamber.storages.boto3 import force_bytes_content from germanium.decorators import data_provider and context (classes, functions, or code) from other files: # Path: chamber/storages/boto3.py # def force_bytes_content(content, blocksize=1024): # """Returns a tuple of content (file-like object) and bool indicating wheter the content has been casted or not""" # block = content.read(blocksize) # content.seek(0) # # if not isinstance(block, bytes): # _content = bytes( # content.read(), # 'utf-8' if not hasattr(content, 'encoding') or content.encoding is None else content.encoding, # ) # return ContentFile(_content), True # return content, False . Output only the next line.
casted_content = result.read()
Using the snippet: <|code_start|> def create_test_smart_model_handler(instance, **kwargs): TestSmartModel.objects.create(name='name') def create_test_fields_model_handler(instance, **kwargs): TestFieldsModel.objects.create() def create_test_dispatchers_model_handler(instance, **kwargs): <|code_end|> , determine the next line of code. You have imports: from chamber.models.handlers import InstanceOneTimePreCommitHandler from .models import TestSmartModel # NOQA from .models import TestFieldsModel # NOQA from .models import TestDispatchersModel # NOQA from .models import CSVRecord # NOQA from .models import TestOnDispatchModel and context (class names, function names, or code) available: # Path: chamber/models/handlers.py # class InstanceOneTimePreCommitHandler(PreCommitHandler): # """ # Use this class to create handler that will be unique per instance and will be called only once per instance. # """ # # def _handle(self, instance, **kwargs): # pre_commit(InstanceOneTimePreCommitHandlerCallable(self, instance), using=self.using) . Output only the next line.
TestDispatchersModel.objects.create()
Here is a snippet: <|code_start|> assert_equal(get_object_or_none(ShortcutsModel, name='test1'), obj) assert_is_none(get_object_or_none(ShortcutsModel, name='test3')) assert_is_none(get_object_or_none(ShortcutsModel, number='test3')) assert_is_none(get_object_or_none(ShortcutsModel, datetime='test3')) assert_raises(FieldError, get_object_or_none, ShortcutsModel, non_field='test2') assert_raises(MultipleObjectsReturned, get_object_or_none, ShortcutsModel, name='test2') def test_get_object_or_404(self): obj = ShortcutsModel.objects.create(name='test1', datetime=timezone.now(), number=1) ShortcutsModel.objects.create(name='test2', datetime=timezone.now(), number=2) ShortcutsModel.objects.create(name='test2', datetime=timezone.now(), number=3) assert_equal(get_object_or_404(ShortcutsModel, name='test1'), obj) assert_raises(Http404, get_object_or_404, ShortcutsModel, name='test3') assert_raises(Http404, get_object_or_404, ShortcutsModel, number='test3') assert_raises(Http404, get_object_or_404, ShortcutsModel, datetime='test3') assert_raises(FieldError, get_object_or_none, ShortcutsModel, non_field='test2') assert_raises(MultipleObjectsReturned, get_object_or_none, ShortcutsModel, name='test2') def test_distinct_fields(self): ShortcutsModel.objects.create(name='test1', datetime=timezone.now(), number=1) ShortcutsModel.objects.create(name='test2', datetime=timezone.now(), number=2) ShortcutsModel.objects.create(name='test2', datetime=timezone.now(), number=3) assert_equal(tuple(distinct_field(ShortcutsModel, 'name')), (('test1',), ('test2',))) assert_equal(list(distinct_field(ShortcutsModel, 'name', flat=True)), ['test1', 'test2']) def test_filter_and_exclude_by_date(self): ShortcutsModel.objects.create(name='test1', datetime=timezone.now(), number=1) <|code_end|> . Write the next line using the current file imports: from datetime import date, datetime from django.core.exceptions import FieldError, MultipleObjectsReturned from django.http.response import Http404 from django.test import TestCase from django.utils import timezone from chamber.shortcuts import ( bulk_change, bulk_change_and_save, bulk_save, change, change_and_save, distinct_field, exclude_by_date, filter_by_date, get_object_or_404, get_object_or_none ) from germanium.tools import assert_equal, assert_is_none, assert_raises # pylint: disable=E0401 from test_chamber.models import ShortcutsModel, DiffModel and context from other files: # Path: chamber/shortcuts.py # def bulk_change(iterable, **changed_fields): # """ # Changes a given `changed_fields` on each object in a given `iterable`, returns the changed objects. # """ # return [change(obj, **changed_fields) for obj in iterable] # # def bulk_change_and_save(iterable, update_only_changed_fields=False, save_kwargs=None, **changed_fields): # """ # Changes a given `changed_fields` on each object in a given `iterable`, saves objects # and returns the changed objects. # """ # return [ # change_and_save(obj, update_only_changed_fields=update_only_changed_fields, save_kwargs=save_kwargs, # **changed_fields) # for obj in iterable # ] # # def bulk_save(iterable): # """ # Saves a objects in a given `iterable`. # """ # return [obj.save() for obj in iterable] # # def change(obj, **changed_fields): # """ # Changes a given `changed_fields` on object and returns changed object. # """ # obj_field_names = get_model_field_names(obj) # # for field_name, value in changed_fields.items(): # if field_name not in obj_field_names: # raise ValueError("'{}' is an invalid field name".format(field_name)) # setattr(obj, field_name, value) # return obj # # def change_and_save(obj, update_only_changed_fields=False, save_kwargs=None, **changed_fields): # """ # Changes a given `changed_fields` on object, saves it and returns changed object. # """ # from chamber.models import SmartModel # # save_kwargs = save_kwargs if save_kwargs is not None else {} # if update_only_changed_fields: # if isinstance(obj, SmartModel): # save_kwargs['update_only_changed_fields'] = True # else: # save_kwargs['update_fields'] = get_update_fields(obj, **changed_fields) # # change(obj, **changed_fields) # obj.save(**save_kwargs) # return obj # # def distinct_field(klass, *args, **kwargs): # return _get_queryset(klass).order_by().values_list(*args, **kwargs).distinct() # # def exclude_by_date(klass, **kwargs): # return filter_or_exclude_by_date(True, klass, **kwargs) # # def filter_by_date(klass, **kwargs): # return filter_or_exclude_by_date(False, klass, **kwargs) # # def get_object_or_404(klass, *args, **kwargs): # queryset = _get_queryset(klass) # try: # return queryset.get(*args, **kwargs) # except (queryset.model.DoesNotExist, ValueError, ValidationError): # raise Http404 # # def get_object_or_none(klass, *args, **kwargs): # queryset = _get_queryset(klass) # try: # return queryset.get(*args, **kwargs) # except (queryset.model.DoesNotExist, ValueError, ValidationError): # return None , which may include functions, classes, or code. Output only the next line.
ShortcutsModel.objects.create(name='test1', datetime=timezone.now(), number=1)
Continue the code snippet: <|code_start|> ShortcutsModel.objects.create(name='test1', datetime=timezone.make_aware(datetime(2014, 1, 1, 12, 12), timezone.get_default_timezone()), number=1) assert_equal(filter_by_date(ShortcutsModel, datetime=date.today()).count(), 2) assert_equal(filter_by_date(ShortcutsModel, datetime=date(2014, 1, 1)).count(), 1) assert_equal(exclude_by_date(ShortcutsModel, datetime=date.today()).count(), 1) assert_equal(exclude_by_date(ShortcutsModel, datetime=date(2014, 1, 1)).count(), 2) def test_change(self): obj = ShortcutsModel.objects.create(name='test1', datetime=timezone.now(), number=1) change(obj, name='modified') assert_equal(obj.name, 'modified') assert_equal(ShortcutsModel.objects.first().name, 'test1') # instance is changed but NOT saved to DB def test_change_and_save(self): obj = ShortcutsModel.objects.create(name='test1', datetime=timezone.now(), number=1) change_and_save(obj, name='modified') assert_equal(obj.name, 'modified') assert_equal(ShortcutsModel.objects.first().name, 'modified') # instance is changed and saved to DB def test_change_and_save_with_update_only_changed_fields_should_change_only_defined_fields(self): obj = DiffModel.objects.create(name='test', datetime=timezone.now(), number=2) DiffModel.objects.filter(pk=obj.pk).update(name='test2') obj.change_and_save(number=3, update_only_changed_fields=True) obj.refresh_from_db() assert_equal(obj.name, 'test2') assert_equal(obj.number, 3) def test_model_change(self): <|code_end|> . Use current file imports: from datetime import date, datetime from django.core.exceptions import FieldError, MultipleObjectsReturned from django.http.response import Http404 from django.test import TestCase from django.utils import timezone from chamber.shortcuts import ( bulk_change, bulk_change_and_save, bulk_save, change, change_and_save, distinct_field, exclude_by_date, filter_by_date, get_object_or_404, get_object_or_none ) from germanium.tools import assert_equal, assert_is_none, assert_raises # pylint: disable=E0401 from test_chamber.models import ShortcutsModel, DiffModel and context (classes, functions, or code) from other files: # Path: chamber/shortcuts.py # def bulk_change(iterable, **changed_fields): # """ # Changes a given `changed_fields` on each object in a given `iterable`, returns the changed objects. # """ # return [change(obj, **changed_fields) for obj in iterable] # # def bulk_change_and_save(iterable, update_only_changed_fields=False, save_kwargs=None, **changed_fields): # """ # Changes a given `changed_fields` on each object in a given `iterable`, saves objects # and returns the changed objects. # """ # return [ # change_and_save(obj, update_only_changed_fields=update_only_changed_fields, save_kwargs=save_kwargs, # **changed_fields) # for obj in iterable # ] # # def bulk_save(iterable): # """ # Saves a objects in a given `iterable`. # """ # return [obj.save() for obj in iterable] # # def change(obj, **changed_fields): # """ # Changes a given `changed_fields` on object and returns changed object. # """ # obj_field_names = get_model_field_names(obj) # # for field_name, value in changed_fields.items(): # if field_name not in obj_field_names: # raise ValueError("'{}' is an invalid field name".format(field_name)) # setattr(obj, field_name, value) # return obj # # def change_and_save(obj, update_only_changed_fields=False, save_kwargs=None, **changed_fields): # """ # Changes a given `changed_fields` on object, saves it and returns changed object. # """ # from chamber.models import SmartModel # # save_kwargs = save_kwargs if save_kwargs is not None else {} # if update_only_changed_fields: # if isinstance(obj, SmartModel): # save_kwargs['update_only_changed_fields'] = True # else: # save_kwargs['update_fields'] = get_update_fields(obj, **changed_fields) # # change(obj, **changed_fields) # obj.save(**save_kwargs) # return obj # # def distinct_field(klass, *args, **kwargs): # return _get_queryset(klass).order_by().values_list(*args, **kwargs).distinct() # # def exclude_by_date(klass, **kwargs): # return filter_or_exclude_by_date(True, klass, **kwargs) # # def filter_by_date(klass, **kwargs): # return filter_or_exclude_by_date(False, klass, **kwargs) # # def get_object_or_404(klass, *args, **kwargs): # queryset = _get_queryset(klass) # try: # return queryset.get(*args, **kwargs) # except (queryset.model.DoesNotExist, ValueError, ValidationError): # raise Http404 # # def get_object_or_none(klass, *args, **kwargs): # queryset = _get_queryset(klass) # try: # return queryset.get(*args, **kwargs) # except (queryset.model.DoesNotExist, ValueError, ValidationError): # return None . Output only the next line.
obj = DiffModel.objects.create(name='test', datetime=timezone.now(), number=2)
Using the snippet: <|code_start|> assert_equal(exclude_by_date(ShortcutsModel, datetime=date.today()).count(), 1) assert_equal(exclude_by_date(ShortcutsModel, datetime=date(2014, 1, 1)).count(), 2) def test_change(self): obj = ShortcutsModel.objects.create(name='test1', datetime=timezone.now(), number=1) change(obj, name='modified') assert_equal(obj.name, 'modified') assert_equal(ShortcutsModel.objects.first().name, 'test1') # instance is changed but NOT saved to DB def test_change_and_save(self): obj = ShortcutsModel.objects.create(name='test1', datetime=timezone.now(), number=1) change_and_save(obj, name='modified') assert_equal(obj.name, 'modified') assert_equal(ShortcutsModel.objects.first().name, 'modified') # instance is changed and saved to DB def test_change_and_save_with_update_only_changed_fields_should_change_only_defined_fields(self): obj = DiffModel.objects.create(name='test', datetime=timezone.now(), number=2) DiffModel.objects.filter(pk=obj.pk).update(name='test2') obj.change_and_save(number=3, update_only_changed_fields=True) obj.refresh_from_db() assert_equal(obj.name, 'test2') assert_equal(obj.number, 3) def test_model_change(self): obj = DiffModel.objects.create(name='test', datetime=timezone.now(), number=2) DiffModel.objects.filter(pk=obj.pk).update(name='test2') obj.change(number=3) assert_equal(obj.number, 3) <|code_end|> , determine the next line of code. You have imports: from datetime import date, datetime from django.core.exceptions import FieldError, MultipleObjectsReturned from django.http.response import Http404 from django.test import TestCase from django.utils import timezone from chamber.shortcuts import ( bulk_change, bulk_change_and_save, bulk_save, change, change_and_save, distinct_field, exclude_by_date, filter_by_date, get_object_or_404, get_object_or_none ) from germanium.tools import assert_equal, assert_is_none, assert_raises # pylint: disable=E0401 from test_chamber.models import ShortcutsModel, DiffModel and context (class names, function names, or code) available: # Path: chamber/shortcuts.py # def bulk_change(iterable, **changed_fields): # """ # Changes a given `changed_fields` on each object in a given `iterable`, returns the changed objects. # """ # return [change(obj, **changed_fields) for obj in iterable] # # def bulk_change_and_save(iterable, update_only_changed_fields=False, save_kwargs=None, **changed_fields): # """ # Changes a given `changed_fields` on each object in a given `iterable`, saves objects # and returns the changed objects. # """ # return [ # change_and_save(obj, update_only_changed_fields=update_only_changed_fields, save_kwargs=save_kwargs, # **changed_fields) # for obj in iterable # ] # # def bulk_save(iterable): # """ # Saves a objects in a given `iterable`. # """ # return [obj.save() for obj in iterable] # # def change(obj, **changed_fields): # """ # Changes a given `changed_fields` on object and returns changed object. # """ # obj_field_names = get_model_field_names(obj) # # for field_name, value in changed_fields.items(): # if field_name not in obj_field_names: # raise ValueError("'{}' is an invalid field name".format(field_name)) # setattr(obj, field_name, value) # return obj # # def change_and_save(obj, update_only_changed_fields=False, save_kwargs=None, **changed_fields): # """ # Changes a given `changed_fields` on object, saves it and returns changed object. # """ # from chamber.models import SmartModel # # save_kwargs = save_kwargs if save_kwargs is not None else {} # if update_only_changed_fields: # if isinstance(obj, SmartModel): # save_kwargs['update_only_changed_fields'] = True # else: # save_kwargs['update_fields'] = get_update_fields(obj, **changed_fields) # # change(obj, **changed_fields) # obj.save(**save_kwargs) # return obj # # def distinct_field(klass, *args, **kwargs): # return _get_queryset(klass).order_by().values_list(*args, **kwargs).distinct() # # def exclude_by_date(klass, **kwargs): # return filter_or_exclude_by_date(True, klass, **kwargs) # # def filter_by_date(klass, **kwargs): # return filter_or_exclude_by_date(False, klass, **kwargs) # # def get_object_or_404(klass, *args, **kwargs): # queryset = _get_queryset(klass) # try: # return queryset.get(*args, **kwargs) # except (queryset.model.DoesNotExist, ValueError, ValidationError): # raise Http404 # # def get_object_or_none(klass, *args, **kwargs): # queryset = _get_queryset(klass) # try: # return queryset.get(*args, **kwargs) # except (queryset.model.DoesNotExist, ValueError, ValidationError): # return None . Output only the next line.
def test_bulk_change_and_save(self):
Based on the snippet: <|code_start|> class ShortcutsTestCase(TestCase): def test_get_object_or_none(self): obj = ShortcutsModel.objects.create(name='test1', datetime=timezone.now(), number=1) ShortcutsModel.objects.create(name='test2', datetime=timezone.now(), number=2) ShortcutsModel.objects.create(name='test2', datetime=timezone.now(), number=3) assert_equal(get_object_or_none(ShortcutsModel, name='test1'), obj) assert_is_none(get_object_or_none(ShortcutsModel, name='test3')) assert_is_none(get_object_or_none(ShortcutsModel, number='test3')) assert_is_none(get_object_or_none(ShortcutsModel, datetime='test3')) assert_raises(FieldError, get_object_or_none, ShortcutsModel, non_field='test2') assert_raises(MultipleObjectsReturned, get_object_or_none, ShortcutsModel, name='test2') def test_get_object_or_404(self): obj = ShortcutsModel.objects.create(name='test1', datetime=timezone.now(), number=1) ShortcutsModel.objects.create(name='test2', datetime=timezone.now(), number=2) <|code_end|> , predict the immediate next line with the help of imports: from datetime import date, datetime from django.core.exceptions import FieldError, MultipleObjectsReturned from django.http.response import Http404 from django.test import TestCase from django.utils import timezone from chamber.shortcuts import ( bulk_change, bulk_change_and_save, bulk_save, change, change_and_save, distinct_field, exclude_by_date, filter_by_date, get_object_or_404, get_object_or_none ) from germanium.tools import assert_equal, assert_is_none, assert_raises # pylint: disable=E0401 from test_chamber.models import ShortcutsModel, DiffModel and context (classes, functions, sometimes code) from other files: # Path: chamber/shortcuts.py # def bulk_change(iterable, **changed_fields): # """ # Changes a given `changed_fields` on each object in a given `iterable`, returns the changed objects. # """ # return [change(obj, **changed_fields) for obj in iterable] # # def bulk_change_and_save(iterable, update_only_changed_fields=False, save_kwargs=None, **changed_fields): # """ # Changes a given `changed_fields` on each object in a given `iterable`, saves objects # and returns the changed objects. # """ # return [ # change_and_save(obj, update_only_changed_fields=update_only_changed_fields, save_kwargs=save_kwargs, # **changed_fields) # for obj in iterable # ] # # def bulk_save(iterable): # """ # Saves a objects in a given `iterable`. # """ # return [obj.save() for obj in iterable] # # def change(obj, **changed_fields): # """ # Changes a given `changed_fields` on object and returns changed object. # """ # obj_field_names = get_model_field_names(obj) # # for field_name, value in changed_fields.items(): # if field_name not in obj_field_names: # raise ValueError("'{}' is an invalid field name".format(field_name)) # setattr(obj, field_name, value) # return obj # # def change_and_save(obj, update_only_changed_fields=False, save_kwargs=None, **changed_fields): # """ # Changes a given `changed_fields` on object, saves it and returns changed object. # """ # from chamber.models import SmartModel # # save_kwargs = save_kwargs if save_kwargs is not None else {} # if update_only_changed_fields: # if isinstance(obj, SmartModel): # save_kwargs['update_only_changed_fields'] = True # else: # save_kwargs['update_fields'] = get_update_fields(obj, **changed_fields) # # change(obj, **changed_fields) # obj.save(**save_kwargs) # return obj # # def distinct_field(klass, *args, **kwargs): # return _get_queryset(klass).order_by().values_list(*args, **kwargs).distinct() # # def exclude_by_date(klass, **kwargs): # return filter_or_exclude_by_date(True, klass, **kwargs) # # def filter_by_date(klass, **kwargs): # return filter_or_exclude_by_date(False, klass, **kwargs) # # def get_object_or_404(klass, *args, **kwargs): # queryset = _get_queryset(klass) # try: # return queryset.get(*args, **kwargs) # except (queryset.model.DoesNotExist, ValueError, ValidationError): # raise Http404 # # def get_object_or_none(klass, *args, **kwargs): # queryset = _get_queryset(klass) # try: # return queryset.get(*args, **kwargs) # except (queryset.model.DoesNotExist, ValueError, ValidationError): # return None . Output only the next line.
ShortcutsModel.objects.create(name='test2', datetime=timezone.now(), number=3)
Using the snippet: <|code_start|> assert_is_none(get_object_or_none(ShortcutsModel, number='test3')) assert_is_none(get_object_or_none(ShortcutsModel, datetime='test3')) assert_raises(FieldError, get_object_or_none, ShortcutsModel, non_field='test2') assert_raises(MultipleObjectsReturned, get_object_or_none, ShortcutsModel, name='test2') def test_get_object_or_404(self): obj = ShortcutsModel.objects.create(name='test1', datetime=timezone.now(), number=1) ShortcutsModel.objects.create(name='test2', datetime=timezone.now(), number=2) ShortcutsModel.objects.create(name='test2', datetime=timezone.now(), number=3) assert_equal(get_object_or_404(ShortcutsModel, name='test1'), obj) assert_raises(Http404, get_object_or_404, ShortcutsModel, name='test3') assert_raises(Http404, get_object_or_404, ShortcutsModel, number='test3') assert_raises(Http404, get_object_or_404, ShortcutsModel, datetime='test3') assert_raises(FieldError, get_object_or_none, ShortcutsModel, non_field='test2') assert_raises(MultipleObjectsReturned, get_object_or_none, ShortcutsModel, name='test2') def test_distinct_fields(self): ShortcutsModel.objects.create(name='test1', datetime=timezone.now(), number=1) ShortcutsModel.objects.create(name='test2', datetime=timezone.now(), number=2) ShortcutsModel.objects.create(name='test2', datetime=timezone.now(), number=3) assert_equal(tuple(distinct_field(ShortcutsModel, 'name')), (('test1',), ('test2',))) assert_equal(list(distinct_field(ShortcutsModel, 'name', flat=True)), ['test1', 'test2']) def test_filter_and_exclude_by_date(self): ShortcutsModel.objects.create(name='test1', datetime=timezone.now(), number=1) ShortcutsModel.objects.create(name='test1', datetime=timezone.now(), number=1) ShortcutsModel.objects.create(name='test1', datetime=timezone.make_aware(datetime(2014, 1, 1, 12, 12), <|code_end|> , determine the next line of code. You have imports: from datetime import date, datetime from django.core.exceptions import FieldError, MultipleObjectsReturned from django.http.response import Http404 from django.test import TestCase from django.utils import timezone from chamber.shortcuts import ( bulk_change, bulk_change_and_save, bulk_save, change, change_and_save, distinct_field, exclude_by_date, filter_by_date, get_object_or_404, get_object_or_none ) from germanium.tools import assert_equal, assert_is_none, assert_raises # pylint: disable=E0401 from test_chamber.models import ShortcutsModel, DiffModel and context (class names, function names, or code) available: # Path: chamber/shortcuts.py # def bulk_change(iterable, **changed_fields): # """ # Changes a given `changed_fields` on each object in a given `iterable`, returns the changed objects. # """ # return [change(obj, **changed_fields) for obj in iterable] # # def bulk_change_and_save(iterable, update_only_changed_fields=False, save_kwargs=None, **changed_fields): # """ # Changes a given `changed_fields` on each object in a given `iterable`, saves objects # and returns the changed objects. # """ # return [ # change_and_save(obj, update_only_changed_fields=update_only_changed_fields, save_kwargs=save_kwargs, # **changed_fields) # for obj in iterable # ] # # def bulk_save(iterable): # """ # Saves a objects in a given `iterable`. # """ # return [obj.save() for obj in iterable] # # def change(obj, **changed_fields): # """ # Changes a given `changed_fields` on object and returns changed object. # """ # obj_field_names = get_model_field_names(obj) # # for field_name, value in changed_fields.items(): # if field_name not in obj_field_names: # raise ValueError("'{}' is an invalid field name".format(field_name)) # setattr(obj, field_name, value) # return obj # # def change_and_save(obj, update_only_changed_fields=False, save_kwargs=None, **changed_fields): # """ # Changes a given `changed_fields` on object, saves it and returns changed object. # """ # from chamber.models import SmartModel # # save_kwargs = save_kwargs if save_kwargs is not None else {} # if update_only_changed_fields: # if isinstance(obj, SmartModel): # save_kwargs['update_only_changed_fields'] = True # else: # save_kwargs['update_fields'] = get_update_fields(obj, **changed_fields) # # change(obj, **changed_fields) # obj.save(**save_kwargs) # return obj # # def distinct_field(klass, *args, **kwargs): # return _get_queryset(klass).order_by().values_list(*args, **kwargs).distinct() # # def exclude_by_date(klass, **kwargs): # return filter_or_exclude_by_date(True, klass, **kwargs) # # def filter_by_date(klass, **kwargs): # return filter_or_exclude_by_date(False, klass, **kwargs) # # def get_object_or_404(klass, *args, **kwargs): # queryset = _get_queryset(klass) # try: # return queryset.get(*args, **kwargs) # except (queryset.model.DoesNotExist, ValueError, ValidationError): # raise Http404 # # def get_object_or_none(klass, *args, **kwargs): # queryset = _get_queryset(klass) # try: # return queryset.get(*args, **kwargs) # except (queryset.model.DoesNotExist, ValueError, ValidationError): # return None . Output only the next line.
timezone.get_default_timezone()),
Based on the snippet: <|code_start|> ShortcutsModel.objects.create(name='test1', datetime=timezone.make_aware(datetime(2014, 1, 1, 12, 12), timezone.get_default_timezone()), number=1) assert_equal(filter_by_date(ShortcutsModel, datetime=date.today()).count(), 2) assert_equal(filter_by_date(ShortcutsModel, datetime=date(2014, 1, 1)).count(), 1) assert_equal(exclude_by_date(ShortcutsModel, datetime=date.today()).count(), 1) assert_equal(exclude_by_date(ShortcutsModel, datetime=date(2014, 1, 1)).count(), 2) def test_change(self): obj = ShortcutsModel.objects.create(name='test1', datetime=timezone.now(), number=1) change(obj, name='modified') assert_equal(obj.name, 'modified') assert_equal(ShortcutsModel.objects.first().name, 'test1') # instance is changed but NOT saved to DB def test_change_and_save(self): obj = ShortcutsModel.objects.create(name='test1', datetime=timezone.now(), number=1) change_and_save(obj, name='modified') assert_equal(obj.name, 'modified') assert_equal(ShortcutsModel.objects.first().name, 'modified') # instance is changed and saved to DB def test_change_and_save_with_update_only_changed_fields_should_change_only_defined_fields(self): obj = DiffModel.objects.create(name='test', datetime=timezone.now(), number=2) DiffModel.objects.filter(pk=obj.pk).update(name='test2') obj.change_and_save(number=3, update_only_changed_fields=True) obj.refresh_from_db() assert_equal(obj.name, 'test2') assert_equal(obj.number, 3) def test_model_change(self): <|code_end|> , predict the immediate next line with the help of imports: from datetime import date, datetime from django.core.exceptions import FieldError, MultipleObjectsReturned from django.http.response import Http404 from django.test import TestCase from django.utils import timezone from chamber.shortcuts import ( bulk_change, bulk_change_and_save, bulk_save, change, change_and_save, distinct_field, exclude_by_date, filter_by_date, get_object_or_404, get_object_or_none ) from germanium.tools import assert_equal, assert_is_none, assert_raises # pylint: disable=E0401 from test_chamber.models import ShortcutsModel, DiffModel and context (classes, functions, sometimes code) from other files: # Path: chamber/shortcuts.py # def bulk_change(iterable, **changed_fields): # """ # Changes a given `changed_fields` on each object in a given `iterable`, returns the changed objects. # """ # return [change(obj, **changed_fields) for obj in iterable] # # def bulk_change_and_save(iterable, update_only_changed_fields=False, save_kwargs=None, **changed_fields): # """ # Changes a given `changed_fields` on each object in a given `iterable`, saves objects # and returns the changed objects. # """ # return [ # change_and_save(obj, update_only_changed_fields=update_only_changed_fields, save_kwargs=save_kwargs, # **changed_fields) # for obj in iterable # ] # # def bulk_save(iterable): # """ # Saves a objects in a given `iterable`. # """ # return [obj.save() for obj in iterable] # # def change(obj, **changed_fields): # """ # Changes a given `changed_fields` on object and returns changed object. # """ # obj_field_names = get_model_field_names(obj) # # for field_name, value in changed_fields.items(): # if field_name not in obj_field_names: # raise ValueError("'{}' is an invalid field name".format(field_name)) # setattr(obj, field_name, value) # return obj # # def change_and_save(obj, update_only_changed_fields=False, save_kwargs=None, **changed_fields): # """ # Changes a given `changed_fields` on object, saves it and returns changed object. # """ # from chamber.models import SmartModel # # save_kwargs = save_kwargs if save_kwargs is not None else {} # if update_only_changed_fields: # if isinstance(obj, SmartModel): # save_kwargs['update_only_changed_fields'] = True # else: # save_kwargs['update_fields'] = get_update_fields(obj, **changed_fields) # # change(obj, **changed_fields) # obj.save(**save_kwargs) # return obj # # def distinct_field(klass, *args, **kwargs): # return _get_queryset(klass).order_by().values_list(*args, **kwargs).distinct() # # def exclude_by_date(klass, **kwargs): # return filter_or_exclude_by_date(True, klass, **kwargs) # # def filter_by_date(klass, **kwargs): # return filter_or_exclude_by_date(False, klass, **kwargs) # # def get_object_or_404(klass, *args, **kwargs): # queryset = _get_queryset(klass) # try: # return queryset.get(*args, **kwargs) # except (queryset.model.DoesNotExist, ValueError, ValidationError): # raise Http404 # # def get_object_or_none(klass, *args, **kwargs): # queryset = _get_queryset(klass) # try: # return queryset.get(*args, **kwargs) # except (queryset.model.DoesNotExist, ValueError, ValidationError): # return None . Output only the next line.
obj = DiffModel.objects.create(name='test', datetime=timezone.now(), number=2)
Given the code snippet: <|code_start|> ShortcutsModel.objects.create(name='test2', datetime=timezone.now(), number=3) assert_equal(get_object_or_none(ShortcutsModel, name='test1'), obj) assert_is_none(get_object_or_none(ShortcutsModel, name='test3')) assert_is_none(get_object_or_none(ShortcutsModel, number='test3')) assert_is_none(get_object_or_none(ShortcutsModel, datetime='test3')) assert_raises(FieldError, get_object_or_none, ShortcutsModel, non_field='test2') assert_raises(MultipleObjectsReturned, get_object_or_none, ShortcutsModel, name='test2') def test_get_object_or_404(self): obj = ShortcutsModel.objects.create(name='test1', datetime=timezone.now(), number=1) ShortcutsModel.objects.create(name='test2', datetime=timezone.now(), number=2) ShortcutsModel.objects.create(name='test2', datetime=timezone.now(), number=3) assert_equal(get_object_or_404(ShortcutsModel, name='test1'), obj) assert_raises(Http404, get_object_or_404, ShortcutsModel, name='test3') assert_raises(Http404, get_object_or_404, ShortcutsModel, number='test3') assert_raises(Http404, get_object_or_404, ShortcutsModel, datetime='test3') assert_raises(FieldError, get_object_or_none, ShortcutsModel, non_field='test2') assert_raises(MultipleObjectsReturned, get_object_or_none, ShortcutsModel, name='test2') def test_distinct_fields(self): ShortcutsModel.objects.create(name='test1', datetime=timezone.now(), number=1) ShortcutsModel.objects.create(name='test2', datetime=timezone.now(), number=2) ShortcutsModel.objects.create(name='test2', datetime=timezone.now(), number=3) assert_equal(tuple(distinct_field(ShortcutsModel, 'name')), (('test1',), ('test2',))) assert_equal(list(distinct_field(ShortcutsModel, 'name', flat=True)), ['test1', 'test2']) <|code_end|> , generate the next line using the imports in this file: from datetime import date, datetime from django.core.exceptions import FieldError, MultipleObjectsReturned from django.http.response import Http404 from django.test import TestCase from django.utils import timezone from chamber.shortcuts import ( bulk_change, bulk_change_and_save, bulk_save, change, change_and_save, distinct_field, exclude_by_date, filter_by_date, get_object_or_404, get_object_or_none ) from germanium.tools import assert_equal, assert_is_none, assert_raises # pylint: disable=E0401 from test_chamber.models import ShortcutsModel, DiffModel and context (functions, classes, or occasionally code) from other files: # Path: chamber/shortcuts.py # def bulk_change(iterable, **changed_fields): # """ # Changes a given `changed_fields` on each object in a given `iterable`, returns the changed objects. # """ # return [change(obj, **changed_fields) for obj in iterable] # # def bulk_change_and_save(iterable, update_only_changed_fields=False, save_kwargs=None, **changed_fields): # """ # Changes a given `changed_fields` on each object in a given `iterable`, saves objects # and returns the changed objects. # """ # return [ # change_and_save(obj, update_only_changed_fields=update_only_changed_fields, save_kwargs=save_kwargs, # **changed_fields) # for obj in iterable # ] # # def bulk_save(iterable): # """ # Saves a objects in a given `iterable`. # """ # return [obj.save() for obj in iterable] # # def change(obj, **changed_fields): # """ # Changes a given `changed_fields` on object and returns changed object. # """ # obj_field_names = get_model_field_names(obj) # # for field_name, value in changed_fields.items(): # if field_name not in obj_field_names: # raise ValueError("'{}' is an invalid field name".format(field_name)) # setattr(obj, field_name, value) # return obj # # def change_and_save(obj, update_only_changed_fields=False, save_kwargs=None, **changed_fields): # """ # Changes a given `changed_fields` on object, saves it and returns changed object. # """ # from chamber.models import SmartModel # # save_kwargs = save_kwargs if save_kwargs is not None else {} # if update_only_changed_fields: # if isinstance(obj, SmartModel): # save_kwargs['update_only_changed_fields'] = True # else: # save_kwargs['update_fields'] = get_update_fields(obj, **changed_fields) # # change(obj, **changed_fields) # obj.save(**save_kwargs) # return obj # # def distinct_field(klass, *args, **kwargs): # return _get_queryset(klass).order_by().values_list(*args, **kwargs).distinct() # # def exclude_by_date(klass, **kwargs): # return filter_or_exclude_by_date(True, klass, **kwargs) # # def filter_by_date(klass, **kwargs): # return filter_or_exclude_by_date(False, klass, **kwargs) # # def get_object_or_404(klass, *args, **kwargs): # queryset = _get_queryset(klass) # try: # return queryset.get(*args, **kwargs) # except (queryset.model.DoesNotExist, ValueError, ValidationError): # raise Http404 # # def get_object_or_none(klass, *args, **kwargs): # queryset = _get_queryset(klass) # try: # return queryset.get(*args, **kwargs) # except (queryset.model.DoesNotExist, ValueError, ValidationError): # return None . Output only the next line.
def test_filter_and_exclude_by_date(self):
Continue the code snippet: <|code_start|> obj1 = ShortcutsModel.objects.create(name='test1', datetime=timezone.now(), number=1) obj2 = ShortcutsModel.objects.create(name='test2', datetime=timezone.now(), number=2) bulk_change_and_save([obj1, obj2], name='modified') assert_equal(obj1.name, 'modified') assert_equal(obj2.name, 'modified') assert_equal(ShortcutsModel.objects.first().name, 'modified') # instance is changed but NOT saved to DB assert_equal(ShortcutsModel.objects.last().name, 'modified') # instance is changed but NOT saved to DB def test_bulk_change_and_bulk_save(self): obj1 = ShortcutsModel.objects.create(name='test1', datetime=timezone.now(), number=1) obj2 = ShortcutsModel.objects.create(name='test2', datetime=timezone.now(), number=2) # Bulk change objects bulk_change([obj1, obj2], name='modified') assert_equal(obj1.name, 'modified') assert_equal(obj2.name, 'modified') assert_equal(ShortcutsModel.objects.first().name, 'test1') # instance is changed but NOT saved to DB assert_equal(ShortcutsModel.objects.last().name, 'test2') # instance is changed but NOT saved to DB # Bulk save objects bulk_save([obj1, obj2]) assert_equal(ShortcutsModel.objects.first().name, 'modified') # instance is changed but saved to DB assert_equal(ShortcutsModel.objects.last().name, 'modified') # instance is changed but saved to DB def test_queryset_change_and_save(self): obj1 = DiffModel.objects.create(name='test', datetime=timezone.now(), number=2) obj2 = DiffModel.objects.create(name='test', datetime=timezone.now(), number=2) DiffModel.objects.all().change_and_save(name='modified') obj1.refresh_from_db() obj2.refresh_from_db() <|code_end|> . Use current file imports: from datetime import date, datetime from django.core.exceptions import FieldError, MultipleObjectsReturned from django.http.response import Http404 from django.test import TestCase from django.utils import timezone from chamber.shortcuts import ( bulk_change, bulk_change_and_save, bulk_save, change, change_and_save, distinct_field, exclude_by_date, filter_by_date, get_object_or_404, get_object_or_none ) from germanium.tools import assert_equal, assert_is_none, assert_raises # pylint: disable=E0401 from test_chamber.models import ShortcutsModel, DiffModel and context (classes, functions, or code) from other files: # Path: chamber/shortcuts.py # def bulk_change(iterable, **changed_fields): # """ # Changes a given `changed_fields` on each object in a given `iterable`, returns the changed objects. # """ # return [change(obj, **changed_fields) for obj in iterable] # # def bulk_change_and_save(iterable, update_only_changed_fields=False, save_kwargs=None, **changed_fields): # """ # Changes a given `changed_fields` on each object in a given `iterable`, saves objects # and returns the changed objects. # """ # return [ # change_and_save(obj, update_only_changed_fields=update_only_changed_fields, save_kwargs=save_kwargs, # **changed_fields) # for obj in iterable # ] # # def bulk_save(iterable): # """ # Saves a objects in a given `iterable`. # """ # return [obj.save() for obj in iterable] # # def change(obj, **changed_fields): # """ # Changes a given `changed_fields` on object and returns changed object. # """ # obj_field_names = get_model_field_names(obj) # # for field_name, value in changed_fields.items(): # if field_name not in obj_field_names: # raise ValueError("'{}' is an invalid field name".format(field_name)) # setattr(obj, field_name, value) # return obj # # def change_and_save(obj, update_only_changed_fields=False, save_kwargs=None, **changed_fields): # """ # Changes a given `changed_fields` on object, saves it and returns changed object. # """ # from chamber.models import SmartModel # # save_kwargs = save_kwargs if save_kwargs is not None else {} # if update_only_changed_fields: # if isinstance(obj, SmartModel): # save_kwargs['update_only_changed_fields'] = True # else: # save_kwargs['update_fields'] = get_update_fields(obj, **changed_fields) # # change(obj, **changed_fields) # obj.save(**save_kwargs) # return obj # # def distinct_field(klass, *args, **kwargs): # return _get_queryset(klass).order_by().values_list(*args, **kwargs).distinct() # # def exclude_by_date(klass, **kwargs): # return filter_or_exclude_by_date(True, klass, **kwargs) # # def filter_by_date(klass, **kwargs): # return filter_or_exclude_by_date(False, klass, **kwargs) # # def get_object_or_404(klass, *args, **kwargs): # queryset = _get_queryset(klass) # try: # return queryset.get(*args, **kwargs) # except (queryset.model.DoesNotExist, ValueError, ValidationError): # raise Http404 # # def get_object_or_none(klass, *args, **kwargs): # queryset = _get_queryset(klass) # try: # return queryset.get(*args, **kwargs) # except (queryset.model.DoesNotExist, ValueError, ValidationError): # return None . Output only the next line.
assert_equal(obj1.name, 'modified')
Given snippet: <|code_start|> ShortcutsModel.objects.create(name='test2', datetime=timezone.now(), number=2) ShortcutsModel.objects.create(name='test2', datetime=timezone.now(), number=3) assert_equal(tuple(distinct_field(ShortcutsModel, 'name')), (('test1',), ('test2',))) assert_equal(list(distinct_field(ShortcutsModel, 'name', flat=True)), ['test1', 'test2']) def test_filter_and_exclude_by_date(self): ShortcutsModel.objects.create(name='test1', datetime=timezone.now(), number=1) ShortcutsModel.objects.create(name='test1', datetime=timezone.now(), number=1) ShortcutsModel.objects.create(name='test1', datetime=timezone.make_aware(datetime(2014, 1, 1, 12, 12), timezone.get_default_timezone()), number=1) assert_equal(filter_by_date(ShortcutsModel, datetime=date.today()).count(), 2) assert_equal(filter_by_date(ShortcutsModel, datetime=date(2014, 1, 1)).count(), 1) assert_equal(exclude_by_date(ShortcutsModel, datetime=date.today()).count(), 1) assert_equal(exclude_by_date(ShortcutsModel, datetime=date(2014, 1, 1)).count(), 2) def test_change(self): obj = ShortcutsModel.objects.create(name='test1', datetime=timezone.now(), number=1) change(obj, name='modified') assert_equal(obj.name, 'modified') assert_equal(ShortcutsModel.objects.first().name, 'test1') # instance is changed but NOT saved to DB def test_change_and_save(self): obj = ShortcutsModel.objects.create(name='test1', datetime=timezone.now(), number=1) change_and_save(obj, name='modified') assert_equal(obj.name, 'modified') assert_equal(ShortcutsModel.objects.first().name, 'modified') # instance is changed and saved to DB def test_change_and_save_with_update_only_changed_fields_should_change_only_defined_fields(self): <|code_end|> , continue by predicting the next line. Consider current file imports: from datetime import date, datetime from django.core.exceptions import FieldError, MultipleObjectsReturned from django.http.response import Http404 from django.test import TestCase from django.utils import timezone from chamber.shortcuts import ( bulk_change, bulk_change_and_save, bulk_save, change, change_and_save, distinct_field, exclude_by_date, filter_by_date, get_object_or_404, get_object_or_none ) from germanium.tools import assert_equal, assert_is_none, assert_raises # pylint: disable=E0401 from test_chamber.models import ShortcutsModel, DiffModel and context: # Path: chamber/shortcuts.py # def bulk_change(iterable, **changed_fields): # """ # Changes a given `changed_fields` on each object in a given `iterable`, returns the changed objects. # """ # return [change(obj, **changed_fields) for obj in iterable] # # def bulk_change_and_save(iterable, update_only_changed_fields=False, save_kwargs=None, **changed_fields): # """ # Changes a given `changed_fields` on each object in a given `iterable`, saves objects # and returns the changed objects. # """ # return [ # change_and_save(obj, update_only_changed_fields=update_only_changed_fields, save_kwargs=save_kwargs, # **changed_fields) # for obj in iterable # ] # # def bulk_save(iterable): # """ # Saves a objects in a given `iterable`. # """ # return [obj.save() for obj in iterable] # # def change(obj, **changed_fields): # """ # Changes a given `changed_fields` on object and returns changed object. # """ # obj_field_names = get_model_field_names(obj) # # for field_name, value in changed_fields.items(): # if field_name not in obj_field_names: # raise ValueError("'{}' is an invalid field name".format(field_name)) # setattr(obj, field_name, value) # return obj # # def change_and_save(obj, update_only_changed_fields=False, save_kwargs=None, **changed_fields): # """ # Changes a given `changed_fields` on object, saves it and returns changed object. # """ # from chamber.models import SmartModel # # save_kwargs = save_kwargs if save_kwargs is not None else {} # if update_only_changed_fields: # if isinstance(obj, SmartModel): # save_kwargs['update_only_changed_fields'] = True # else: # save_kwargs['update_fields'] = get_update_fields(obj, **changed_fields) # # change(obj, **changed_fields) # obj.save(**save_kwargs) # return obj # # def distinct_field(klass, *args, **kwargs): # return _get_queryset(klass).order_by().values_list(*args, **kwargs).distinct() # # def exclude_by_date(klass, **kwargs): # return filter_or_exclude_by_date(True, klass, **kwargs) # # def filter_by_date(klass, **kwargs): # return filter_or_exclude_by_date(False, klass, **kwargs) # # def get_object_or_404(klass, *args, **kwargs): # queryset = _get_queryset(klass) # try: # return queryset.get(*args, **kwargs) # except (queryset.model.DoesNotExist, ValueError, ValidationError): # raise Http404 # # def get_object_or_none(klass, *args, **kwargs): # queryset = _get_queryset(klass) # try: # return queryset.get(*args, **kwargs) # except (queryset.model.DoesNotExist, ValueError, ValidationError): # return None which might include code, classes, or functions. Output only the next line.
obj = DiffModel.objects.create(name='test', datetime=timezone.now(), number=2)
Given snippet: <|code_start|> setup( name='django-chamber', version=get_version(), description='Utilities library meant as a complement to django-is-core.', author='Lubos Matl, Oskar Hollmann', author_email='matllubos@gmail.com, oskar@hollmann.me', url='http://github.com/druids/django-chamber', packages=find_packages(include=['chamber']), include_package_data=True, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.5', 'Framework :: Django', ], install_requires=[ 'Django>=2.2', 'Unidecode>=1.1.1', 'pyprind>=2.11.2', 'filemagic>=1.6', ], extras_require={ 'boto3storage': ['django-storages<2.0', 'boto3'], }, <|code_end|> , continue by predicting the next line. Consider current file imports: from setuptools import setup, find_packages from chamber.version import get_version and context: # Path: chamber/version.py # def get_version(): # return '.'.join(map(str, VERSION)) which might include code, classes, or functions. Output only the next line.
)
Given the code snippet: <|code_start|> class DatastructuresTestCase(TestCase): def test_enum_should_contain_only_defined_values(self): enum = Enum( 'A', 'B' ) assert_equal(enum.A, 'A') assert_equal(enum.B, 'B') assert_equal(list(enum), ['A', 'B']) assert_equal(enum.all, ('A', 'B')) assert_equal(enum.get_name('A'), 'A') with assert_raises(AttributeError): enum.C # pylint: disable=W0104 <|code_end|> , generate the next line using the imports in this file: from django.test import TestCase from chamber.utils.datastructures import ChoicesEnum, ChoicesNumEnum, Enum, NumEnum, OrderedSet from germanium.tools import assert_equal, assert_raises, assert_is_none, assert_in, assert_not_in and context (functions, classes, or occasionally code) from other files: # Path: chamber/utils/datastructures.py # class ChoicesEnum(AbstractChoicesEnum, Enum): # pass # # class ChoicesNumEnum(AbstractChoicesEnum, NumEnum): # pass # # class Enum(AbstractEnum): # # def __init__(self, *items): # super().__init__(*( # item if isinstance(item, (list, tuple)) else (item, item) # for item in items # )) # # class NumEnum(Enum): # # def __init__(self, *items): # used_ids = set() # # enum_items = [] # i = 0 # for item in items: # if len(item) == 2: # key, i = item # if not isinstance(i, int): # raise ValueError('Choice value of item must by integer') # else: # key = item # i += 1 # # if i in used_ids: # raise ValueError('Index %s already exists, please renumber choices') # # used_ids.add(i) # enum_items.append((key, i)) # super().__init__(*enum_items) # # class OrderedSet(MutableSet): # # def __init__(self, *iterable): # self.end = end = [] # end += [None, end, end] # sentinel node for doubly linked list # self.map = {} # key --> [key, prev, next] # if iterable is not None: # self |= iterable # # def __len__(self): # return len(self.map) # # def __contains__(self, key): # return key in self.map # # def add(self, key): # if key not in self.map: # end = self.end # curr = end[1] # curr[2] = end[1] = self.map[key] = [key, curr, end] # # def discard(self, key): # if key in self.map: # key, prev_item, next_item = self.map.pop(key) # prev_item[2] = next_item # next_item[1] = prev_item # # def __iter__(self): # end = self.end # curr = end[2] # while curr is not end: # yield curr[0] # curr = curr[2] # # def __reversed__(self): # end = self.end # curr = end[1] # while curr is not end: # yield curr[0] # curr = curr[1] # # def pop(self, last=True): # if not self: # raise KeyError('set is empty') # key = self.end[1][0] if last else self.end[2][0] # self.discard(key) # return key # # def __repr__(self): # if not self: # return '{}()'.format(self.__class__.__name__,) # else: # return '{}({})'.format(self.__class__.__name__, list(self)) # # def __eq__(self, other): # if isinstance(other, OrderedSet): # return len(self) == len(other) and list(self) == list(other) # return set(self) == set(other) . Output only the next line.
assert_is_none(enum.get_name('C'))
Predict the next line after this snippet: <|code_start|> with assert_raises(AttributeError): enum.C # pylint: disable=W0104 assert_is_none(enum.get_name('f')) assert_in('c', enum) assert_in(enum.A, enum) assert_not_in('A', enum) def test_auto_gemerated_num_enum_should_contain_only_defined_values(self): enum = NumEnum( 'A', 'B' ) assert_equal(enum.A, 1) assert_equal(enum.B, 2) assert_equal(list(enum), [1, 2]) assert_equal(enum.all, (1, 2)) assert_equal(enum.get_name(1), 'A') with assert_raises(AttributeError): enum.C # pylint: disable=W0104 assert_is_none(enum.get_name(3)) assert_in(1, enum) assert_in(enum.A, enum) assert_not_in('A', enum) def test_num_enum_with_defined_ids_should_return_valid_values(self): enum = NumEnum( ('A', 4), ('B', 2), 'C' ) assert_equal(enum.A, 4) assert_equal(enum.B, 2) assert_equal(enum.C, 3) <|code_end|> using the current file's imports: from django.test import TestCase from chamber.utils.datastructures import ChoicesEnum, ChoicesNumEnum, Enum, NumEnum, OrderedSet from germanium.tools import assert_equal, assert_raises, assert_is_none, assert_in, assert_not_in and any relevant context from other files: # Path: chamber/utils/datastructures.py # class ChoicesEnum(AbstractChoicesEnum, Enum): # pass # # class ChoicesNumEnum(AbstractChoicesEnum, NumEnum): # pass # # class Enum(AbstractEnum): # # def __init__(self, *items): # super().__init__(*( # item if isinstance(item, (list, tuple)) else (item, item) # for item in items # )) # # class NumEnum(Enum): # # def __init__(self, *items): # used_ids = set() # # enum_items = [] # i = 0 # for item in items: # if len(item) == 2: # key, i = item # if not isinstance(i, int): # raise ValueError('Choice value of item must by integer') # else: # key = item # i += 1 # # if i in used_ids: # raise ValueError('Index %s already exists, please renumber choices') # # used_ids.add(i) # enum_items.append((key, i)) # super().__init__(*enum_items) # # class OrderedSet(MutableSet): # # def __init__(self, *iterable): # self.end = end = [] # end += [None, end, end] # sentinel node for doubly linked list # self.map = {} # key --> [key, prev, next] # if iterable is not None: # self |= iterable # # def __len__(self): # return len(self.map) # # def __contains__(self, key): # return key in self.map # # def add(self, key): # if key not in self.map: # end = self.end # curr = end[1] # curr[2] = end[1] = self.map[key] = [key, curr, end] # # def discard(self, key): # if key in self.map: # key, prev_item, next_item = self.map.pop(key) # prev_item[2] = next_item # next_item[1] = prev_item # # def __iter__(self): # end = self.end # curr = end[2] # while curr is not end: # yield curr[0] # curr = curr[2] # # def __reversed__(self): # end = self.end # curr = end[1] # while curr is not end: # yield curr[0] # curr = curr[1] # # def pop(self, last=True): # if not self: # raise KeyError('set is empty') # key = self.end[1][0] if last else self.end[2][0] # self.discard(key) # return key # # def __repr__(self): # if not self: # return '{}()'.format(self.__class__.__name__,) # else: # return '{}({})'.format(self.__class__.__name__, list(self)) # # def __eq__(self, other): # if isinstance(other, OrderedSet): # return len(self) == len(other) and list(self) == list(other) # return set(self) == set(other) . Output only the next line.
assert_equal(list(enum), [4, 2, 3])
Given snippet: <|code_start|> ChoicesNumEnum( ('A', 'label a', 'e'), ('B', 'label b', 2) ) def test_enum_key_should_have_right_format(self): with assert_raises(ValueError): Enum( 1, 2 ) with assert_raises(ValueError): Enum( '1A', 'B' ) with assert_raises(ValueError): Enum( 'A-B', 'B' ) Enum( 'A_B_3', 'B' ) def test_ordered_set_should_keep_order(self): ordered_set = OrderedSet(4, 5, 3) assert_equal(ordered_set, [4, 5, 3]) ordered_set.add(8) assert_equal(ordered_set, [4, 5, 3, 8]) assert_equal(ordered_set.pop(), 8) assert_equal(ordered_set.pop(False), 4) assert_equal(ordered_set, [5, 3]) ordered_set |= OrderedSet(9, 10) <|code_end|> , continue by predicting the next line. Consider current file imports: from django.test import TestCase from chamber.utils.datastructures import ChoicesEnum, ChoicesNumEnum, Enum, NumEnum, OrderedSet from germanium.tools import assert_equal, assert_raises, assert_is_none, assert_in, assert_not_in and context: # Path: chamber/utils/datastructures.py # class ChoicesEnum(AbstractChoicesEnum, Enum): # pass # # class ChoicesNumEnum(AbstractChoicesEnum, NumEnum): # pass # # class Enum(AbstractEnum): # # def __init__(self, *items): # super().__init__(*( # item if isinstance(item, (list, tuple)) else (item, item) # for item in items # )) # # class NumEnum(Enum): # # def __init__(self, *items): # used_ids = set() # # enum_items = [] # i = 0 # for item in items: # if len(item) == 2: # key, i = item # if not isinstance(i, int): # raise ValueError('Choice value of item must by integer') # else: # key = item # i += 1 # # if i in used_ids: # raise ValueError('Index %s already exists, please renumber choices') # # used_ids.add(i) # enum_items.append((key, i)) # super().__init__(*enum_items) # # class OrderedSet(MutableSet): # # def __init__(self, *iterable): # self.end = end = [] # end += [None, end, end] # sentinel node for doubly linked list # self.map = {} # key --> [key, prev, next] # if iterable is not None: # self |= iterable # # def __len__(self): # return len(self.map) # # def __contains__(self, key): # return key in self.map # # def add(self, key): # if key not in self.map: # end = self.end # curr = end[1] # curr[2] = end[1] = self.map[key] = [key, curr, end] # # def discard(self, key): # if key in self.map: # key, prev_item, next_item = self.map.pop(key) # prev_item[2] = next_item # next_item[1] = prev_item # # def __iter__(self): # end = self.end # curr = end[2] # while curr is not end: # yield curr[0] # curr = curr[2] # # def __reversed__(self): # end = self.end # curr = end[1] # while curr is not end: # yield curr[0] # curr = curr[1] # # def pop(self, last=True): # if not self: # raise KeyError('set is empty') # key = self.end[1][0] if last else self.end[2][0] # self.discard(key) # return key # # def __repr__(self): # if not self: # return '{}()'.format(self.__class__.__name__,) # else: # return '{}({})'.format(self.__class__.__name__, list(self)) # # def __eq__(self, other): # if isinstance(other, OrderedSet): # return len(self) == len(other) and list(self) == list(other) # return set(self) == set(other) which might include code, classes, or functions. Output only the next line.
assert_equal(ordered_set, [5, 3, 9, 10])
Next line prediction: <|code_start|> ('B', 'label b', 2), ('C', 'label c') ) assert_equal(choices_num.A, 4) assert_equal(choices_num.B, 2) assert_equal(choices_num.C, 3) assert_equal(list(choices_num.choices), [(4, 'label a'), (2, 'label b'), (3, 'label c')]) assert_equal(choices_num.all, (4, 2, 3)) assert_equal(choices_num.get_label(4), 'label a') assert_equal(choices_num.get_label(2), 'label b') assert_equal(choices_num.get_label(3), 'label c') def test_choices_num_enum_same_numbers_should_raise_exception(self): with assert_raises(ValueError): ChoicesNumEnum( ('A', 'label a', 1), ('B', 'label b', 1) ) def test_choices_num_enum_same_generated_numbers_should_raise_exception(self): with assert_raises(ValueError): ChoicesNumEnum( ('A', 'label a', 3), ('B', 'label b', 2), ('C', 'label c') ) def test_choices_num_enum_invalid_num_raise_exception(self): with assert_raises(ValueError): ChoicesNumEnum( ('A', 'label a', 'e'), ('B', 'label b', 2) ) <|code_end|> . Use current file imports: (from django.test import TestCase from chamber.utils.datastructures import ChoicesEnum, ChoicesNumEnum, Enum, NumEnum, OrderedSet from germanium.tools import assert_equal, assert_raises, assert_is_none, assert_in, assert_not_in) and context including class names, function names, or small code snippets from other files: # Path: chamber/utils/datastructures.py # class ChoicesEnum(AbstractChoicesEnum, Enum): # pass # # class ChoicesNumEnum(AbstractChoicesEnum, NumEnum): # pass # # class Enum(AbstractEnum): # # def __init__(self, *items): # super().__init__(*( # item if isinstance(item, (list, tuple)) else (item, item) # for item in items # )) # # class NumEnum(Enum): # # def __init__(self, *items): # used_ids = set() # # enum_items = [] # i = 0 # for item in items: # if len(item) == 2: # key, i = item # if not isinstance(i, int): # raise ValueError('Choice value of item must by integer') # else: # key = item # i += 1 # # if i in used_ids: # raise ValueError('Index %s already exists, please renumber choices') # # used_ids.add(i) # enum_items.append((key, i)) # super().__init__(*enum_items) # # class OrderedSet(MutableSet): # # def __init__(self, *iterable): # self.end = end = [] # end += [None, end, end] # sentinel node for doubly linked list # self.map = {} # key --> [key, prev, next] # if iterable is not None: # self |= iterable # # def __len__(self): # return len(self.map) # # def __contains__(self, key): # return key in self.map # # def add(self, key): # if key not in self.map: # end = self.end # curr = end[1] # curr[2] = end[1] = self.map[key] = [key, curr, end] # # def discard(self, key): # if key in self.map: # key, prev_item, next_item = self.map.pop(key) # prev_item[2] = next_item # next_item[1] = prev_item # # def __iter__(self): # end = self.end # curr = end[2] # while curr is not end: # yield curr[0] # curr = curr[2] # # def __reversed__(self): # end = self.end # curr = end[1] # while curr is not end: # yield curr[0] # curr = curr[1] # # def pop(self, last=True): # if not self: # raise KeyError('set is empty') # key = self.end[1][0] if last else self.end[2][0] # self.discard(key) # return key # # def __repr__(self): # if not self: # return '{}()'.format(self.__class__.__name__,) # else: # return '{}({})'.format(self.__class__.__name__, list(self)) # # def __eq__(self, other): # if isinstance(other, OrderedSet): # return len(self) == len(other) and list(self) == list(other) # return set(self) == set(other) . Output only the next line.
def test_enum_key_should_have_right_format(self):
Here is a snippet: <|code_start|> ('A', 1), ('B', 1) ) def test_num_enum_same_generated_numbers_should_raise_exception(self): with assert_raises(ValueError): NumEnum( ('A', 3), ('B', 2), 'C' ) def test_num_enum_invalid_num_should_raise_exception(self): with assert_raises(ValueError): NumEnum( ('A', 'e'), ('B', 2) ) def test_choices_enum_should_return_right_values_and_choices(self): choices_num = ChoicesEnum( ('A', 'label a'), ('B', 'label b'), ) assert_equal(choices_num.A, 'A') assert_equal(choices_num.B, 'B') assert_equal(list(choices_num.choices), [('A', 'label a'), ('B', 'label b')]) assert_equal(choices_num.all, ('A', 'B')) assert_equal(choices_num.get_label('A'), 'label a') assert_equal(choices_num.get_label('B'), 'label b') def test_choices_enum_with_distinct_key_and_value_should_return_right_values_and_choices(self): choices_num = ChoicesEnum( ('A', 'label a', 'c'), <|code_end|> . Write the next line using the current file imports: from django.test import TestCase from chamber.utils.datastructures import ChoicesEnum, ChoicesNumEnum, Enum, NumEnum, OrderedSet from germanium.tools import assert_equal, assert_raises, assert_is_none, assert_in, assert_not_in and context from other files: # Path: chamber/utils/datastructures.py # class ChoicesEnum(AbstractChoicesEnum, Enum): # pass # # class ChoicesNumEnum(AbstractChoicesEnum, NumEnum): # pass # # class Enum(AbstractEnum): # # def __init__(self, *items): # super().__init__(*( # item if isinstance(item, (list, tuple)) else (item, item) # for item in items # )) # # class NumEnum(Enum): # # def __init__(self, *items): # used_ids = set() # # enum_items = [] # i = 0 # for item in items: # if len(item) == 2: # key, i = item # if not isinstance(i, int): # raise ValueError('Choice value of item must by integer') # else: # key = item # i += 1 # # if i in used_ids: # raise ValueError('Index %s already exists, please renumber choices') # # used_ids.add(i) # enum_items.append((key, i)) # super().__init__(*enum_items) # # class OrderedSet(MutableSet): # # def __init__(self, *iterable): # self.end = end = [] # end += [None, end, end] # sentinel node for doubly linked list # self.map = {} # key --> [key, prev, next] # if iterable is not None: # self |= iterable # # def __len__(self): # return len(self.map) # # def __contains__(self, key): # return key in self.map # # def add(self, key): # if key not in self.map: # end = self.end # curr = end[1] # curr[2] = end[1] = self.map[key] = [key, curr, end] # # def discard(self, key): # if key in self.map: # key, prev_item, next_item = self.map.pop(key) # prev_item[2] = next_item # next_item[1] = prev_item # # def __iter__(self): # end = self.end # curr = end[2] # while curr is not end: # yield curr[0] # curr = curr[2] # # def __reversed__(self): # end = self.end # curr = end[1] # while curr is not end: # yield curr[0] # curr = curr[1] # # def pop(self, last=True): # if not self: # raise KeyError('set is empty') # key = self.end[1][0] if last else self.end[2][0] # self.discard(key) # return key # # def __repr__(self): # if not self: # return '{}()'.format(self.__class__.__name__,) # else: # return '{}({})'.format(self.__class__.__name__, list(self)) # # def __eq__(self, other): # if isinstance(other, OrderedSet): # return len(self) == len(other) and list(self) == list(other) # return set(self) == set(other) , which may include functions, classes, or code. Output only the next line.
('B', 'label b', 'd'),
Predict the next line after this snippet: <|code_start|> class DispatchersTestCase(TransactionTestCase): def test_state_dispatcher(self): m = TestDispatchersModel.objects.create() # Moving TestDispatcher model to SECOND state should create new TestSmartModel instance assert_equal(TestSmartModel.objects.count(), 0) change_and_save(m, state=TestDispatchersModel.STATE.SECOND) assert_equal(TestSmartModel.objects.count(), 1) # But subsequent saves should not create more instances change_and_save(m, state=TestDispatchersModel.STATE.SECOND) assert_equal(TestSmartModel.objects.count(), 1) # Moving back and forth between the states creates another instance change_and_save(m, state=TestDispatchersModel.STATE.FIRST) change_and_save(m, state=TestDispatchersModel.STATE.SECOND) assert_equal(TestSmartModel.objects.count(), 2) def test_property_dispatcher(self): # Saving the model should always fire up the one property handler, not the second <|code_end|> using the current file's imports: from nose.tools import raises # pylint: disable=E0401 from django.core.exceptions import ImproperlyConfigured from django.test import TransactionTestCase from django.db import transaction from chamber.models.dispatchers import BaseDispatcher, StateDispatcher from chamber.shortcuts import change_and_save from germanium.tools import assert_equal # pylint: disable=E0401 from test_chamber.models import ( CSVRecord, TestDispatchersModel, TestFieldsModel, TestSmartModel, TestOnDispatchModel ) # pylint: disable=E0401 and any relevant context from other files: # Path: chamber/models/dispatchers.py # class BaseDispatcher: # """ # Base dispatcher class that can be subclassed to call a handler based on a change in some a SmartModel. # If you subclass, be sure the __call__ method does not change signature. # """ # # signal = None # # def __init__(self, handler, signal=None): # self.handler = handler # assert (isinstance(handler, types.FunctionType) # or isinstance(handler, BaseHandler)), 'Handler must be function or instance of ' \ # 'chamber.models.handlers.BaseHandler, {}: {}'.format(self, # handler) # self._connected = defaultdict(list) # self._signal = signal if signal is not None else self.signal # # def connect(self, sender): # self._signal.connect(self, sender=sender) # # def __call__(self, instance, **kwargs): # """ # `instance` ... instance of the SmartModel where the handler is being called # Some dispatchers require additional params to evaluate the handler can be dispatched, # these are hidden in args and kwargs. # """ # if self._can_dispatch(instance, **kwargs): # self.handler(instance=instance, **kwargs) # # def _can_dispatch(self, instance, *args, **kwargs): # raise NotImplementedError # # class StateDispatcher(BaseDispatcher): # """ # Use this class to register a handler for transition of a model to a certain state. # """ # # def _validate_init_params(self): # super()._validate_init_params() # if self.field_value not in {value for value, _ in self.enum.choices}: # raise ImproperlyConfigured('Enum of FieldDispatcher does not contain {}.'.format(self.field_value)) # # def __init__(self, handler, enum, field, field_value, signal=None): # self.enum = enum # self.field = field # self.field_value = field_value # super().__init__(handler, signal=signal) # # def _can_dispatch(self, instance, changed, changed_fields, *args, **kwargs): # return ( # self.field.get_attname() in changed_fields and # getattr(instance, self.field.get_attname()) == self.field_value # ) # # Path: chamber/shortcuts.py # def change_and_save(obj, update_only_changed_fields=False, save_kwargs=None, **changed_fields): # """ # Changes a given `changed_fields` on object, saves it and returns changed object. # """ # from chamber.models import SmartModel # # save_kwargs = save_kwargs if save_kwargs is not None else {} # if update_only_changed_fields: # if isinstance(obj, SmartModel): # save_kwargs['update_only_changed_fields'] = True # else: # save_kwargs['update_fields'] = get_update_fields(obj, **changed_fields) # # change(obj, **changed_fields) # obj.save(**save_kwargs) # return obj . Output only the next line.
assert_equal(TestFieldsModel.objects.count(), 0)
Next line prediction: <|code_start|> __all__ = ( 'FormFieldsTestCase', ) class FormFieldsTestCase(TransactionTestCase): def test_decimal_field_should_return_correct_widget_attrs(self): kwargs = { 'step': 0.5, 'min': 1.0, 'max': 10.0, } field = DecimalField(**kwargs) widget_attrs = field.widget_attrs(TextInput()) assert_true(len(widget_attrs.keys()) > 0) <|code_end|> . Use current file imports: (import os from django.conf import settings from django.core.files.uploadedfile import SimpleUploadedFile from django.forms import TextInput, ValidationError from django.test import TransactionTestCase from germanium.tools import assert_equal, assert_true, assert_raises, assert_not_raises # pylint: disable=E0401 from chamber.forms.fields import DecimalField, RestrictedFileField) and context including class names, function names, or small code snippets from other files: # Path: chamber/forms/fields.py # class DecimalField(forms.DecimalField): # # def __init__(self, *args, **kwargs): # self.step = kwargs.pop('step', 'any') # self.min = kwargs.pop('min', None) # self.max = kwargs.pop('max', None) # super().__init__(*args, **kwargs) # # def widget_attrs(self, widget): # attrs = super().widget_attrs(widget) # attrs['step'] = self.step # if self.min is not None: # attrs['min'] = self.min # if self.max is not None: # attrs['max'] = self.max # return attrs # # class RestrictedFileField(forms.FileField): # # def __init__(self, *args, **kwargs): # max_upload_size = kwargs.pop('max_upload_size', settings.MAX_FILE_UPLOAD_SIZE) * 1024 * 1024 # allowed_content_types = kwargs.pop('allowed_content_types', None) # # validators = tuple(kwargs.pop('validators', [])) + ( # RestrictedFileValidator(max_upload_size), # ) # if allowed_content_types: # validators += ( # AllowedContentTypesByFilenameFileValidator(allowed_content_types), # AllowedContentTypesByContentFileValidator(allowed_content_types), # ) # super().__init__(validators=validators, *args, **kwargs) . Output only the next line.
for attr, value in kwargs.items():
Predict the next line after this snippet: <|code_start|> __all__ = ( 'FormFieldsTestCase', ) class FormFieldsTestCase(TransactionTestCase): def test_decimal_field_should_return_correct_widget_attrs(self): kwargs = { 'step': 0.5, 'min': 1.0, 'max': 10.0, } field = DecimalField(**kwargs) widget_attrs = field.widget_attrs(TextInput()) assert_true(len(widget_attrs.keys()) > 0) for attr, value in kwargs.items(): assert_equal(value, widget_attrs[attr]) def test_decimal_field_should_return_default_attrs(self): field = DecimalField() widget_attrs = field.widget_attrs(TextInput()) assert_equal({'step': 'any'}, widget_attrs) <|code_end|> using the current file's imports: import os from django.conf import settings from django.core.files.uploadedfile import SimpleUploadedFile from django.forms import TextInput, ValidationError from django.test import TransactionTestCase from germanium.tools import assert_equal, assert_true, assert_raises, assert_not_raises # pylint: disable=E0401 from chamber.forms.fields import DecimalField, RestrictedFileField and any relevant context from other files: # Path: chamber/forms/fields.py # class DecimalField(forms.DecimalField): # # def __init__(self, *args, **kwargs): # self.step = kwargs.pop('step', 'any') # self.min = kwargs.pop('min', None) # self.max = kwargs.pop('max', None) # super().__init__(*args, **kwargs) # # def widget_attrs(self, widget): # attrs = super().widget_attrs(widget) # attrs['step'] = self.step # if self.min is not None: # attrs['min'] = self.min # if self.max is not None: # attrs['max'] = self.max # return attrs # # class RestrictedFileField(forms.FileField): # # def __init__(self, *args, **kwargs): # max_upload_size = kwargs.pop('max_upload_size', settings.MAX_FILE_UPLOAD_SIZE) * 1024 * 1024 # allowed_content_types = kwargs.pop('allowed_content_types', None) # # validators = tuple(kwargs.pop('validators', [])) + ( # RestrictedFileValidator(max_upload_size), # ) # if allowed_content_types: # validators += ( # AllowedContentTypesByFilenameFileValidator(allowed_content_types), # AllowedContentTypesByContentFileValidator(allowed_content_types), # ) # super().__init__(validators=validators, *args, **kwargs) . Output only the next line.
def test_restricted_file_field_should_raise_validation_error_for_invalid_files(self):
Predict the next line for this snippet: <|code_start|> singleton = SingletonObject() assert_equal(singleton.num_singletons, 1) singleton = SingletonObject() assert_equal(singleton.num_singletons, 1) def test_translation_activate_block(self): @translation_activate_block(language='en') def en_block(): assert_equal(get_language(), 'en') assert_equal(get_language(), 'cs') en_block() assert_equal(get_language(), 'cs') def test_smat_atomic_should_be_to_use_as_a_decorator(self): @smart_atomic def change_object_and_raise_exception(): CSVRecord.objects.create( name='test', number=1 ) raise RuntimeError('test') with assert_raises(RuntimeError): change_object_and_raise_exception() assert_false(CSVRecord.objects.exists()) def test_smart_atomic_should_be_to_use_as_a_context_manager(self): <|code_end|> with the help of current file imports: from django.test import TestCase from django.utils.translation import get_language from chamber.utils.decorators import classproperty, singleton, translation_activate_block from chamber.utils.transaction import smart_atomic from germanium.tools import assert_equal, assert_raises, assert_false # pylint: disable=E0401 from test_chamber.models import CSVRecord and context from other files: # Path: chamber/utils/decorators.py # class classproperty(property): # # def __get__(self, cls, owner): # return self.fget.__get__(None, owner)() # # def singleton(klass): # """ # Create singleton from class # """ # instances = {} # # def getinstance(*args, **kwargs): # if klass not in instances: # instances[klass] = klass(*args, **kwargs) # return instances[klass] # return wraps(klass)(getinstance) # # def translation_activate_block(function=None, language=None): # """ # Activate language only for one method or function # """ # # def _translation_activate_block(function): # def _decorator(*args, **kwargs): # tmp_language = translation.get_language() # try: # translation.activate(language or settings.LANGUAGE_CODE) # return function(*args, **kwargs) # finally: # translation.activate(tmp_language) # return wraps(function)(_decorator) # # if function: # return _translation_activate_block(function) # else: # return _translation_activate_block # # Path: chamber/utils/transaction.py # def smart_atomic(using=None, savepoint=True, ignore_errors=None, reversion=True, reversion_using=None): # """ # Decorator and context manager that overrides django atomic decorator and automatically adds create revision. # The _atomic closure is required to achieve save ContextDecorator that nest more inner context decorator. # More here https://stackoverflow.com/questions/45589718/combine-two-context-managers-into-one # """ # # ignore_errors = () if ignore_errors is None else ignore_errors # # @contextmanager # def _atomic(using=None, savepoint=True, reversion=True, reversion_using=None): # try: # from reversion.revisions import create_revision # except ImportError: # reversion = False # # if not reversion: # @contextmanager # noqa: F811 # def create_revision(*args, **kwargs): # noqa: F811 # yield # # error = None # with transaction.atomic(using, savepoint), create_revision(using=reversion_using): # try: # yield # except ignore_errors as ex: # error = ex # # if error: # raise error # pylint: disable=E0702 # # if callable(using): # return _atomic(DEFAULT_DB_ALIAS, savepoint, reversion, reversion_using)(using) # else: # return _atomic(using, savepoint, reversion, reversion_using) , which may contain function names, class names, or code. Output only the next line.
with assert_raises(RuntimeError):
Given the following code snippet before the placeholder: <|code_start|> @classmethod def class_method_property(cls): return 1 @singleton class SingletonObject(object): num_singletons = 0 def __init__(self): self.num_singletons += 1 super(self.__class__, self).__init__() def get_count_singletons(self): return self.num_singletons class DecoratorsTestCase(TestCase): def test_class_property(self): assert_equal(ObjectWithClassProperty.class_method_property, 1) assert_equal(ObjectWithClassProperty().class_method_property, 1) def test_singleton(self): singleton = SingletonObject() assert_equal(singleton.num_singletons, 1) singleton = SingletonObject() assert_equal(singleton.num_singletons, 1) <|code_end|> , predict the next line using imports from the current file: from django.test import TestCase from django.utils.translation import get_language from chamber.utils.decorators import classproperty, singleton, translation_activate_block from chamber.utils.transaction import smart_atomic from germanium.tools import assert_equal, assert_raises, assert_false # pylint: disable=E0401 from test_chamber.models import CSVRecord and context including class names, function names, and sometimes code from other files: # Path: chamber/utils/decorators.py # class classproperty(property): # # def __get__(self, cls, owner): # return self.fget.__get__(None, owner)() # # def singleton(klass): # """ # Create singleton from class # """ # instances = {} # # def getinstance(*args, **kwargs): # if klass not in instances: # instances[klass] = klass(*args, **kwargs) # return instances[klass] # return wraps(klass)(getinstance) # # def translation_activate_block(function=None, language=None): # """ # Activate language only for one method or function # """ # # def _translation_activate_block(function): # def _decorator(*args, **kwargs): # tmp_language = translation.get_language() # try: # translation.activate(language or settings.LANGUAGE_CODE) # return function(*args, **kwargs) # finally: # translation.activate(tmp_language) # return wraps(function)(_decorator) # # if function: # return _translation_activate_block(function) # else: # return _translation_activate_block # # Path: chamber/utils/transaction.py # def smart_atomic(using=None, savepoint=True, ignore_errors=None, reversion=True, reversion_using=None): # """ # Decorator and context manager that overrides django atomic decorator and automatically adds create revision. # The _atomic closure is required to achieve save ContextDecorator that nest more inner context decorator. # More here https://stackoverflow.com/questions/45589718/combine-two-context-managers-into-one # """ # # ignore_errors = () if ignore_errors is None else ignore_errors # # @contextmanager # def _atomic(using=None, savepoint=True, reversion=True, reversion_using=None): # try: # from reversion.revisions import create_revision # except ImportError: # reversion = False # # if not reversion: # @contextmanager # noqa: F811 # def create_revision(*args, **kwargs): # noqa: F811 # yield # # error = None # with transaction.atomic(using, savepoint), create_revision(using=reversion_using): # try: # yield # except ignore_errors as ex: # error = ex # # if error: # raise error # pylint: disable=E0702 # # if callable(using): # return _atomic(DEFAULT_DB_ALIAS, savepoint, reversion, reversion_using)(using) # else: # return _atomic(using, savepoint, reversion, reversion_using) . Output only the next line.
def test_translation_activate_block(self):
Predict the next line for this snippet: <|code_start|> def get_count_singletons(self): return self.num_singletons class DecoratorsTestCase(TestCase): def test_class_property(self): assert_equal(ObjectWithClassProperty.class_method_property, 1) assert_equal(ObjectWithClassProperty().class_method_property, 1) def test_singleton(self): singleton = SingletonObject() assert_equal(singleton.num_singletons, 1) singleton = SingletonObject() assert_equal(singleton.num_singletons, 1) def test_translation_activate_block(self): @translation_activate_block(language='en') def en_block(): assert_equal(get_language(), 'en') assert_equal(get_language(), 'cs') en_block() assert_equal(get_language(), 'cs') def test_smat_atomic_should_be_to_use_as_a_decorator(self): @smart_atomic def change_object_and_raise_exception(): CSVRecord.objects.create( <|code_end|> with the help of current file imports: from django.test import TestCase from django.utils.translation import get_language from chamber.utils.decorators import classproperty, singleton, translation_activate_block from chamber.utils.transaction import smart_atomic from germanium.tools import assert_equal, assert_raises, assert_false # pylint: disable=E0401 from test_chamber.models import CSVRecord and context from other files: # Path: chamber/utils/decorators.py # class classproperty(property): # # def __get__(self, cls, owner): # return self.fget.__get__(None, owner)() # # def singleton(klass): # """ # Create singleton from class # """ # instances = {} # # def getinstance(*args, **kwargs): # if klass not in instances: # instances[klass] = klass(*args, **kwargs) # return instances[klass] # return wraps(klass)(getinstance) # # def translation_activate_block(function=None, language=None): # """ # Activate language only for one method or function # """ # # def _translation_activate_block(function): # def _decorator(*args, **kwargs): # tmp_language = translation.get_language() # try: # translation.activate(language or settings.LANGUAGE_CODE) # return function(*args, **kwargs) # finally: # translation.activate(tmp_language) # return wraps(function)(_decorator) # # if function: # return _translation_activate_block(function) # else: # return _translation_activate_block # # Path: chamber/utils/transaction.py # def smart_atomic(using=None, savepoint=True, ignore_errors=None, reversion=True, reversion_using=None): # """ # Decorator and context manager that overrides django atomic decorator and automatically adds create revision. # The _atomic closure is required to achieve save ContextDecorator that nest more inner context decorator. # More here https://stackoverflow.com/questions/45589718/combine-two-context-managers-into-one # """ # # ignore_errors = () if ignore_errors is None else ignore_errors # # @contextmanager # def _atomic(using=None, savepoint=True, reversion=True, reversion_using=None): # try: # from reversion.revisions import create_revision # except ImportError: # reversion = False # # if not reversion: # @contextmanager # noqa: F811 # def create_revision(*args, **kwargs): # noqa: F811 # yield # # error = None # with transaction.atomic(using, savepoint), create_revision(using=reversion_using): # try: # yield # except ignore_errors as ex: # error = ex # # if error: # raise error # pylint: disable=E0702 # # if callable(using): # return _atomic(DEFAULT_DB_ALIAS, savepoint, reversion, reversion_using)(using) # else: # return _atomic(using, savepoint, reversion, reversion_using) , which may contain function names, class names, or code. Output only the next line.
name='test',
Given snippet: <|code_start|> def test_singleton(self): singleton = SingletonObject() assert_equal(singleton.num_singletons, 1) singleton = SingletonObject() assert_equal(singleton.num_singletons, 1) def test_translation_activate_block(self): @translation_activate_block(language='en') def en_block(): assert_equal(get_language(), 'en') assert_equal(get_language(), 'cs') en_block() assert_equal(get_language(), 'cs') def test_smat_atomic_should_be_to_use_as_a_decorator(self): @smart_atomic def change_object_and_raise_exception(): CSVRecord.objects.create( name='test', number=1 ) raise RuntimeError('test') with assert_raises(RuntimeError): change_object_and_raise_exception() assert_false(CSVRecord.objects.exists()) <|code_end|> , continue by predicting the next line. Consider current file imports: from django.test import TestCase from django.utils.translation import get_language from chamber.utils.decorators import classproperty, singleton, translation_activate_block from chamber.utils.transaction import smart_atomic from germanium.tools import assert_equal, assert_raises, assert_false # pylint: disable=E0401 from test_chamber.models import CSVRecord and context: # Path: chamber/utils/decorators.py # class classproperty(property): # # def __get__(self, cls, owner): # return self.fget.__get__(None, owner)() # # def singleton(klass): # """ # Create singleton from class # """ # instances = {} # # def getinstance(*args, **kwargs): # if klass not in instances: # instances[klass] = klass(*args, **kwargs) # return instances[klass] # return wraps(klass)(getinstance) # # def translation_activate_block(function=None, language=None): # """ # Activate language only for one method or function # """ # # def _translation_activate_block(function): # def _decorator(*args, **kwargs): # tmp_language = translation.get_language() # try: # translation.activate(language or settings.LANGUAGE_CODE) # return function(*args, **kwargs) # finally: # translation.activate(tmp_language) # return wraps(function)(_decorator) # # if function: # return _translation_activate_block(function) # else: # return _translation_activate_block # # Path: chamber/utils/transaction.py # def smart_atomic(using=None, savepoint=True, ignore_errors=None, reversion=True, reversion_using=None): # """ # Decorator and context manager that overrides django atomic decorator and automatically adds create revision. # The _atomic closure is required to achieve save ContextDecorator that nest more inner context decorator. # More here https://stackoverflow.com/questions/45589718/combine-two-context-managers-into-one # """ # # ignore_errors = () if ignore_errors is None else ignore_errors # # @contextmanager # def _atomic(using=None, savepoint=True, reversion=True, reversion_using=None): # try: # from reversion.revisions import create_revision # except ImportError: # reversion = False # # if not reversion: # @contextmanager # noqa: F811 # def create_revision(*args, **kwargs): # noqa: F811 # yield # # error = None # with transaction.atomic(using, savepoint), create_revision(using=reversion_using): # try: # yield # except ignore_errors as ex: # error = ex # # if error: # raise error # pylint: disable=E0702 # # if callable(using): # return _atomic(DEFAULT_DB_ALIAS, savepoint, reversion, reversion_using)(using) # else: # return _atomic(using, savepoint, reversion, reversion_using) which might include code, classes, or functions. Output only the next line.
def test_smart_atomic_should_be_to_use_as_a_context_manager(self):
Given the code snippet: <|code_start|> def skip_unreadable_post(record): if record.exc_info: exc_type, exc_value = record.exc_info[:2] if isinstance(exc_value, UnreadablePostError): return False return True class AppendExtraJSONHandler(logging.StreamHandler): DEFAULT_STREAM_HANDLER_VARIABLE_KEYS = { 'name', 'msg', 'args', 'levelname', 'levelno', 'pathname', 'filename', 'module', 'exc_info', 'exc_text', 'stack_info', 'lineno', 'funcName', 'created', 'msecs', 'relativeCreated', 'thread', 'threadName', 'processName', 'process', } CUSTOM_STREAM_HANDLER_VARIABLE_KEYS = {'hostname'} def emit(self, record): <|code_end|> , generate the next line using the imports in this file: import json import logging import platform from django.http import UnreadablePostError from chamber.utils.json import ChamberJSONEncoder and context (functions, classes, or occasionally code) from other files: # Path: chamber/utils/json.py # class ChamberJSONEncoder(DjangoJSONEncoder): # # def default(self, val): # try: # return super().default(val) # except TypeError: # # https://github.com/python/cpython/blob/v3.8.3/Lib/json/encoder.py#L160-L180 # return 'Unserializable value of "{}"'.format(str(type(val))) # except ValueError as ex: # # https://github.com/django/django/blob/2.2.14/django/core/serializers/json.py#L81-L104 # return str(ex) . Output only the next line.
extra = {
Given the code snippet: <|code_start|> class GetUserMixin: def get_user(self, user_id): UserModel = get_user_class() try: return UserModel._default_manager.get(pk=user_id) except UserModel.DoesNotExist: <|code_end|> , generate the next line using the imports in this file: from django.contrib.auth.backends import ModelBackend as OriginModelBackend from django.contrib.auth.models import Permission from chamber.multidomains.domain import get_user_class and context (functions, classes, or occasionally code) from other files: # Path: chamber/multidomains/domain.py # def get_user_class(): # return get_current_domain().user_class . Output only the next line.
return None
Using the snippet: <|code_start|> assert_equal(get_domain(settings.FRONTEND_SITE_ID).name, 'frontend') assert_raises(ImproperlyConfigured, get_domain, 3) def test_get_domain_url(self): assert_equal(get_domain(settings.BACKEND_SITE_ID).url, 'http://localhost:8000') assert_equal(get_domain(settings.FRONTEND_SITE_ID).url, 'https://localhost') def test_new_domain_port(self): assert_equal(Domain('testA', 'dj.backend_urls', 'test_chamber.BackendUser', protocol='http', hostname='localhost').port, 80) assert_equal(Domain('testB', 'dj.backend_urls', 'test_chamber.BackendUser', protocol='https', hostname='localhost').port, 443) assert_equal(Domain('testC', 'dj.backend_urls', 'test_chamber.BackendUser', protocol='http', hostname='localhost', port=443).port, 443) assert_equal(Domain('testD', 'dj.backend_urls', 'test_chamber.BackendUser', protocol='https', hostname='localhost', port=80).port, 80) assert_raises(ImproperlyConfigured, Domain, 'testF', 'dj.backend_urls', 'test_chamber.BackendUser', protocol='hbbs', hostname='localhost') assert_equal(Domain('testD', 'dj.backend_urls', 'test_chamber.BackendUser', url='https://localhost:80').port, 80) assert_equal(Domain('testD', 'dj.backend_urls', 'test_chamber.BackendUser', url='https://localhost').port, 443) assert_equal(Domain('testA', 'dj.backend_urls', 'test_chamber.BackendUser', protocol='http', hostname='localhost').url, 'http://localhost') assert_equal(Domain('testB', 'dj.backend_urls', 'test_chamber.BackendUser', protocol='https', hostname='localhost').url, 'https://localhost') assert_equal(Domain('testC', 'dj.backend_urls', 'test_chamber.BackendUser', protocol='http', hostname='localhost', port=443).url, 'http://localhost:443') assert_equal(Domain('testD', 'dj.backend_urls', 'test_chamber.BackendUser', <|code_end|> , determine the next line of code. You have imports: from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.test import TestCase from chamber.multidomains.domain import Domain, get_current_domain, get_domain, get_domain_choices, get_user_class from chamber.multidomains.urlresolvers import reverse from germanium.tools import assert_equal, assert_raises # pylint: disable=E0401 from test_chamber.models import BackendUser, FrontendUser # pylint: disable=E0401 and context (class names, function names, or code) available: # Path: chamber/multidomains/domain.py # class Domain: # # def __init__(self, name, urlconf=None, user_model=None, url=None, protocol=None, hostname=None, port=None): # self.name = name # self.protocol = protocol # self.hostname = hostname # self.urlconf = urlconf # self.port = port # # if url: # parsed_url = urlparse(url) # self.protocol, self.hostname, self.port = parsed_url.scheme, parsed_url.hostname, parsed_url.port # # if self.protocol is None: # raise ImproperlyConfigured('protocol must be set') # if self.hostname is None: # raise ImproperlyConfigured('hostname must be set') # # if self.port is None: # if self.protocol == 'http': # self.port = 80 # elif self.protocol == 'https': # self.port = 443 # else: # raise ImproperlyConfigured('port must be set') # self.user_model = user_model # # @property # def url(self): # return ('{}://{}'.format(self.protocol, self.hostname) # if (self.protocol == 'http' and self.port == 80) or (self.protocol == 'https' and self.port == 443) # else '{}://{}:{}'.format(self.protocol, self.hostname, self.port)) # # @property # def user_class(self): # return apps.get_model(*self.user_model.split('.', 1)) # # def get_current_domain(): # from django.conf import settings # # return get_domain(settings.SITE_ID) # # def get_domain(site_id): # from django.conf import settings # # if site_id in settings.DOMAINS: # return settings.DOMAINS.get(site_id) # else: # raise ImproperlyConfigured('Domain with ID "{}" does not exists'.format(site_id)) # # def get_domain_choices(): # from django.conf import settings # # return [(key, domain.name) for key, domain in settings.DOMAINS.items()] # # def get_user_class(): # return get_current_domain().user_class # # Path: chamber/multidomains/urlresolvers.py # def reverse(viewname, site_id=None, add_domain=False, urlconf=None, args=None, kwargs=None, current_app=None, # qs_kwargs=None): # from .domain import get_domain # # urlconf = (get_domain(site_id).urlconf # if site_id is not None and urlconf is None and settings.SITE_ID != site_id # else urlconf) # site_id = settings.SITE_ID if site_id is None else site_id # domain = get_domain(site_id).url if add_domain else '' # qs = '?{}'.format(urlencode(qs_kwargs)) if qs_kwargs else '' # return ''.join((domain, django_reverse(viewname, urlconf, args, kwargs, current_app), qs)) . Output only the next line.
protocol='https', hostname='localhost', port=80).url, 'https://localhost:80')
Predict the next line for this snippet: <|code_start|> assert_equal(Domain('testA', 'dj.backend_urls', 'test_chamber.BackendUser', protocol='http', hostname='localhost').port, 80) assert_equal(Domain('testB', 'dj.backend_urls', 'test_chamber.BackendUser', protocol='https', hostname='localhost').port, 443) assert_equal(Domain('testC', 'dj.backend_urls', 'test_chamber.BackendUser', protocol='http', hostname='localhost', port=443).port, 443) assert_equal(Domain('testD', 'dj.backend_urls', 'test_chamber.BackendUser', protocol='https', hostname='localhost', port=80).port, 80) assert_raises(ImproperlyConfigured, Domain, 'testF', 'dj.backend_urls', 'test_chamber.BackendUser', protocol='hbbs', hostname='localhost') assert_equal(Domain('testD', 'dj.backend_urls', 'test_chamber.BackendUser', url='https://localhost:80').port, 80) assert_equal(Domain('testD', 'dj.backend_urls', 'test_chamber.BackendUser', url='https://localhost').port, 443) assert_equal(Domain('testA', 'dj.backend_urls', 'test_chamber.BackendUser', protocol='http', hostname='localhost').url, 'http://localhost') assert_equal(Domain('testB', 'dj.backend_urls', 'test_chamber.BackendUser', protocol='https', hostname='localhost').url, 'https://localhost') assert_equal(Domain('testC', 'dj.backend_urls', 'test_chamber.BackendUser', protocol='http', hostname='localhost', port=443).url, 'http://localhost:443') assert_equal(Domain('testD', 'dj.backend_urls', 'test_chamber.BackendUser', protocol='https', hostname='localhost', port=80).url, 'https://localhost:80') def test_reverse(self): assert_equal(reverse('current-datetime'), '/current_time_backend/') assert_equal(reverse('current-datetime', site_id=settings.BACKEND_SITE_ID), '/current_time_backend/') assert_equal(reverse('current-datetime', site_id=settings.FRONTEND_SITE_ID), '/current_time_frontend/') assert_equal(reverse('current-datetime', site_id=settings.BACKEND_SITE_ID, add_domain=True), <|code_end|> with the help of current file imports: from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.test import TestCase from chamber.multidomains.domain import Domain, get_current_domain, get_domain, get_domain_choices, get_user_class from chamber.multidomains.urlresolvers import reverse from germanium.tools import assert_equal, assert_raises # pylint: disable=E0401 from test_chamber.models import BackendUser, FrontendUser # pylint: disable=E0401 and context from other files: # Path: chamber/multidomains/domain.py # class Domain: # # def __init__(self, name, urlconf=None, user_model=None, url=None, protocol=None, hostname=None, port=None): # self.name = name # self.protocol = protocol # self.hostname = hostname # self.urlconf = urlconf # self.port = port # # if url: # parsed_url = urlparse(url) # self.protocol, self.hostname, self.port = parsed_url.scheme, parsed_url.hostname, parsed_url.port # # if self.protocol is None: # raise ImproperlyConfigured('protocol must be set') # if self.hostname is None: # raise ImproperlyConfigured('hostname must be set') # # if self.port is None: # if self.protocol == 'http': # self.port = 80 # elif self.protocol == 'https': # self.port = 443 # else: # raise ImproperlyConfigured('port must be set') # self.user_model = user_model # # @property # def url(self): # return ('{}://{}'.format(self.protocol, self.hostname) # if (self.protocol == 'http' and self.port == 80) or (self.protocol == 'https' and self.port == 443) # else '{}://{}:{}'.format(self.protocol, self.hostname, self.port)) # # @property # def user_class(self): # return apps.get_model(*self.user_model.split('.', 1)) # # def get_current_domain(): # from django.conf import settings # # return get_domain(settings.SITE_ID) # # def get_domain(site_id): # from django.conf import settings # # if site_id in settings.DOMAINS: # return settings.DOMAINS.get(site_id) # else: # raise ImproperlyConfigured('Domain with ID "{}" does not exists'.format(site_id)) # # def get_domain_choices(): # from django.conf import settings # # return [(key, domain.name) for key, domain in settings.DOMAINS.items()] # # def get_user_class(): # return get_current_domain().user_class # # Path: chamber/multidomains/urlresolvers.py # def reverse(viewname, site_id=None, add_domain=False, urlconf=None, args=None, kwargs=None, current_app=None, # qs_kwargs=None): # from .domain import get_domain # # urlconf = (get_domain(site_id).urlconf # if site_id is not None and urlconf is None and settings.SITE_ID != site_id # else urlconf) # site_id = settings.SITE_ID if site_id is None else site_id # domain = get_domain(site_id).url if add_domain else '' # qs = '?{}'.format(urlencode(qs_kwargs)) if qs_kwargs else '' # return ''.join((domain, django_reverse(viewname, urlconf, args, kwargs, current_app), qs)) , which may contain function names, class names, or code. Output only the next line.
'http://localhost:8000/current_time_backend/')
Based on the snippet: <|code_start|> class MultidomainsTestCase(TestCase): def test_get_domain_choices(self): choices = get_domain_choices() assert_equal(len(choices), 2) assert_equal(choices[0][1], 'backend') assert_equal(choices[1][1], 'frontend') assert_equal(choices[0][0], 1) assert_equal(choices[1][0], 2) def test_get_current_user_class(self): assert_equal(get_user_class(), BackendUser) def test_get_user_class(self): assert_equal(get_domain(settings.BACKEND_SITE_ID).user_class, BackendUser) assert_equal(get_domain(settings.FRONTEND_SITE_ID).user_class, FrontendUser) def test_get_current_domain(self): assert_equal(get_current_domain().name, 'backend') def test_get_domain(self): assert_equal(get_domain(settings.BACKEND_SITE_ID).name, 'backend') assert_equal(get_domain(settings.FRONTEND_SITE_ID).name, 'frontend') assert_raises(ImproperlyConfigured, get_domain, 3) <|code_end|> , predict the immediate next line with the help of imports: from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.test import TestCase from chamber.multidomains.domain import Domain, get_current_domain, get_domain, get_domain_choices, get_user_class from chamber.multidomains.urlresolvers import reverse from germanium.tools import assert_equal, assert_raises # pylint: disable=E0401 from test_chamber.models import BackendUser, FrontendUser # pylint: disable=E0401 and context (classes, functions, sometimes code) from other files: # Path: chamber/multidomains/domain.py # class Domain: # # def __init__(self, name, urlconf=None, user_model=None, url=None, protocol=None, hostname=None, port=None): # self.name = name # self.protocol = protocol # self.hostname = hostname # self.urlconf = urlconf # self.port = port # # if url: # parsed_url = urlparse(url) # self.protocol, self.hostname, self.port = parsed_url.scheme, parsed_url.hostname, parsed_url.port # # if self.protocol is None: # raise ImproperlyConfigured('protocol must be set') # if self.hostname is None: # raise ImproperlyConfigured('hostname must be set') # # if self.port is None: # if self.protocol == 'http': # self.port = 80 # elif self.protocol == 'https': # self.port = 443 # else: # raise ImproperlyConfigured('port must be set') # self.user_model = user_model # # @property # def url(self): # return ('{}://{}'.format(self.protocol, self.hostname) # if (self.protocol == 'http' and self.port == 80) or (self.protocol == 'https' and self.port == 443) # else '{}://{}:{}'.format(self.protocol, self.hostname, self.port)) # # @property # def user_class(self): # return apps.get_model(*self.user_model.split('.', 1)) # # def get_current_domain(): # from django.conf import settings # # return get_domain(settings.SITE_ID) # # def get_domain(site_id): # from django.conf import settings # # if site_id in settings.DOMAINS: # return settings.DOMAINS.get(site_id) # else: # raise ImproperlyConfigured('Domain with ID "{}" does not exists'.format(site_id)) # # def get_domain_choices(): # from django.conf import settings # # return [(key, domain.name) for key, domain in settings.DOMAINS.items()] # # def get_user_class(): # return get_current_domain().user_class # # Path: chamber/multidomains/urlresolvers.py # def reverse(viewname, site_id=None, add_domain=False, urlconf=None, args=None, kwargs=None, current_app=None, # qs_kwargs=None): # from .domain import get_domain # # urlconf = (get_domain(site_id).urlconf # if site_id is not None and urlconf is None and settings.SITE_ID != site_id # else urlconf) # site_id = settings.SITE_ID if site_id is None else site_id # domain = get_domain(site_id).url if add_domain else '' # qs = '?{}'.format(urlencode(qs_kwargs)) if qs_kwargs else '' # return ''.join((domain, django_reverse(viewname, urlconf, args, kwargs, current_app), qs)) . Output only the next line.
def test_get_domain_url(self):
Given the code snippet: <|code_start|> class MultidomainsTestCase(TestCase): def test_get_domain_choices(self): choices = get_domain_choices() assert_equal(len(choices), 2) assert_equal(choices[0][1], 'backend') assert_equal(choices[1][1], 'frontend') assert_equal(choices[0][0], 1) assert_equal(choices[1][0], 2) def test_get_current_user_class(self): assert_equal(get_user_class(), BackendUser) def test_get_user_class(self): assert_equal(get_domain(settings.BACKEND_SITE_ID).user_class, BackendUser) assert_equal(get_domain(settings.FRONTEND_SITE_ID).user_class, FrontendUser) def test_get_current_domain(self): assert_equal(get_current_domain().name, 'backend') def test_get_domain(self): assert_equal(get_domain(settings.BACKEND_SITE_ID).name, 'backend') assert_equal(get_domain(settings.FRONTEND_SITE_ID).name, 'frontend') assert_raises(ImproperlyConfigured, get_domain, 3) <|code_end|> , generate the next line using the imports in this file: from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.test import TestCase from chamber.multidomains.domain import Domain, get_current_domain, get_domain, get_domain_choices, get_user_class from chamber.multidomains.urlresolvers import reverse from germanium.tools import assert_equal, assert_raises # pylint: disable=E0401 from test_chamber.models import BackendUser, FrontendUser # pylint: disable=E0401 and context (functions, classes, or occasionally code) from other files: # Path: chamber/multidomains/domain.py # class Domain: # # def __init__(self, name, urlconf=None, user_model=None, url=None, protocol=None, hostname=None, port=None): # self.name = name # self.protocol = protocol # self.hostname = hostname # self.urlconf = urlconf # self.port = port # # if url: # parsed_url = urlparse(url) # self.protocol, self.hostname, self.port = parsed_url.scheme, parsed_url.hostname, parsed_url.port # # if self.protocol is None: # raise ImproperlyConfigured('protocol must be set') # if self.hostname is None: # raise ImproperlyConfigured('hostname must be set') # # if self.port is None: # if self.protocol == 'http': # self.port = 80 # elif self.protocol == 'https': # self.port = 443 # else: # raise ImproperlyConfigured('port must be set') # self.user_model = user_model # # @property # def url(self): # return ('{}://{}'.format(self.protocol, self.hostname) # if (self.protocol == 'http' and self.port == 80) or (self.protocol == 'https' and self.port == 443) # else '{}://{}:{}'.format(self.protocol, self.hostname, self.port)) # # @property # def user_class(self): # return apps.get_model(*self.user_model.split('.', 1)) # # def get_current_domain(): # from django.conf import settings # # return get_domain(settings.SITE_ID) # # def get_domain(site_id): # from django.conf import settings # # if site_id in settings.DOMAINS: # return settings.DOMAINS.get(site_id) # else: # raise ImproperlyConfigured('Domain with ID "{}" does not exists'.format(site_id)) # # def get_domain_choices(): # from django.conf import settings # # return [(key, domain.name) for key, domain in settings.DOMAINS.items()] # # def get_user_class(): # return get_current_domain().user_class # # Path: chamber/multidomains/urlresolvers.py # def reverse(viewname, site_id=None, add_domain=False, urlconf=None, args=None, kwargs=None, current_app=None, # qs_kwargs=None): # from .domain import get_domain # # urlconf = (get_domain(site_id).urlconf # if site_id is not None and urlconf is None and settings.SITE_ID != site_id # else urlconf) # site_id = settings.SITE_ID if site_id is None else site_id # domain = get_domain(site_id).url if add_domain else '' # qs = '?{}'.format(urlencode(qs_kwargs)) if qs_kwargs else '' # return ''.join((domain, django_reverse(viewname, urlconf, args, kwargs, current_app), qs)) . Output only the next line.
def test_get_domain_url(self):
Given the code snippet: <|code_start|> class MultidomainsTestCase(TestCase): def test_get_domain_choices(self): choices = get_domain_choices() assert_equal(len(choices), 2) assert_equal(choices[0][1], 'backend') assert_equal(choices[1][1], 'frontend') assert_equal(choices[0][0], 1) assert_equal(choices[1][0], 2) def test_get_current_user_class(self): assert_equal(get_user_class(), BackendUser) def test_get_user_class(self): assert_equal(get_domain(settings.BACKEND_SITE_ID).user_class, BackendUser) assert_equal(get_domain(settings.FRONTEND_SITE_ID).user_class, FrontendUser) def test_get_current_domain(self): assert_equal(get_current_domain().name, 'backend') def test_get_domain(self): assert_equal(get_domain(settings.BACKEND_SITE_ID).name, 'backend') assert_equal(get_domain(settings.FRONTEND_SITE_ID).name, 'frontend') assert_raises(ImproperlyConfigured, get_domain, 3) <|code_end|> , generate the next line using the imports in this file: from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.test import TestCase from chamber.multidomains.domain import Domain, get_current_domain, get_domain, get_domain_choices, get_user_class from chamber.multidomains.urlresolvers import reverse from germanium.tools import assert_equal, assert_raises # pylint: disable=E0401 from test_chamber.models import BackendUser, FrontendUser # pylint: disable=E0401 and context (functions, classes, or occasionally code) from other files: # Path: chamber/multidomains/domain.py # class Domain: # # def __init__(self, name, urlconf=None, user_model=None, url=None, protocol=None, hostname=None, port=None): # self.name = name # self.protocol = protocol # self.hostname = hostname # self.urlconf = urlconf # self.port = port # # if url: # parsed_url = urlparse(url) # self.protocol, self.hostname, self.port = parsed_url.scheme, parsed_url.hostname, parsed_url.port # # if self.protocol is None: # raise ImproperlyConfigured('protocol must be set') # if self.hostname is None: # raise ImproperlyConfigured('hostname must be set') # # if self.port is None: # if self.protocol == 'http': # self.port = 80 # elif self.protocol == 'https': # self.port = 443 # else: # raise ImproperlyConfigured('port must be set') # self.user_model = user_model # # @property # def url(self): # return ('{}://{}'.format(self.protocol, self.hostname) # if (self.protocol == 'http' and self.port == 80) or (self.protocol == 'https' and self.port == 443) # else '{}://{}:{}'.format(self.protocol, self.hostname, self.port)) # # @property # def user_class(self): # return apps.get_model(*self.user_model.split('.', 1)) # # def get_current_domain(): # from django.conf import settings # # return get_domain(settings.SITE_ID) # # def get_domain(site_id): # from django.conf import settings # # if site_id in settings.DOMAINS: # return settings.DOMAINS.get(site_id) # else: # raise ImproperlyConfigured('Domain with ID "{}" does not exists'.format(site_id)) # # def get_domain_choices(): # from django.conf import settings # # return [(key, domain.name) for key, domain in settings.DOMAINS.items()] # # def get_user_class(): # return get_current_domain().user_class # # Path: chamber/multidomains/urlresolvers.py # def reverse(viewname, site_id=None, add_domain=False, urlconf=None, args=None, kwargs=None, current_app=None, # qs_kwargs=None): # from .domain import get_domain # # urlconf = (get_domain(site_id).urlconf # if site_id is not None and urlconf is None and settings.SITE_ID != site_id # else urlconf) # site_id = settings.SITE_ID if site_id is None else site_id # domain = get_domain(site_id).url if add_domain else '' # qs = '?{}'.format(urlencode(qs_kwargs)) if qs_kwargs else '' # return ''.join((domain, django_reverse(viewname, urlconf, args, kwargs, current_app), qs)) . Output only the next line.
def test_get_domain_url(self):
Continue the code snippet: <|code_start|> self._waiters = [] # Export the lock's acquire() and release() methods self.acquire = lock.acquire self.release = lock.release # If the lock defines _release_save() and/or _acquire_restore(), # these override the default implementations (which just call # release() and acquire() on the lock). Ditto for _is_owned(). try: self._release_save = lock._release_save except AttributeError: pass try: self._acquire_restore = lock._acquire_restore except AttributeError: pass try: self._is_owned = lock._is_owned except AttributeError: pass def wait(self, timeout=None): if not self._is_owned(): raise RuntimeError('cannot wait on un-acquired lock') waiter = Semaphore() waiter.acquire() self._waiters.append(waiter) saved_state = self._release_save() try: return waiter.acquire(timeout=timeout) <|code_end|> . Use current file imports: import evergreen from evergreen.timeout import Timeout and context (classes, functions, or code) from other files: # Path: evergreen/timeout.py # class Timeout(BaseException): # """Raises *exception* in the current task after *timeout* seconds. # # When *exception* is omitted or ``None``, the :class:`Timeout` instance # itself is raised. If *seconds* is None, the timer is not scheduled, and is # only useful if you're planning to raise it directly. # # Timeout objects are context managers, and so can be used in with statements. # When used in a with statement, if *exception* is ``False``, the timeout is # still raised, but the context manager suppresses it, so the code outside the # with-block won't see it. # """ # # def __init__(self, seconds=None, exception=None): # self.seconds = seconds # self.exception = exception # self._timer = None # # def start(self): # """Schedule the timeout. This is called on construction, so # it should not be called explicitly, unless the timer has been # canceled.""" # assert not self._timer, '%r is already started; to restart it, cancel it first' % self # loop = evergreen.current.loop # current = evergreen.current.task # if self.seconds is None or self.seconds < 0: # # "fake" timeout (never expires) # self._timer = None # elif self.exception is None or isinstance(self.exception, bool): # # timeout that raises self # self._timer = loop.call_later(self.seconds, self._timer_cb, current.throw, self) # else: # # regular timeout with user-provided exception # self._timer = loop.call_later(self.seconds, self._timer_cb, current.throw, self.exception) # # def _timer_cb(self, func, arg): # self._timer = None # func(arg) # # def cancel(self): # """If the timeout is pending, cancel it. If not using # Timeouts in ``with`` statements, always call cancel() in a # ``finally`` after the block of code that is getting timed out. # If not canceled, the timeout will be raised later on, in some # unexpected section of the application.""" # if self._timer is not None: # self._timer.cancel() # self._timer = None # # def __repr__(self): # if self.exception is None: # exception = '' # else: # exception = ' exception=%r' % self.exception # return '<%s at %s seconds=%s%s>' % ( # self.__class__.__name__, hex(id(self)), self.seconds, exception) # # def __str__(self): # if self.seconds is None: # return '' # if self.seconds == 1: # suffix = '' # else: # suffix = 's' # if self.exception is None or self.exception is True: # return '%s second%s' % (self.seconds, suffix) # elif self.exception is False: # return '%s second%s (silent)' % (self.seconds, suffix) # else: # return '%s second%s (%s)' % (self.seconds, suffix, self.exception) # # def __enter__(self): # if not self._timer: # self.start() # return self # # def __exit__(self, typ, value, tb): # self.cancel() # if value is self and self.exception is False: # return True . Output only the next line.
finally:
Based on the snippet: <|code_start|> class FooTimeout(Exception): pass class TimeoutTests(EvergreenTestCase): def test_with_timeout(self): def sleep(): with Timeout(0.01): evergreen.sleep(10) def func(): self.assertRaises(Timeout, sleep) evergreen.spawn(func) self.loop.run() def test_with_none_timeout(self): def sleep(): with Timeout(None): evergreen.sleep(0.01) def func(): sleep() evergreen.spawn(func) <|code_end|> , predict the immediate next line with the help of imports: from common import unittest, EvergreenTestCase from evergreen.timeout import Timeout import evergreen and context (classes, functions, sometimes code) from other files: # Path: evergreen/timeout.py # class Timeout(BaseException): # """Raises *exception* in the current task after *timeout* seconds. # # When *exception* is omitted or ``None``, the :class:`Timeout` instance # itself is raised. If *seconds* is None, the timer is not scheduled, and is # only useful if you're planning to raise it directly. # # Timeout objects are context managers, and so can be used in with statements. # When used in a with statement, if *exception* is ``False``, the timeout is # still raised, but the context manager suppresses it, so the code outside the # with-block won't see it. # """ # # def __init__(self, seconds=None, exception=None): # self.seconds = seconds # self.exception = exception # self._timer = None # # def start(self): # """Schedule the timeout. This is called on construction, so # it should not be called explicitly, unless the timer has been # canceled.""" # assert not self._timer, '%r is already started; to restart it, cancel it first' % self # loop = evergreen.current.loop # current = evergreen.current.task # if self.seconds is None or self.seconds < 0: # # "fake" timeout (never expires) # self._timer = None # elif self.exception is None or isinstance(self.exception, bool): # # timeout that raises self # self._timer = loop.call_later(self.seconds, self._timer_cb, current.throw, self) # else: # # regular timeout with user-provided exception # self._timer = loop.call_later(self.seconds, self._timer_cb, current.throw, self.exception) # # def _timer_cb(self, func, arg): # self._timer = None # func(arg) # # def cancel(self): # """If the timeout is pending, cancel it. If not using # Timeouts in ``with`` statements, always call cancel() in a # ``finally`` after the block of code that is getting timed out. # If not canceled, the timeout will be raised later on, in some # unexpected section of the application.""" # if self._timer is not None: # self._timer.cancel() # self._timer = None # # def __repr__(self): # if self.exception is None: # exception = '' # else: # exception = ' exception=%r' % self.exception # return '<%s at %s seconds=%s%s>' % ( # self.__class__.__name__, hex(id(self)), self.seconds, exception) # # def __str__(self): # if self.seconds is None: # return '' # if self.seconds == 1: # suffix = '' # else: # suffix = 's' # if self.exception is None or self.exception is True: # return '%s second%s' % (self.seconds, suffix) # elif self.exception is False: # return '%s second%s (silent)' % (self.seconds, suffix) # else: # return '%s second%s (%s)' % (self.seconds, suffix, self.exception) # # def __enter__(self): # if not self._timer: # self.start() # return self # # def __exit__(self, typ, value, tb): # self.cancel() # if value is self and self.exception is False: # return True . Output only the next line.
self.loop.run()
Given snippet: <|code_start|># # This file is part of Evergreen. See the NOTICE for more information. # from __future__ import absolute_import __all__ = ['Empty', 'Full', 'Queue', 'PriorityQueue', 'LifoQueue'] Empty = __queue__.Empty Full = __queue__.Full <|code_end|> , continue by predicting the next line. Consider current file imports: import heapq from collections import deque from six.moves import queue as __queue__ from evergreen.locks import Condition, Lock and context: # Path: evergreen/locks.py # class Condition(object): # # def __init__(self, lock=None): # if lock is None: # lock = RLock() # self._lock = lock # self._waiters = [] # # # Export the lock's acquire() and release() methods # self.acquire = lock.acquire # self.release = lock.release # # If the lock defines _release_save() and/or _acquire_restore(), # # these override the default implementations (which just call # # release() and acquire() on the lock). Ditto for _is_owned(). # try: # self._release_save = lock._release_save # except AttributeError: # pass # try: # self._acquire_restore = lock._acquire_restore # except AttributeError: # pass # try: # self._is_owned = lock._is_owned # except AttributeError: # pass # # def wait(self, timeout=None): # if not self._is_owned(): # raise RuntimeError('cannot wait on un-acquired lock') # waiter = Semaphore() # waiter.acquire() # self._waiters.append(waiter) # saved_state = self._release_save() # try: # return waiter.acquire(timeout=timeout) # finally: # self._acquire_restore(saved_state) # # def wait_for(self, predicate, timeout=None): # endtime = None # waittime = timeout # result = predicate() # if not result: # self.wait(waittime) # result = predicate() # return result # # def notify(self, n=1): # if not self._is_owned(): # raise RuntimeError('cannot wait on un-acquired lock') # _waiters = self._waiters # waiters = _waiters[:n] # for waiter in waiters: # waiter.release() # try: # _waiters.remove(waiter) # except ValueError: # pass # # def notify_all(self): # self.notify(len(self._waiters)) # # def _acquire_restore(self, state): # self._lock.acquire() # # def _release_save(self): # self._lock.release() # # def _is_owned(self): # # Return True if lock is owned by current_thread. # # This method is called only if __lock doesn't have _is_owned(). # if self._lock.acquire(False): # self._lock.release() # return False # else: # return True # # def __enter__(self): # return self._lock.__enter__() # # def __exit__(self, *args): # return self._lock.__exit__(*args) # # class Lock(Semaphore): # # def __init__(self): # super(Lock, self).__init__(value=1) which might include code, classes, or functions. Output only the next line.
class Queue(object):
Given the following code snippet before the placeholder: <|code_start|> assert not isinstance(func, Handler) obj = partial.__new__(cls, func, *args, **kw) obj._cancelled = False return obj def cancel(self): self._cancelled = True class Timer(Handler): def __new__(cls, handle, func, *args, **kw): obj = Handler.__new__(cls, func, *args, **kw) obj._timer_h = handle return obj def cancel(self): super(Timer, self).cancel() if self._timer_h and not self._timer_h.closed: loop = self._timer_h.loop.event_loop self._timer_h.close() loop._timers.remove(self._timer_h) self._timer_h = None class SignalHandler(Handler): def __new__(cls, handle, func, *args, **kw): obj = Handler.__new__(cls, func, *args, **kw) obj._signal_h = handle <|code_end|> , predict the next line using imports from the current file: import os import pyuv import sys import threading import traceback import signal from time import monotonic as _time from time import time as _time from collections import deque from fibers import Fiber from functools import partial from evergreen.core.socketpair import SocketPair from evergreen.core.threadpool import ThreadPool and context including class names, function names, and sometimes code from other files: # Path: evergreen/core/socketpair.py # class SocketPair(object): # # def __init__(self): # self._reader, self._writer = socketpair() # self._reader.setblocking(False) # self._writer.setblocking(False) # # def reader_fileno(self): # return self._reader.fileno() # # def writer_fileno(self): # return self._writer.fileno() # # def close(self): # self._reader.close() # self._writer.close() # # Path: evergreen/core/threadpool.py # class ThreadPool(object): # # def __init__(self, loop): # self.loop = loop # # def spawn(self, func, *args, **kwargs): # fut = Future() # work = _Work(func, *args, **kwargs) # def after(error): # if error is not None: # assert error == pyuv.errno.UV_ECANCELLED # return # if work.exc is not None: # fut.set_exception(work.exc) # else: # fut.set_result(work.result) # fut.set_running_or_notify_cancel() # self.loop._loop.queue_work(work, after) # return fut . Output only the next line.
return obj
Continue the code snippet: <|code_start|> RUN_DEFAULT = 1 RUN_FOREVER = 2 class EventLoop(object): def __init__(self): if getattr(_tls, 'loop', None) is not None: raise RuntimeError('cannot instantiate more than one event loop per thread') _tls.loop = self self._loop = pyuv.Loop() self._loop.excepthook = self._handle_error self._loop.event_loop = self self._threadpool = ThreadPool(self) self.task = Fiber(self._run_loop) self._destroyed = False self._started = False self._running = False self._fd_map = dict() self._signals = dict() self._timers = set() self._ready = deque() self._ready_processor = pyuv.Idle(self._loop) self._waker = pyuv.Async(self._loop, self._async_cb) self._waker.unref() <|code_end|> . Use current file imports: import os import pyuv import sys import threading import traceback import signal from time import monotonic as _time from time import time as _time from collections import deque from fibers import Fiber from functools import partial from evergreen.core.socketpair import SocketPair from evergreen.core.threadpool import ThreadPool and context (classes, functions, or code) from other files: # Path: evergreen/core/socketpair.py # class SocketPair(object): # # def __init__(self): # self._reader, self._writer = socketpair() # self._reader.setblocking(False) # self._writer.setblocking(False) # # def reader_fileno(self): # return self._reader.fileno() # # def writer_fileno(self): # return self._writer.fileno() # # def close(self): # self._reader.close() # self._writer.close() # # Path: evergreen/core/threadpool.py # class ThreadPool(object): # # def __init__(self, loop): # self.loop = loop # # def spawn(self, func, *args, **kwargs): # fut = Future() # work = _Work(func, *args, **kwargs) # def after(error): # if error is not None: # assert error == pyuv.errno.UV_ECANCELLED # return # if work.exc is not None: # fut.set_exception(work.exc) # else: # fut.set_result(work.result) # fut.set_running_or_notify_cancel() # self.loop._loop.queue_work(work, after) # return fut . Output only the next line.
self._install_signal_checker()
Predict the next line for this snippet: <|code_start|> class LocalTests(EvergreenTestCase): def test_local(self): tls = local() tls.foo = 42 <|code_end|> with the help of current file imports: from common import unittest, EvergreenTestCase from evergreen.local import local import evergreen and context from other files: # Path: evergreen/local.py # class local(object): # # def __getattribute__(self, attr): # local_dict = _get_local_dict() # try: # return local_dict[attr] # except KeyError: # raise AttributeError("'local' object has no attribute '%s'" % attr) # # def __setattr__(self, attr, value): # local_dict = _get_local_dict() # local_dict[attr] = value # # def __delattr__(self, attr): # local_dict = _get_local_dict() # try: # del local_dict[attr] # except KeyError: # raise AttributeError(attr) , which may contain function names, class names, or code. Output only the next line.
def func(x):
Continue the code snippet: <|code_start|> class EventTests(EvergreenTestCase): def test_event_simple(self): ev = Event() def waiter(): self.assertTrue(ev.wait()) <|code_end|> . Use current file imports: from common import unittest, EvergreenTestCase from evergreen.event import Event import evergreen and context (classes, functions, or code) from other files: # Path: evergreen/event.py # class Event(object): # # def __init__(self): # self._cond = Condition(Lock()) # self._flag = False # # def is_set(self): # return self._flag # # def set(self): # self._cond.acquire() # try: # self._flag = True # self._cond.notify_all() # finally: # self._cond.release() # # def clear(self): # self._cond.acquire() # try: # self._flag = False # finally: # self._cond.release() # # def wait(self, timeout=None): # self._cond.acquire() # try: # signaled = self._flag # if not signaled: # signaled = self._cond.wait(timeout) # return signaled # finally: # self._cond.release() . Output only the next line.
evergreen.spawn(waiter)
Given snippet: <|code_start|># # This file is part of Evergreen. See the NOTICE for more information. # from __future__ import absolute_import __all__ = ['select', 'error'] __patched__ = ['select'] error = __select__.error def get_fileno(obj): # The purpose of this function is to exactly replicate # the behavior of the select module when confronted with # abnormal filenos; the details are extensively tested in # the stdlib test/test_select.py. try: f = obj.fileno except AttributeError: if not isinstance(obj, six.integer_types): raise TypeError("Expected int or long, got " + type(obj)) return obj <|code_end|> , continue by predicting the next line. Consider current file imports: import six import evergreen import select as __select__ from evergreen.event import Event and context: # Path: evergreen/event.py # class Event(object): # # def __init__(self): # self._cond = Condition(Lock()) # self._flag = False # # def is_set(self): # return self._flag # # def set(self): # self._cond.acquire() # try: # self._flag = True # self._cond.notify_all() # finally: # self._cond.release() # # def clear(self): # self._cond.acquire() # try: # self._flag = False # finally: # self._cond.release() # # def wait(self, timeout=None): # self._cond.acquire() # try: # signaled = self._flag # if not signaled: # signaled = self._cond.wait(timeout) # return signaled # finally: # self._cond.release() which might include code, classes, or functions. Output only the next line.
else:
Predict the next line after this snippet: <|code_start|> def test_rlock(self): lock = locks.RLock() def func1(): lock.acquire() self.assertTrue(lock.acquire()) def func2(): self.assertFalse(lock.acquire(blocking=False)) evergreen.spawn(func1) evergreen.spawn(func2) self.loop.run() def test_condition(self): d = dummy() d.value = 0 cond = locks.Condition() def func1(): with cond: self.assertEqual(d.value, 0) cond.wait() self.assertEqual(d.value, 42) def func2(): with cond: d.value = 42 cond.notify_all() evergreen.spawn(func1) evergreen.spawn(func2) self.loop.run() def test_barrier(self): num_tasks = 10 <|code_end|> using the current file's imports: from common import dummy, unittest, EvergreenTestCase from evergreen import locks import evergreen and any relevant context from other files: # Path: evergreen/locks.py # class Semaphore(object): # class BoundedSemaphore(Semaphore): # class Lock(Semaphore): # class RLock(object): # class Condition(object): # class Barrier(object): # class BrokenBarrierError(RuntimeError): # def __init__(self, value=1): # def acquire(self, blocking=True, timeout=None): # def release(self): # def _notify_waiters(self): # def __enter__(self): # def __exit__(self, typ, val, tb): # def __init__(self, value=1): # def release(self): # def __init__(self): # def __init__(self): # def acquire(self, blocking=True, timeout=None): # def release(self): # def __enter__(self): # def __exit__(self, typ, value, tb): # def _acquire_restore(self, state): # def _release_save(self): # def _is_owned(self): # def __init__(self, lock=None): # def wait(self, timeout=None): # def wait_for(self, predicate, timeout=None): # def notify(self, n=1): # def notify_all(self): # def _acquire_restore(self, state): # def _release_save(self): # def _is_owned(self): # def __enter__(self): # def __exit__(self, *args): # def __init__(self, parties, action=None, timeout=None): # def wait(self, timeout=None): # def _enter(self): # def _release(self): # def _wait(self, timeout): # def _exit(self): # def reset(self): # def abort(self): # def _break(self): # def parties(self): # def n_waiting(self): # def broken(self): . Output only the next line.
d = dummy()
Here is a snippet: <|code_start|> loop = evergreen.EventLoop() class EchoServer(tcp.TCPServer): @evergreen.task def handle_connection(self, connection): print('client connected from {}'.format(connection.peername)) while True: data = connection.read_until('\n') if not data: break connection.write(data) print('connection closed') def main(): server = EchoServer() port = int(sys.argv[1] if len(sys.argv) > 1 else 1234) server.bind(('0.0.0.0', port)) <|code_end|> . Write the next line using the current file imports: import sys import evergreen from evergreen.io import tcp and context from other files: # Path: evergreen/io/tcp.py # class TCPStream(BaseStream): # class TCPClient(TCPStream): # class TCPConnection(TCPStream, StreamConnection): # class TCPServer(StreamServer): # def __init__(self, handle): # def sockname(self): # def peername(self): # def __init__(self): # def connect(self, target, source_address=None): # def __connect_cb(self, handle, error): # def __init__(self): # def sockname(self): # def _bind(self, address): # def _serve(self, backlog): # def _close(self): # def __listen_cb(self, handle, error): , which may include functions, classes, or code. Output only the next line.
print ('listening on {}'.format(server.sockname))
Given the code snippet: <|code_start|># # This file is part of Evergreen. See the NOTICE for more information. # __all__ = ['Event'] class Event(object): def __init__(self): self._cond = Condition(Lock()) self._flag = False def is_set(self): return self._flag def set(self): self._cond.acquire() try: self._flag = True <|code_end|> , generate the next line using the imports in this file: from evergreen.locks import Condition, Lock and context (functions, classes, or occasionally code) from other files: # Path: evergreen/locks.py # class Condition(object): # # def __init__(self, lock=None): # if lock is None: # lock = RLock() # self._lock = lock # self._waiters = [] # # # Export the lock's acquire() and release() methods # self.acquire = lock.acquire # self.release = lock.release # # If the lock defines _release_save() and/or _acquire_restore(), # # these override the default implementations (which just call # # release() and acquire() on the lock). Ditto for _is_owned(). # try: # self._release_save = lock._release_save # except AttributeError: # pass # try: # self._acquire_restore = lock._acquire_restore # except AttributeError: # pass # try: # self._is_owned = lock._is_owned # except AttributeError: # pass # # def wait(self, timeout=None): # if not self._is_owned(): # raise RuntimeError('cannot wait on un-acquired lock') # waiter = Semaphore() # waiter.acquire() # self._waiters.append(waiter) # saved_state = self._release_save() # try: # return waiter.acquire(timeout=timeout) # finally: # self._acquire_restore(saved_state) # # def wait_for(self, predicate, timeout=None): # endtime = None # waittime = timeout # result = predicate() # if not result: # self.wait(waittime) # result = predicate() # return result # # def notify(self, n=1): # if not self._is_owned(): # raise RuntimeError('cannot wait on un-acquired lock') # _waiters = self._waiters # waiters = _waiters[:n] # for waiter in waiters: # waiter.release() # try: # _waiters.remove(waiter) # except ValueError: # pass # # def notify_all(self): # self.notify(len(self._waiters)) # # def _acquire_restore(self, state): # self._lock.acquire() # # def _release_save(self): # self._lock.release() # # def _is_owned(self): # # Return True if lock is owned by current_thread. # # This method is called only if __lock doesn't have _is_owned(). # if self._lock.acquire(False): # self._lock.release() # return False # else: # return True # # def __enter__(self): # return self._lock.__enter__() # # def __exit__(self, *args): # return self._lock.__exit__(*args) # # class Lock(Semaphore): # # def __init__(self): # super(Lock, self).__init__(value=1) . Output only the next line.
self._cond.notify_all()
Given the code snippet: <|code_start|># # This file is part of Evergreen. See the NOTICE for more information. # __all__ = ['Event'] class Event(object): def __init__(self): self._cond = Condition(Lock()) <|code_end|> , generate the next line using the imports in this file: from evergreen.locks import Condition, Lock and context (functions, classes, or occasionally code) from other files: # Path: evergreen/locks.py # class Condition(object): # # def __init__(self, lock=None): # if lock is None: # lock = RLock() # self._lock = lock # self._waiters = [] # # # Export the lock's acquire() and release() methods # self.acquire = lock.acquire # self.release = lock.release # # If the lock defines _release_save() and/or _acquire_restore(), # # these override the default implementations (which just call # # release() and acquire() on the lock). Ditto for _is_owned(). # try: # self._release_save = lock._release_save # except AttributeError: # pass # try: # self._acquire_restore = lock._acquire_restore # except AttributeError: # pass # try: # self._is_owned = lock._is_owned # except AttributeError: # pass # # def wait(self, timeout=None): # if not self._is_owned(): # raise RuntimeError('cannot wait on un-acquired lock') # waiter = Semaphore() # waiter.acquire() # self._waiters.append(waiter) # saved_state = self._release_save() # try: # return waiter.acquire(timeout=timeout) # finally: # self._acquire_restore(saved_state) # # def wait_for(self, predicate, timeout=None): # endtime = None # waittime = timeout # result = predicate() # if not result: # self.wait(waittime) # result = predicate() # return result # # def notify(self, n=1): # if not self._is_owned(): # raise RuntimeError('cannot wait on un-acquired lock') # _waiters = self._waiters # waiters = _waiters[:n] # for waiter in waiters: # waiter.release() # try: # _waiters.remove(waiter) # except ValueError: # pass # # def notify_all(self): # self.notify(len(self._waiters)) # # def _acquire_restore(self, state): # self._lock.acquire() # # def _release_save(self): # self._lock.release() # # def _is_owned(self): # # Return True if lock is owned by current_thread. # # This method is called only if __lock doesn't have _is_owned(). # if self._lock.acquire(False): # self._lock.release() # return False # else: # return True # # def __enter__(self): # return self._lock.__enter__() # # def __exit__(self, *args): # return self._lock.__exit__(*args) # # class Lock(Semaphore): # # def __init__(self): # super(Lock, self).__init__(value=1) . Output only the next line.
self._flag = False
Given the following code snippet before the placeholder: <|code_start|> def raise_(self): six.reraise(self.type, self.value, self.traceback) class Channel(object): def __init__(self): self._send_lock = Lock() self._recv_lock = Lock() self._new_data = Event() self._recv_data = Event() self._data = None def send(self, data): with self._send_lock: self._data = data self._new_data.set() self._recv_data.wait() self._recv_data.clear() def send_exception(self, exc_type, exc_value=None, exc_tb=None): self.send(_Bomb(exc_type, exc_value, exc_tb)) def receive(self): with self._recv_lock: self._new_data.wait() data, self._data = self._data, None self._new_data.clear() self._recv_data.set() if isinstance(data, _Bomb): <|code_end|> , predict the next line using imports from the current file: import six from evergreen.event import Event from evergreen.locks import Lock and context including class names, function names, and sometimes code from other files: # Path: evergreen/event.py # class Event(object): # # def __init__(self): # self._cond = Condition(Lock()) # self._flag = False # # def is_set(self): # return self._flag # # def set(self): # self._cond.acquire() # try: # self._flag = True # self._cond.notify_all() # finally: # self._cond.release() # # def clear(self): # self._cond.acquire() # try: # self._flag = False # finally: # self._cond.release() # # def wait(self, timeout=None): # self._cond.acquire() # try: # signaled = self._flag # if not signaled: # signaled = self._cond.wait(timeout) # return signaled # finally: # self._cond.release() # # Path: evergreen/locks.py # class Lock(Semaphore): # # def __init__(self): # super(Lock, self).__init__(value=1) . Output only the next line.
data.raise_()
Using the snippet: <|code_start|> __all__ = ['Channel'] class _Bomb(object): def __init__(self, exp_type, exp_value=None, exp_traceback=None): self.type = exp_type self.value = exp_value if exp_value is not None else exp_type() self.traceback = exp_traceback def raise_(self): six.reraise(self.type, self.value, self.traceback) class Channel(object): def __init__(self): self._send_lock = Lock() self._recv_lock = Lock() self._new_data = Event() self._recv_data = Event() self._data = None def send(self, data): with self._send_lock: self._data = data self._new_data.set() <|code_end|> , determine the next line of code. You have imports: import six from evergreen.event import Event from evergreen.locks import Lock and context (class names, function names, or code) available: # Path: evergreen/event.py # class Event(object): # # def __init__(self): # self._cond = Condition(Lock()) # self._flag = False # # def is_set(self): # return self._flag # # def set(self): # self._cond.acquire() # try: # self._flag = True # self._cond.notify_all() # finally: # self._cond.release() # # def clear(self): # self._cond.acquire() # try: # self._flag = False # finally: # self._cond.release() # # def wait(self, timeout=None): # self._cond.acquire() # try: # signaled = self._flag # if not signaled: # signaled = self._cond.wait(timeout) # return signaled # finally: # self._cond.release() # # Path: evergreen/locks.py # class Lock(Semaphore): # # def __init__(self): # super(Lock, self).__init__(value=1) . Output only the next line.
self._recv_data.wait()
Given the following code snippet before the placeholder: <|code_start|># __all__ = ['UDPEndpoint', 'UDPError'] UDPError = pyuv.error.UDPError class UDPEndpoint(object): def __init__(self): loop = evergreen.current.loop self._handle = pyuv.UDP(loop._loop) self._closed = False self._receive_result = Result() self._pending_writes = 0 self._flush_event = Event() self._flush_event.set() self._sockname = None @property def sockname(self): self._check_closed() if self._sockname is None: self._sockname = self._handle.getsockname() return self._sockname def bind(self, addr): <|code_end|> , predict the next line using imports from the current file: import pyuv import evergreen from evergreen.core.utils import Result from evergreen.event import Event from evergreen.io import errno from evergreen.log import log and context including class names, function names, and sometimes code from other files: # Path: evergreen/core/utils.py # class Result(object): # """ # Result is an internal object which is meant to be used like a Future, but being more # lightweight and supporting a single waiter. Example: # # result = Result() # # def f1(): # with result: # some_async_func() # return result.get() # # def some_async_func(): # # this function runs in a different task # ... # result.set_value(42) # """ # # __slots__ = ['_lock', '_cond', '_locked', '_used', '_exc', '_value'] # # def __init__(self): # self._lock = Lock() # self._cond = Condition(Lock()) # self._locked = False # self._used = False # self._exc = self._value = Null # # def acquire(self): # self._lock.acquire() # self._locked = True # # def release(self): # self._lock.release() # self._locked = False # self._used = False # self._exc = self._value = Null # # def get(self): # assert self._locked # assert not self._used # try: # with self._cond: # if self._exc == self._value == Null: # self._cond.wait() # if self._exc != Null: # raise self._exc # assert self._value != Null # return self._value # finally: # self._used = True # self._exc = self._value = Null # # def set_value(self, value): # assert self._locked # assert not self._used # assert self._exc == self._value == Null # with self._cond: # self._value = value # self._cond.notify_all() # # def set_exception(self, value): # assert self._locked # assert not self._used # assert self._exc == self._value == Null # with self._cond: # self._exc = value # self._cond.notify_all() # # def __enter__(self): # self.acquire() # # def __exit__(self, typ, val, tb): # self.release() # # Path: evergreen/event.py # class Event(object): # # def __init__(self): # self._cond = Condition(Lock()) # self._flag = False # # def is_set(self): # return self._flag # # def set(self): # self._cond.acquire() # try: # self._flag = True # self._cond.notify_all() # finally: # self._cond.release() # # def clear(self): # self._cond.acquire() # try: # self._flag = False # finally: # self._cond.release() # # def wait(self, timeout=None): # self._cond.acquire() # try: # signaled = self._flag # if not signaled: # signaled = self._cond.wait(timeout) # return signaled # finally: # self._cond.release() # # Path: evergreen/io/errno.py # def _bootstrap(): # # Path: evergreen/log.py . Output only the next line.
self._check_closed()
Next line prediction: <|code_start|> def bind(self, addr): self._check_closed() self._handle.bind(addr) def send(self, data, addr): self._check_closed() self._handle.send(addr, data, self.__send_cb) if self._pending_writes == 0: self._flush_event.clear() self._pending_writes += 1 def receive(self): self._check_closed() with self._receive_result: self._handle.start_recv(self.__receive_cb) return self._receive_result.get() def flush(self): self._check_closed() self._flush_event.wait() def close(self): if self._closed: return self._closed = True self._handle.close() def _check_closed(self): if self._closed: <|code_end|> . Use current file imports: (import pyuv import evergreen from evergreen.core.utils import Result from evergreen.event import Event from evergreen.io import errno from evergreen.log import log) and context including class names, function names, or small code snippets from other files: # Path: evergreen/core/utils.py # class Result(object): # """ # Result is an internal object which is meant to be used like a Future, but being more # lightweight and supporting a single waiter. Example: # # result = Result() # # def f1(): # with result: # some_async_func() # return result.get() # # def some_async_func(): # # this function runs in a different task # ... # result.set_value(42) # """ # # __slots__ = ['_lock', '_cond', '_locked', '_used', '_exc', '_value'] # # def __init__(self): # self._lock = Lock() # self._cond = Condition(Lock()) # self._locked = False # self._used = False # self._exc = self._value = Null # # def acquire(self): # self._lock.acquire() # self._locked = True # # def release(self): # self._lock.release() # self._locked = False # self._used = False # self._exc = self._value = Null # # def get(self): # assert self._locked # assert not self._used # try: # with self._cond: # if self._exc == self._value == Null: # self._cond.wait() # if self._exc != Null: # raise self._exc # assert self._value != Null # return self._value # finally: # self._used = True # self._exc = self._value = Null # # def set_value(self, value): # assert self._locked # assert not self._used # assert self._exc == self._value == Null # with self._cond: # self._value = value # self._cond.notify_all() # # def set_exception(self, value): # assert self._locked # assert not self._used # assert self._exc == self._value == Null # with self._cond: # self._exc = value # self._cond.notify_all() # # def __enter__(self): # self.acquire() # # def __exit__(self, typ, val, tb): # self.release() # # Path: evergreen/event.py # class Event(object): # # def __init__(self): # self._cond = Condition(Lock()) # self._flag = False # # def is_set(self): # return self._flag # # def set(self): # self._cond.acquire() # try: # self._flag = True # self._cond.notify_all() # finally: # self._cond.release() # # def clear(self): # self._cond.acquire() # try: # self._flag = False # finally: # self._cond.release() # # def wait(self, timeout=None): # self._cond.acquire() # try: # signaled = self._flag # if not signaled: # signaled = self._cond.wait(timeout) # return signaled # finally: # self._cond.release() # # Path: evergreen/io/errno.py # def _bootstrap(): # # Path: evergreen/log.py . Output only the next line.
raise UDPError('endpoint is closed')
Given the following code snippet before the placeholder: <|code_start|> def __init__(self): loop = evergreen.current.loop self._handle = pyuv.UDP(loop._loop) self._closed = False self._receive_result = Result() self._pending_writes = 0 self._flush_event = Event() self._flush_event.set() self._sockname = None @property def sockname(self): self._check_closed() if self._sockname is None: self._sockname = self._handle.getsockname() return self._sockname def bind(self, addr): self._check_closed() self._handle.bind(addr) def send(self, data, addr): self._check_closed() self._handle.send(addr, data, self.__send_cb) if self._pending_writes == 0: self._flush_event.clear() self._pending_writes += 1 def receive(self): <|code_end|> , predict the next line using imports from the current file: import pyuv import evergreen from evergreen.core.utils import Result from evergreen.event import Event from evergreen.io import errno from evergreen.log import log and context including class names, function names, and sometimes code from other files: # Path: evergreen/core/utils.py # class Result(object): # """ # Result is an internal object which is meant to be used like a Future, but being more # lightweight and supporting a single waiter. Example: # # result = Result() # # def f1(): # with result: # some_async_func() # return result.get() # # def some_async_func(): # # this function runs in a different task # ... # result.set_value(42) # """ # # __slots__ = ['_lock', '_cond', '_locked', '_used', '_exc', '_value'] # # def __init__(self): # self._lock = Lock() # self._cond = Condition(Lock()) # self._locked = False # self._used = False # self._exc = self._value = Null # # def acquire(self): # self._lock.acquire() # self._locked = True # # def release(self): # self._lock.release() # self._locked = False # self._used = False # self._exc = self._value = Null # # def get(self): # assert self._locked # assert not self._used # try: # with self._cond: # if self._exc == self._value == Null: # self._cond.wait() # if self._exc != Null: # raise self._exc # assert self._value != Null # return self._value # finally: # self._used = True # self._exc = self._value = Null # # def set_value(self, value): # assert self._locked # assert not self._used # assert self._exc == self._value == Null # with self._cond: # self._value = value # self._cond.notify_all() # # def set_exception(self, value): # assert self._locked # assert not self._used # assert self._exc == self._value == Null # with self._cond: # self._exc = value # self._cond.notify_all() # # def __enter__(self): # self.acquire() # # def __exit__(self, typ, val, tb): # self.release() # # Path: evergreen/event.py # class Event(object): # # def __init__(self): # self._cond = Condition(Lock()) # self._flag = False # # def is_set(self): # return self._flag # # def set(self): # self._cond.acquire() # try: # self._flag = True # self._cond.notify_all() # finally: # self._cond.release() # # def clear(self): # self._cond.acquire() # try: # self._flag = False # finally: # self._cond.release() # # def wait(self, timeout=None): # self._cond.acquire() # try: # signaled = self._flag # if not signaled: # signaled = self._cond.wait(timeout) # return signaled # finally: # self._cond.release() # # Path: evergreen/io/errno.py # def _bootstrap(): # # Path: evergreen/log.py . Output only the next line.
self._check_closed()
Predict the next line for this snippet: <|code_start|> return self._sockname def bind(self, addr): self._check_closed() self._handle.bind(addr) def send(self, data, addr): self._check_closed() self._handle.send(addr, data, self.__send_cb) if self._pending_writes == 0: self._flush_event.clear() self._pending_writes += 1 def receive(self): self._check_closed() with self._receive_result: self._handle.start_recv(self.__receive_cb) return self._receive_result.get() def flush(self): self._check_closed() self._flush_event.wait() def close(self): if self._closed: return self._closed = True self._handle.close() def _check_closed(self): <|code_end|> with the help of current file imports: import pyuv import evergreen from evergreen.core.utils import Result from evergreen.event import Event from evergreen.io import errno from evergreen.log import log and context from other files: # Path: evergreen/core/utils.py # class Result(object): # """ # Result is an internal object which is meant to be used like a Future, but being more # lightweight and supporting a single waiter. Example: # # result = Result() # # def f1(): # with result: # some_async_func() # return result.get() # # def some_async_func(): # # this function runs in a different task # ... # result.set_value(42) # """ # # __slots__ = ['_lock', '_cond', '_locked', '_used', '_exc', '_value'] # # def __init__(self): # self._lock = Lock() # self._cond = Condition(Lock()) # self._locked = False # self._used = False # self._exc = self._value = Null # # def acquire(self): # self._lock.acquire() # self._locked = True # # def release(self): # self._lock.release() # self._locked = False # self._used = False # self._exc = self._value = Null # # def get(self): # assert self._locked # assert not self._used # try: # with self._cond: # if self._exc == self._value == Null: # self._cond.wait() # if self._exc != Null: # raise self._exc # assert self._value != Null # return self._value # finally: # self._used = True # self._exc = self._value = Null # # def set_value(self, value): # assert self._locked # assert not self._used # assert self._exc == self._value == Null # with self._cond: # self._value = value # self._cond.notify_all() # # def set_exception(self, value): # assert self._locked # assert not self._used # assert self._exc == self._value == Null # with self._cond: # self._exc = value # self._cond.notify_all() # # def __enter__(self): # self.acquire() # # def __exit__(self, typ, val, tb): # self.release() # # Path: evergreen/event.py # class Event(object): # # def __init__(self): # self._cond = Condition(Lock()) # self._flag = False # # def is_set(self): # return self._flag # # def set(self): # self._cond.acquire() # try: # self._flag = True # self._cond.notify_all() # finally: # self._cond.release() # # def clear(self): # self._cond.acquire() # try: # self._flag = False # finally: # self._cond.release() # # def wait(self, timeout=None): # self._cond.acquire() # try: # signaled = self._flag # if not signaled: # signaled = self._cond.wait(timeout) # return signaled # finally: # self._cond.release() # # Path: evergreen/io/errno.py # def _bootstrap(): # # Path: evergreen/log.py , which may contain function names, class names, or code. Output only the next line.
if self._closed:
Predict the next line after this snippet: <|code_start|> _counter = _counter + 1 return template % _counter class Task(Fiber): def __init__(self, target=None, name=None, args=(), kwargs={}): super(Task, self).__init__(target=self.__run, parent=evergreen.current.loop.task) self._name = str(name or _newname()) self._target = target self._args = args self._kwargs = kwargs self._started = False self._running = False self._exit_event = Event() def start(self): if self._started: raise RuntimeError('tasks can only be started once') self._started = True evergreen.current.loop.call_soon(self.switch) def run(self): if self._target: self._target(*self._args, **self._kwargs) def join(self, timeout=None): """Wait for this Task to end. If a timeout is given, after the time expires the function will return anyway.""" if not self._started: <|code_end|> using the current file's imports: import six import evergreen from evergreen.event import Event from fibers import Fiber and any relevant context from other files: # Path: evergreen/event.py # class Event(object): # # def __init__(self): # self._cond = Condition(Lock()) # self._flag = False # # def is_set(self): # return self._flag # # def set(self): # self._cond.acquire() # try: # self._flag = True # self._cond.notify_all() # finally: # self._cond.release() # # def clear(self): # self._cond.acquire() # try: # self._flag = False # finally: # self._cond.release() # # def wait(self, timeout=None): # self._cond.acquire() # try: # signaled = self._flag # if not signaled: # signaled = self._cond.wait(timeout) # return signaled # finally: # self._cond.release() . Output only the next line.
raise RuntimeError('cannot join task before it is started')
Next line prediction: <|code_start|> if parsed_node: ndict['children'].append(gcdict) nlist.append(ndict) ndict = {} ndict['title'] = graph.node.name ndict['children'] = [] parsed_node.append(graph.node) if graph.node.group not in parsed_group: if parsed_group: nlist.sort(key=lambda item: item['title'], reverse=False) grdict['children'] = nlist grlist.append(grdict) nlist = [] grdict = {} grdict['title'] = graph.node.group.name grdict['children'] = [] grdict['baseurl'] = common_start(graph.baseurl, graph.node.url) parsed_group.append(graph.node.group) if graph.graph.category.name not in parsed_graph_category: if parsed_graph_category: ndict['children'].append(gcdict) gcdict = {} gcdict['title'] = graph.graph.category.name gcdict['children'] = [] gcdict['nodeurl'] = graph.pageurl.replace(common_start(graph.baseurl, graph.node.url), '') parsed_graph_category.append(graph.graph.category.name) gdict = {} gdict['title'] = graph.graph.name gdict['url'] = graph.baseurl.replace(common_start(graph.baseurl, graph.node.url), '') <|code_end|> . Use current file imports: (import bz2 import json from django import template from muparse.models import SavedSearch, NodeGraphs, common_start from django.core.cache import cache) and context including class names, function names, or small code snippets from other files: # Path: muparse/models.py # class SavedSearch(models.Model): # description = models.CharField(max_length=255) # display_type = models.CharField(max_length=64) # graphs = models.ManyToManyField(NodeGraphs, blank=True, null=True) # user = models.ForeignKey(User) # default = models.BooleanField(default=False) # # def get_absolute_url(self): # return reverse('load_search', kwargs={'search_id': self.id}) # # def get_delete_url(self): # return reverse('delete_search', kwargs={'search_id': self.id}) # # def get_default_url(self): # return reverse('default_search', kwargs={'search_id': self.id}) # # def __unicode__(self): # return self.description # # class Meta: # verbose_name_plural = "Saved Searches" # # class NodeGraphs(models.Model): # node = models.ForeignKey(Node) # graph = models.ForeignKey(Graph) # baseurl = models.CharField(max_length=512) # pageurl = models.CharField(max_length=512) # updated = models.DateTimeField(auto_now=True) # # def img_url(self): # return '%s-day.png' % self.baseurl # # def __unicode__(self): # return u'%s:%s:%s' % (self.node, self.graph, self.baseurl) # # class Meta: # verbose_name_plural = "Node Graphs" # # def common_start(sa, sb): # ''' # returns the longest common substring from the beginning of sa and sb # ''' # def _iter(): # for a, b in zip(sa, sb): # if a == b: # yield a # else: # return # # return ''.join(_iter()) . Output only the next line.
gdict['key'] = 'graph_%s' % (graph.pk)
Here is a snippet: <|code_start|> nlist.append(ndict) nlist.sort(key=lambda item: item['title'], reverse=False) grdict['children'] = nlist grlist.append(grdict) ndict['children'].append(gcdict) glist = json.dumps(grlist) cache.set('user_%s_tree' % (request.user.pk), bz2.compress(glist), 60 * 60 * 24 *5) return {'nodes': grlist} @register.inclusion_tag('partial/graphs.html', takes_context=True) def load_graphs_by_type(context): request = context.get('request') glist = cache.get('user_%s_tree_cat' % (request.user.pk)) if glist: grlist = json.loads(bz2.decompress(glist)) else: grlist = [] gcdict = {} parsed_group = [] parsed_graph_category = [] parsed_graph_name = [] graphs = NodeGraphs.objects.all().select_related('node', 'graph', 'node__group', 'graph__category').order_by('graph__category__name', 'graph__name', 'node__group', 'node__name') if not request.user.is_superuser: nodes = request.user.get_profile().nodes.all() graphs = graphs.filter(node__in=nodes) len_graphs = len(graphs) for index, graph in enumerate(graphs): if graph.graph.category.name not in parsed_graph_category: if parsed_graph_category: <|code_end|> . Write the next line using the current file imports: import bz2 import json from django import template from muparse.models import SavedSearch, NodeGraphs, common_start from django.core.cache import cache and context from other files: # Path: muparse/models.py # class SavedSearch(models.Model): # description = models.CharField(max_length=255) # display_type = models.CharField(max_length=64) # graphs = models.ManyToManyField(NodeGraphs, blank=True, null=True) # user = models.ForeignKey(User) # default = models.BooleanField(default=False) # # def get_absolute_url(self): # return reverse('load_search', kwargs={'search_id': self.id}) # # def get_delete_url(self): # return reverse('delete_search', kwargs={'search_id': self.id}) # # def get_default_url(self): # return reverse('default_search', kwargs={'search_id': self.id}) # # def __unicode__(self): # return self.description # # class Meta: # verbose_name_plural = "Saved Searches" # # class NodeGraphs(models.Model): # node = models.ForeignKey(Node) # graph = models.ForeignKey(Graph) # baseurl = models.CharField(max_length=512) # pageurl = models.CharField(max_length=512) # updated = models.DateTimeField(auto_now=True) # # def img_url(self): # return '%s-day.png' % self.baseurl # # def __unicode__(self): # return u'%s:%s:%s' % (self.node, self.graph, self.baseurl) # # class Meta: # verbose_name_plural = "Node Graphs" # # def common_start(sa, sb): # ''' # returns the longest common substring from the beginning of sa and sb # ''' # def _iter(): # for a, b in zip(sa, sb): # if a == b: # yield a # else: # return # # return ''.join(_iter()) , which may include functions, classes, or code. Output only the next line.
grlist.append(gcdict)
Predict the next line after this snippet: <|code_start|> nodes = request.user.get_profile().nodes.all() graphs = graphs.filter(node__in=nodes) len_graphs = len(graphs) for index, graph in enumerate(graphs): if graph.graph.category.name not in parsed_graph_category: if parsed_graph_category: grlist.append(gcdict) gcdict = {} gcdict['title'] = graph.graph.category.name gcdict['children'] = [] gcdict['nodeurl'] = graph.pageurl.replace(common_start(graph.baseurl, graph.node.url), '') parsed_graph_category.append(graph.graph.category.name) if graph.graph.name not in parsed_graph_name: parsed_group = [] gdict = {} gdict['title'] = graph.graph.name gdict['children'] = [] gcdict['children'].append(gdict) parsed_graph_name.append(graph.graph.name) if graph.node.group.name not in parsed_group: grdict = {} grdict['title'] = graph.node.group.name grdict['children'] = [] grdict['baseurl'] = common_start(graph.baseurl, graph.node.url) gdict['children'].append(grdict) parsed_group.append(graph.node.group.name) ndict = {} <|code_end|> using the current file's imports: import bz2 import json from django import template from muparse.models import SavedSearch, NodeGraphs, common_start from django.core.cache import cache and any relevant context from other files: # Path: muparse/models.py # class SavedSearch(models.Model): # description = models.CharField(max_length=255) # display_type = models.CharField(max_length=64) # graphs = models.ManyToManyField(NodeGraphs, blank=True, null=True) # user = models.ForeignKey(User) # default = models.BooleanField(default=False) # # def get_absolute_url(self): # return reverse('load_search', kwargs={'search_id': self.id}) # # def get_delete_url(self): # return reverse('delete_search', kwargs={'search_id': self.id}) # # def get_default_url(self): # return reverse('default_search', kwargs={'search_id': self.id}) # # def __unicode__(self): # return self.description # # class Meta: # verbose_name_plural = "Saved Searches" # # class NodeGraphs(models.Model): # node = models.ForeignKey(Node) # graph = models.ForeignKey(Graph) # baseurl = models.CharField(max_length=512) # pageurl = models.CharField(max_length=512) # updated = models.DateTimeField(auto_now=True) # # def img_url(self): # return '%s-day.png' % self.baseurl # # def __unicode__(self): # return u'%s:%s:%s' % (self.node, self.graph, self.baseurl) # # class Meta: # verbose_name_plural = "Node Graphs" # # def common_start(sa, sb): # ''' # returns the longest common substring from the beginning of sa and sb # ''' # def _iter(): # for a, b in zip(sa, sb): # if a == b: # yield a # else: # return # # return ''.join(_iter()) . Output only the next line.
ndict['title'] = graph.node.name
Continue the code snippet: <|code_start|># Copyright (C) 2010-2014 GRNET S.A. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # class UserProfile(models.Model): user = models.OneToOneField(User) nodes = models.ManyToManyField(Node, blank=True, null=True) <|code_end|> . Use current file imports: from django.db import models from django.contrib.auth.models import User from django.core.cache import cache from django.db.models.signals import post_save from django.core.mail import send_mail from django.conf import settings from muparse.models import Node and context (classes, functions, or code) from other files: # Path: muparse/models.py # class Node(models.Model): # name = models.SlugField(max_length=255) # url = models.CharField(max_length=512) # group = models.ForeignKey(NodeGroup) # graphs = models.ManyToManyField(Graph, blank=True, null=True, through='NodeGraphs') # updated = models.DateTimeField(auto_now=True) # # def __unicode__(self): # return self.name # # def get_graph_categories(self): # cat_list = [] # for graph in self.graphs.all(): # cat_list.append(graph.category.pk) # return GraphCategory.objects.filter(pk__in=list(set(cat_list))) # # class Meta: # ordering = ['name'] . Output only the next line.
def get_nodes(self):
Given the following code snippet before the placeholder: <|code_start|> if isinstance(node, tuple): MNODES.append(node) else: raise ImproperlyConfigured('Munin node should be a tupple') for node in MuninNodes.objects.all(): MNODES.append((node.name, node.as_dict())) if not MNODES: raise Exception('No nodes found!!') return MNODES def get_v2_nodes(): nodes = [] for node in get_all_nodes(): url = node[1].get('url') try: html = requests.get(url).text if html[html.find('version ') + 8] != '1': nodes.append(node) except: print 'Could not fetch %s' % (url) return nodes def get_v1_nodes(): nodes = [] for node in get_all_nodes(): url = node[1].get('url') try: html = requests.get(url).text <|code_end|> , predict the next line using imports from the current file: from django.conf import settings from muparse.models import MuninNodes from django.core.exceptions import ImproperlyConfigured import requests and context including class names, function names, and sometimes code from other files: # Path: muparse/models.py # class MuninNodes(models.Model): # name = models.CharField(max_length=255) # url = models.URLField(max_length=255) # cgi_path = models.CharField(max_length=255) # image_path = models.CharField(max_length=255, blank=True) # # def __unicode__(self): # return self.name # # def as_dict(self): # return { # 'name': self.name, # 'url': self.url, # 'cgi_path': self.cgi_path, # 'image_path': self.image_path # } # # class Meta: # verbose_name_plural = "Munin Node" # verbose_name_plural = "Munin Nodes" . Output only the next line.
if html[html.find('version ') + 8] == '1':
Predict the next line after this snippet: <|code_start|>@login_required @never_cache def delete_search(request, search_id=None): try: savedsearch = SavedSearch.objects.get(pk=search_id) savedsearch.delete() response = json.dumps({"result": "Successfully deleted %s" % (savedsearch.description), 'errors': False}) except Exception as e: response = json.dumps({"result": "Errors: %s" % (e), 'errors': True}) return HttpResponse(response, mimetype="application/json") @login_required @never_cache def saved_searches(request): searches = [] saved_searches = SavedSearch.objects.filter(user=request.user).order_by('description') for s in saved_searches: searches.append({ 'id': s.id, 'description': s.description, 'url': s.get_absolute_url(), 'default': s.default, 'default_url': s.get_default_url(), 'delete_url': s.get_delete_url() }) return HttpResponse(json.dumps({"saved": searches}), mimetype="application/json") @login_required <|code_end|> using the current file's imports: import json from django.shortcuts import render from django.http import HttpResponse from muparse.models import SavedSearch from muparse.forms import SavedSearchForm from accounts.models import UserProfile from django.views.decorators.cache import never_cache from django.contrib.auth.decorators import login_required from django.http import Http404 from muparse.models import NodeGraphs and any relevant context from other files: # Path: muparse/models.py # class SavedSearch(models.Model): # description = models.CharField(max_length=255) # display_type = models.CharField(max_length=64) # graphs = models.ManyToManyField(NodeGraphs, blank=True, null=True) # user = models.ForeignKey(User) # default = models.BooleanField(default=False) # # def get_absolute_url(self): # return reverse('load_search', kwargs={'search_id': self.id}) # # def get_delete_url(self): # return reverse('delete_search', kwargs={'search_id': self.id}) # # def get_default_url(self): # return reverse('default_search', kwargs={'search_id': self.id}) # # def __unicode__(self): # return self.description # # class Meta: # verbose_name_plural = "Saved Searches" # # Path: muparse/forms.py # class SavedSearchForm(ModelForm): # class Meta: # model = SavedSearch # # Path: accounts/models.py # class UserProfile(models.Model): # user = models.OneToOneField(User) # nodes = models.ManyToManyField(Node, blank=True, null=True) # # def get_nodes(self): # ret = '' # ngs = self.nodes.all() # for ng in ngs: # ret = "%s, %s" % (ng, ret) # if ret: # nodes = ret.rstrip(', ') # return nodes # else: # return None # # def save(self, *args, **kwargs): # cache.delete('user_%s_tree' % (self.user.pk)) # cache.delete('user_%s_tree_cat' % (self.user.pk)) # super(UserProfile, self).save(*args, **kwargs) # # def __unicode__(self): # return "%s:%s" % (self.user.username, self.get_nodes()) # # Path: muparse/models.py # class NodeGraphs(models.Model): # node = models.ForeignKey(Node) # graph = models.ForeignKey(Graph) # baseurl = models.CharField(max_length=512) # pageurl = models.CharField(max_length=512) # updated = models.DateTimeField(auto_now=True) # # def img_url(self): # return '%s-day.png' % self.baseurl # # def __unicode__(self): # return u'%s:%s:%s' % (self.node, self.graph, self.baseurl) # # class Meta: # verbose_name_plural = "Node Graphs" . Output only the next line.
@never_cache
Continue the code snippet: <|code_start|> nodes = request.user.get_profile().nodes.all() except UserProfile.DoesNotExist: raise Http404 graphs.extend(["%s" % (i.pk) for i in savedsearches.graphs.filter(node__in=nodes)]) else: graphs.extend(["%s" % (i.pk) for i in savedsearches.graphs.all()]) graphs = ','.join(graphs) result = json.dumps({'result': graphs, 'display_type': savedsearches.display_type, 'description': savedsearches.description}) return HttpResponse(result, mimetype="application/json") @login_required @never_cache def delete_search(request, search_id=None): try: savedsearch = SavedSearch.objects.get(pk=search_id) savedsearch.delete() response = json.dumps({"result": "Successfully deleted %s" % (savedsearch.description), 'errors': False}) except Exception as e: response = json.dumps({"result": "Errors: %s" % (e), 'errors': True}) return HttpResponse(response, mimetype="application/json") @login_required @never_cache def saved_searches(request): searches = [] saved_searches = SavedSearch.objects.filter(user=request.user).order_by('description') for s in saved_searches: searches.append({ <|code_end|> . Use current file imports: import json from django.shortcuts import render from django.http import HttpResponse from muparse.models import SavedSearch from muparse.forms import SavedSearchForm from accounts.models import UserProfile from django.views.decorators.cache import never_cache from django.contrib.auth.decorators import login_required from django.http import Http404 from muparse.models import NodeGraphs and context (classes, functions, or code) from other files: # Path: muparse/models.py # class SavedSearch(models.Model): # description = models.CharField(max_length=255) # display_type = models.CharField(max_length=64) # graphs = models.ManyToManyField(NodeGraphs, blank=True, null=True) # user = models.ForeignKey(User) # default = models.BooleanField(default=False) # # def get_absolute_url(self): # return reverse('load_search', kwargs={'search_id': self.id}) # # def get_delete_url(self): # return reverse('delete_search', kwargs={'search_id': self.id}) # # def get_default_url(self): # return reverse('default_search', kwargs={'search_id': self.id}) # # def __unicode__(self): # return self.description # # class Meta: # verbose_name_plural = "Saved Searches" # # Path: muparse/forms.py # class SavedSearchForm(ModelForm): # class Meta: # model = SavedSearch # # Path: accounts/models.py # class UserProfile(models.Model): # user = models.OneToOneField(User) # nodes = models.ManyToManyField(Node, blank=True, null=True) # # def get_nodes(self): # ret = '' # ngs = self.nodes.all() # for ng in ngs: # ret = "%s, %s" % (ng, ret) # if ret: # nodes = ret.rstrip(', ') # return nodes # else: # return None # # def save(self, *args, **kwargs): # cache.delete('user_%s_tree' % (self.user.pk)) # cache.delete('user_%s_tree_cat' % (self.user.pk)) # super(UserProfile, self).save(*args, **kwargs) # # def __unicode__(self): # return "%s:%s" % (self.user.username, self.get_nodes()) # # Path: muparse/models.py # class NodeGraphs(models.Model): # node = models.ForeignKey(Node) # graph = models.ForeignKey(Graph) # baseurl = models.CharField(max_length=512) # pageurl = models.CharField(max_length=512) # updated = models.DateTimeField(auto_now=True) # # def img_url(self): # return '%s-day.png' % self.baseurl # # def __unicode__(self): # return u'%s:%s:%s' % (self.node, self.graph, self.baseurl) # # class Meta: # verbose_name_plural = "Node Graphs" . Output only the next line.
'id': s.id,
Here is a snippet: <|code_start|># MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. @login_required def home(request): saved_search = SavedSearch.objects.filter(user=request.user) if saved_search: default = saved_search.filter(default=True) if default: saved_search = default graphs = saved_search[0].graphs.all() else: nodes = request.user.get_profile().nodes.all() graphs = NodeGraphs.objects.filter(node__in=nodes)[:50] default = False return render(request, 'main.html', {'graphs': graphs, 'default': default}) @login_required def get_menu(request): return render(request, 'partial/graphs_menu.html') @login_required <|code_end|> . Write the next line using the current file imports: import json from django.shortcuts import render from django.http import HttpResponse from muparse.models import SavedSearch from muparse.forms import SavedSearchForm from accounts.models import UserProfile from django.views.decorators.cache import never_cache from django.contrib.auth.decorators import login_required from django.http import Http404 from muparse.models import NodeGraphs and context from other files: # Path: muparse/models.py # class SavedSearch(models.Model): # description = models.CharField(max_length=255) # display_type = models.CharField(max_length=64) # graphs = models.ManyToManyField(NodeGraphs, blank=True, null=True) # user = models.ForeignKey(User) # default = models.BooleanField(default=False) # # def get_absolute_url(self): # return reverse('load_search', kwargs={'search_id': self.id}) # # def get_delete_url(self): # return reverse('delete_search', kwargs={'search_id': self.id}) # # def get_default_url(self): # return reverse('default_search', kwargs={'search_id': self.id}) # # def __unicode__(self): # return self.description # # class Meta: # verbose_name_plural = "Saved Searches" # # Path: muparse/forms.py # class SavedSearchForm(ModelForm): # class Meta: # model = SavedSearch # # Path: accounts/models.py # class UserProfile(models.Model): # user = models.OneToOneField(User) # nodes = models.ManyToManyField(Node, blank=True, null=True) # # def get_nodes(self): # ret = '' # ngs = self.nodes.all() # for ng in ngs: # ret = "%s, %s" % (ng, ret) # if ret: # nodes = ret.rstrip(', ') # return nodes # else: # return None # # def save(self, *args, **kwargs): # cache.delete('user_%s_tree' % (self.user.pk)) # cache.delete('user_%s_tree_cat' % (self.user.pk)) # super(UserProfile, self).save(*args, **kwargs) # # def __unicode__(self): # return "%s:%s" % (self.user.username, self.get_nodes()) # # Path: muparse/models.py # class NodeGraphs(models.Model): # node = models.ForeignKey(Node) # graph = models.ForeignKey(Graph) # baseurl = models.CharField(max_length=512) # pageurl = models.CharField(max_length=512) # updated = models.DateTimeField(auto_now=True) # # def img_url(self): # return '%s-day.png' % self.baseurl # # def __unicode__(self): # return u'%s:%s:%s' % (self.node, self.graph, self.baseurl) # # class Meta: # verbose_name_plural = "Node Graphs" , which may include functions, classes, or code. Output only the next line.
@never_cache
Here is a snippet: <|code_start|> except UserProfile.DoesNotExist: raise Http404 graphs.extend(["%s" % (i.pk) for i in savedsearches.graphs.filter(node__in=nodes)]) else: graphs.extend(["%s" % (i.pk) for i in savedsearches.graphs.all()]) graphs = ','.join(graphs) result = json.dumps({'result': graphs, 'display_type': savedsearches.display_type, 'description': savedsearches.description}) return HttpResponse(result, mimetype="application/json") @login_required @never_cache def delete_search(request, search_id=None): try: savedsearch = SavedSearch.objects.get(pk=search_id) savedsearch.delete() response = json.dumps({"result": "Successfully deleted %s" % (savedsearch.description), 'errors': False}) except Exception as e: response = json.dumps({"result": "Errors: %s" % (e), 'errors': True}) return HttpResponse(response, mimetype="application/json") @login_required @never_cache def saved_searches(request): searches = [] saved_searches = SavedSearch.objects.filter(user=request.user).order_by('description') for s in saved_searches: searches.append({ 'id': s.id, <|code_end|> . Write the next line using the current file imports: import json from django.shortcuts import render from django.http import HttpResponse from muparse.models import SavedSearch from muparse.forms import SavedSearchForm from accounts.models import UserProfile from django.views.decorators.cache import never_cache from django.contrib.auth.decorators import login_required from django.http import Http404 from muparse.models import NodeGraphs and context from other files: # Path: muparse/models.py # class SavedSearch(models.Model): # description = models.CharField(max_length=255) # display_type = models.CharField(max_length=64) # graphs = models.ManyToManyField(NodeGraphs, blank=True, null=True) # user = models.ForeignKey(User) # default = models.BooleanField(default=False) # # def get_absolute_url(self): # return reverse('load_search', kwargs={'search_id': self.id}) # # def get_delete_url(self): # return reverse('delete_search', kwargs={'search_id': self.id}) # # def get_default_url(self): # return reverse('default_search', kwargs={'search_id': self.id}) # # def __unicode__(self): # return self.description # # class Meta: # verbose_name_plural = "Saved Searches" # # Path: muparse/forms.py # class SavedSearchForm(ModelForm): # class Meta: # model = SavedSearch # # Path: accounts/models.py # class UserProfile(models.Model): # user = models.OneToOneField(User) # nodes = models.ManyToManyField(Node, blank=True, null=True) # # def get_nodes(self): # ret = '' # ngs = self.nodes.all() # for ng in ngs: # ret = "%s, %s" % (ng, ret) # if ret: # nodes = ret.rstrip(', ') # return nodes # else: # return None # # def save(self, *args, **kwargs): # cache.delete('user_%s_tree' % (self.user.pk)) # cache.delete('user_%s_tree_cat' % (self.user.pk)) # super(UserProfile, self).save(*args, **kwargs) # # def __unicode__(self): # return "%s:%s" % (self.user.username, self.get_nodes()) # # Path: muparse/models.py # class NodeGraphs(models.Model): # node = models.ForeignKey(Node) # graph = models.ForeignKey(Graph) # baseurl = models.CharField(max_length=512) # pageurl = models.CharField(max_length=512) # updated = models.DateTimeField(auto_now=True) # # def img_url(self): # return '%s-day.png' % self.baseurl # # def __unicode__(self): # return u'%s:%s:%s' % (self.node, self.graph, self.baseurl) # # class Meta: # verbose_name_plural = "Node Graphs" , which may include functions, classes, or code. Output only the next line.
'description': s.description,
Predict the next line for this snippet: <|code_start|> def save(self, message='auto-save'): self.commit_thing(message + ' ' + str(time())) class WorldWrapper: # TODO: Merge this class with TextViewerWorldMixin. def __init__(self, world): self.world = world def do_lookup(self, name): self.world.step(['"%s"' % (name,), 'lookup']) def do_opendoc(self, name): self.do_lookup(name) def pop(self): stack, dictionary = self.world.getCurrentState() if not stack: return self.world.step(['drop']) def push(self, it): it = '"%s"' % it.encode('utf8') self.world.step([it]) def peek(self): stack, dictionary = self.world.getCurrentState() if not stack: raise IndexError <|code_end|> with the help of current file imports: from Tkinter import ( Text, Toplevel, TclError, END, INSERT, SEL, DISABLED, NORMAL, ) from time import time from traceback import format_exc from pigeon.xerblin.btree import get from pigeon.xerblin.btree import items from pigeon.xerblin.world import HistoryListWorld, view0 import re, os and context from other files: # Path: pigeon/xerblin/btree.py # def get(node, key): # ''' # Return the value stored under key or raise KeyError if not found. # ''' # if not node: # raise KeyError, key # # node_key, value, lower, higher = node # # if key == node_key: # return value # # return get(lower if key < node_key else higher, key) , which may contain function names, class names, or code. Output only the next line.
return stack[0]
Using the snippet: <|code_start|># def make_commit_thing(path, files): log = logging.getLogger('COMMIT') try: repo = Repo(path) except NotGitRepository: log.critical("%r isn't a repository!", path) raise ValueError("%r isn't a repository!" % (path,)) # Note that we bind the args as defaults rather than via a closure so # you can override them later if you want. def commit(message, files=files, repo=repo, log=log): repo.stage(files) commit_sha = repo.do_commit(message) log.info('commit %s %s', commit_sha, message[:100]) return commit def list_words(dictionary): words = sorted(name for name, value in items(dictionary)) return 'Words: ' + ' '.join(words) + '\n' def initialize_repo(path, state, text, create_default_config=True): log = logging.getLogger('INIT_REPO') if not exists(path): log.critical("%r doesn't exist!", path) <|code_end|> , determine the next line of code. You have imports: import pickle, logging, sys from os.path import exists, join from dulwich.repo import Repo, NotGitRepository from pigeon.xerblin.btree import items from pigeon.xerblin.world import ROOT and context (class names, function names, or code) available: # Path: pigeon/xerblin/btree.py # def items(node): # ''' # Iterate in order over the (key, value) pairs in a tree. # ''' # if not node: # return # # key, value, lower, higher = node # # for kv in items(lower): # yield kv # # yield key, value # # for kv in items(higher): # yield kv . Output only the next line.
raise ValueError("%r doesn't exist!" % (path,))
Using the snippet: <|code_start|># evil INSTANCE_PRICES_FILENAME = '/tmp/aws-prices.json' INSTANCE_PRICES_URL_PREFIX="https://pricing.us-east-1.amazonaws.com/" OPERATING_SYSTEM="Linux" TENANCY='Shared' class InstancePricing(object): def __init__(self): if not os.path.isfile(INSTANCE_PRICES_FILENAME): self.retrieve_pricing_file() with open(INSTANCE_PRICES_FILENAME, 'r') as infile: pricing = json.load(infile) vers = nav(pricing, 'formatVersion') if vers != "v1.0": raise Exception("Expected version v1.0 but got {}".format(vers)) self.products = nav(pricing, 'products') self.terms = nav(pricing, 'terms') def retrieve_pricing_file(self): # http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/price-changes.html OFFERS_URL=urlparse.urljoin(INSTANCE_PRICES_URL_PREFIX, "/offers/v1.0/aws/index.json") offers = requests.get(OFFERS_URL).json() AMAZONEC2_URL = urlparse.urljoin(INSTANCE_PRICES_URL_PREFIX, offers['offers']['AmazonEC2']['currentVersionUrl']) ec2_prices = requests.get(AMAZONEC2_URL).json() with open(INSTANCE_PRICES_FILENAME, 'w') as f: print(json.dumps(ec2_prices), file=f) @memoized <|code_end|> , determine the next line of code. You have imports: import os import json import requests import urlparse from pricing.nav import nav from pricing.aws_regions import AWS_REGION_LONG_NAMES from pricing.memoizer import memoized and context (class names, function names, or code) available: # Path: pricing/nav.py # def nav(d, ks): # def nav2(d, ks): # if len(ks) == 0: # return d # if not isinstance(d, dict): # raise KeyError(ks) # if ks[0] not in d: # return None # return nav2(d[ks[0]], ks[1:]) # return nav2(d, ks.split('.')) # # Path: pricing/aws_regions.py # AWS_REGION_LONG_NAMES = { # "us-east-1": "US East (N. Virginia)", # "us-west-1": "US West (N. California)", # "us-west-2": "US West (Oregon)", # "eu-west-1": "EU (Ireland)", # "eu-central-1": "EU (Frankfurt)", # "ap-northeast-1": "Asia Pacific (Tokyo)", # "ap-northeast-2": "Asia Pacific (Seoul)", # "ap-southeast-1": "Asia Pacific (Singapore)", # "ap-southeast-2": "Asia Pacific (Sydney)", # "sa-east-1": "South America (Sao Paulo)" # } # # Path: pricing/memoizer.py # class memoized(object): # '''Decorator. Caches a function's return value each time it is called. # If called later with the same arguments, the cached value is returned # (not reevaluated). # ''' # def __init__(self, func): # self.func = func # self.cache = {} # def __call__(self, *args): # if not isinstance(args, collections.Hashable): # # uncacheable. a list, for instance. # # better to not cache than blow up. # return self.func(*args) # if args in self.cache: # return self.cache[args] # else: # value = self.func(*args) # self.cache[args] = value # return value # def __repr__(self): # '''Return the function's docstring.''' # return self.func.__doc__ # def __get__(self, obj, objtype): # '''Support instance methods.''' # return functools.partial(self.__call__, obj) . Output only the next line.
def get_spot_pricing(self, ec2, spot_instance_request_id):
Given snippet: <|code_start|> with open(INSTANCE_PRICES_FILENAME, 'w') as f: print(json.dumps(ec2_prices), file=f) @memoized def get_spot_pricing(self, ec2, spot_instance_request_id): # inefficient spot_instance_requests = ec2.get_all_spot_instance_requests(request_ids=[spot_instance_request_id]) return spot_instance_requests[0].price @memoized def get_ondemand_pricing(self, region, instance_type): def pick_one(d): return d.itervalues().next() location = AWS_REGION_LONG_NAMES[region] (sku,product) = [ (sku, nav(product, 'attributes')) for sku,product in self.products.items() if (nav(product, 'attributes.instanceType')==instance_type and nav(product, 'attributes.operatingSystem') == OPERATING_SYSTEM and nav(product, 'attributes.location') == location and nav(product, 'attributes.tenancy') == TENANCY) ][0] price = float(nav(pick_one(nav(pick_one(self.terms['OnDemand'][sku]), "priceDimensions")), 'pricePerUnit.USD')) return price if __name__ == "__main__": <|code_end|> , continue by predicting the next line. Consider current file imports: import os import json import requests import urlparse from pricing.nav import nav from pricing.aws_regions import AWS_REGION_LONG_NAMES from pricing.memoizer import memoized and context: # Path: pricing/nav.py # def nav(d, ks): # def nav2(d, ks): # if len(ks) == 0: # return d # if not isinstance(d, dict): # raise KeyError(ks) # if ks[0] not in d: # return None # return nav2(d[ks[0]], ks[1:]) # return nav2(d, ks.split('.')) # # Path: pricing/aws_regions.py # AWS_REGION_LONG_NAMES = { # "us-east-1": "US East (N. Virginia)", # "us-west-1": "US West (N. California)", # "us-west-2": "US West (Oregon)", # "eu-west-1": "EU (Ireland)", # "eu-central-1": "EU (Frankfurt)", # "ap-northeast-1": "Asia Pacific (Tokyo)", # "ap-northeast-2": "Asia Pacific (Seoul)", # "ap-southeast-1": "Asia Pacific (Singapore)", # "ap-southeast-2": "Asia Pacific (Sydney)", # "sa-east-1": "South America (Sao Paulo)" # } # # Path: pricing/memoizer.py # class memoized(object): # '''Decorator. Caches a function's return value each time it is called. # If called later with the same arguments, the cached value is returned # (not reevaluated). # ''' # def __init__(self, func): # self.func = func # self.cache = {} # def __call__(self, *args): # if not isinstance(args, collections.Hashable): # # uncacheable. a list, for instance. # # better to not cache than blow up. # return self.func(*args) # if args in self.cache: # return self.cache[args] # else: # value = self.func(*args) # self.cache[args] = value # return value # def __repr__(self): # '''Return the function's docstring.''' # return self.func.__doc__ # def __get__(self, obj, objtype): # '''Support instance methods.''' # return functools.partial(self.__call__, obj) which might include code, classes, or functions. Output only the next line.
print(InstancePricing().get_ondemand_pricing('ap-southeast-1', 'm1.small'))
Predict the next line for this snippet: <|code_start|>#!/usr/bin/python from __future__ import print_function # evil INSTANCE_PRICES_FILENAME = '/tmp/aws-prices.json' INSTANCE_PRICES_URL_PREFIX="https://pricing.us-east-1.amazonaws.com/" OPERATING_SYSTEM="Linux" TENANCY='Shared' class InstancePricing(object): def __init__(self): if not os.path.isfile(INSTANCE_PRICES_FILENAME): <|code_end|> with the help of current file imports: import os import json import requests import urlparse from pricing.nav import nav from pricing.aws_regions import AWS_REGION_LONG_NAMES from pricing.memoizer import memoized and context from other files: # Path: pricing/nav.py # def nav(d, ks): # def nav2(d, ks): # if len(ks) == 0: # return d # if not isinstance(d, dict): # raise KeyError(ks) # if ks[0] not in d: # return None # return nav2(d[ks[0]], ks[1:]) # return nav2(d, ks.split('.')) # # Path: pricing/aws_regions.py # AWS_REGION_LONG_NAMES = { # "us-east-1": "US East (N. Virginia)", # "us-west-1": "US West (N. California)", # "us-west-2": "US West (Oregon)", # "eu-west-1": "EU (Ireland)", # "eu-central-1": "EU (Frankfurt)", # "ap-northeast-1": "Asia Pacific (Tokyo)", # "ap-northeast-2": "Asia Pacific (Seoul)", # "ap-southeast-1": "Asia Pacific (Singapore)", # "ap-southeast-2": "Asia Pacific (Sydney)", # "sa-east-1": "South America (Sao Paulo)" # } # # Path: pricing/memoizer.py # class memoized(object): # '''Decorator. Caches a function's return value each time it is called. # If called later with the same arguments, the cached value is returned # (not reevaluated). # ''' # def __init__(self, func): # self.func = func # self.cache = {} # def __call__(self, *args): # if not isinstance(args, collections.Hashable): # # uncacheable. a list, for instance. # # better to not cache than blow up. # return self.func(*args) # if args in self.cache: # return self.cache[args] # else: # value = self.func(*args) # self.cache[args] = value # return value # def __repr__(self): # '''Return the function's docstring.''' # return self.func.__doc__ # def __get__(self, obj, objtype): # '''Support instance methods.''' # return functools.partial(self.__call__, obj) , which may contain function names, class names, or code. Output only the next line.
self.retrieve_pricing_file()
Based on the snippet: <|code_start|> name = get_host_name(i) archdomain = get_archdomain(i) env_tag = get_env_tag(i) if i.ip_address and i.private_ip_address and name: if i.spot_instance_request_id is not None: start_time = dateutil.parser.parse(i.launch_time) end_time = datetime.datetime.utcnow().replace(tzinfo=dateutil.tz.tzutc()) hourly_price = spot_pricer.get_spot_instance_pricing(i.instance_type, start_time, end_time, i.placement, i.spot_instance_request_id) else: hourly_price = instance_pricer.get_ondemand_pricing(region.name, i.instance_type) results.append((region.name, name, i.instance_type, str(hourly_price), archdomain, env_tag, i.ip_address, i.private_ip_address)) if args.format=='tsv': for line in results: print("\t".join(line)) elif args.format=='json-lines': for line in results: print(json.dumps(dict(zip(['region', 'name', 'type', 'price', 'archdomain', 'env', 'ip_public', 'ip_private'], line)))) elif args.format=='json': print('[') for line in results: print(json.dumps(dict(zip(['region', 'name', 'type', 'price', 'archdomain', 'env', 'ip_public', 'ip_private'], line))), end=',\n') print(']') else: raise ValueError("--format tsv|json|json-lines") <|code_end|> , predict the immediate next line with the help of imports: import argparse import boto.ec2 import dateutil import datetime import json from pricing.instance_pricing import InstancePricing from pricing.spot_pricing import SpotPricing and context (classes, functions, sometimes code) from other files: # Path: pricing/instance_pricing.py # class InstancePricing(object): # def __init__(self): # if not os.path.isfile(INSTANCE_PRICES_FILENAME): # self.retrieve_pricing_file() # with open(INSTANCE_PRICES_FILENAME, 'r') as infile: # pricing = json.load(infile) # vers = nav(pricing, 'formatVersion') # if vers != "v1.0": # raise Exception("Expected version v1.0 but got {}".format(vers)) # self.products = nav(pricing, 'products') # self.terms = nav(pricing, 'terms') # # def retrieve_pricing_file(self): # # http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/price-changes.html # OFFERS_URL=urlparse.urljoin(INSTANCE_PRICES_URL_PREFIX, "/offers/v1.0/aws/index.json") # offers = requests.get(OFFERS_URL).json() # AMAZONEC2_URL = urlparse.urljoin(INSTANCE_PRICES_URL_PREFIX, offers['offers']['AmazonEC2']['currentVersionUrl']) # ec2_prices = requests.get(AMAZONEC2_URL).json() # with open(INSTANCE_PRICES_FILENAME, 'w') as f: # print(json.dumps(ec2_prices), file=f) # # @memoized # def get_spot_pricing(self, ec2, spot_instance_request_id): # # inefficient # spot_instance_requests = ec2.get_all_spot_instance_requests(request_ids=[spot_instance_request_id]) # return spot_instance_requests[0].price # # @memoized # def get_ondemand_pricing(self, region, instance_type): # def pick_one(d): # return d.itervalues().next() # # location = AWS_REGION_LONG_NAMES[region] # # (sku,product) = [ # (sku, nav(product, 'attributes')) # for sku,product in self.products.items() # if (nav(product, 'attributes.instanceType')==instance_type and # nav(product, 'attributes.operatingSystem') == OPERATING_SYSTEM and # nav(product, 'attributes.location') == location and # nav(product, 'attributes.tenancy') == TENANCY) # ][0] # price = float(nav(pick_one(nav(pick_one(self.terms['OnDemand'][sku]), "priceDimensions")), 'pricePerUnit.USD')) # return price # # Path: pricing/spot_pricing.py # class SpotPricing(object): # def __init__(self): # self.ec2 = boto3.client('ec2') # # # this is an estimate based on recent prices # # http://stackoverflow.com/questions/11780262/calculate-running-cumulative-cost-of-ec2-spot-instance # @memoized # def get_spot_instance_pricing(self, instance_type, start_time, end_time, availability_zone, spot_instance_request_id=None): # # don't fetch any more since this is an approximation of hourly cost anyway # # we can only report the accumulated cost for the time period we examine, # # not the total time. # # max_results = 30 # result = self.ec2.describe_spot_price_history(InstanceTypes=[instance_type], StartTime=start_time, EndTime=end_time, # AvailabilityZone=availability_zone, MaxResults = max_results) # total_cost = 0.0 # total_seconds = (end_time - start_time).total_seconds() # total_hours = total_seconds / (60*60) # computed_seconds = 0 # # last_time = end_time # for price in result["SpotPriceHistory"]: # price["SpotPrice"] = float(price["SpotPrice"]) # # available_seconds = (last_time - price["Timestamp"]).total_seconds() # remaining_seconds = total_seconds - computed_seconds # used_seconds = min(available_seconds, remaining_seconds) # # total_cost += (price["SpotPrice"] / (60 * 60)) * used_seconds # computed_seconds += used_seconds # # last_time = price["Timestamp"] # # return float("{0:.3f}".format((total_cost / (computed_seconds / (60.0 * 60.0))))) . Output only the next line.
if __name__=="__main__":
Based on the snippet: <|code_start|>#!/usr/bin/python from __future__ import print_function # region.name, name, instance_type, price, archdomain, env_tag, ip_address, private_ip_address ... def sanitize(value): if value is None or value == "": <|code_end|> , predict the immediate next line with the help of imports: import argparse import boto.ec2 import dateutil import datetime import json from pricing.instance_pricing import InstancePricing from pricing.spot_pricing import SpotPricing and context (classes, functions, sometimes code) from other files: # Path: pricing/instance_pricing.py # class InstancePricing(object): # def __init__(self): # if not os.path.isfile(INSTANCE_PRICES_FILENAME): # self.retrieve_pricing_file() # with open(INSTANCE_PRICES_FILENAME, 'r') as infile: # pricing = json.load(infile) # vers = nav(pricing, 'formatVersion') # if vers != "v1.0": # raise Exception("Expected version v1.0 but got {}".format(vers)) # self.products = nav(pricing, 'products') # self.terms = nav(pricing, 'terms') # # def retrieve_pricing_file(self): # # http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/price-changes.html # OFFERS_URL=urlparse.urljoin(INSTANCE_PRICES_URL_PREFIX, "/offers/v1.0/aws/index.json") # offers = requests.get(OFFERS_URL).json() # AMAZONEC2_URL = urlparse.urljoin(INSTANCE_PRICES_URL_PREFIX, offers['offers']['AmazonEC2']['currentVersionUrl']) # ec2_prices = requests.get(AMAZONEC2_URL).json() # with open(INSTANCE_PRICES_FILENAME, 'w') as f: # print(json.dumps(ec2_prices), file=f) # # @memoized # def get_spot_pricing(self, ec2, spot_instance_request_id): # # inefficient # spot_instance_requests = ec2.get_all_spot_instance_requests(request_ids=[spot_instance_request_id]) # return spot_instance_requests[0].price # # @memoized # def get_ondemand_pricing(self, region, instance_type): # def pick_one(d): # return d.itervalues().next() # # location = AWS_REGION_LONG_NAMES[region] # # (sku,product) = [ # (sku, nav(product, 'attributes')) # for sku,product in self.products.items() # if (nav(product, 'attributes.instanceType')==instance_type and # nav(product, 'attributes.operatingSystem') == OPERATING_SYSTEM and # nav(product, 'attributes.location') == location and # nav(product, 'attributes.tenancy') == TENANCY) # ][0] # price = float(nav(pick_one(nav(pick_one(self.terms['OnDemand'][sku]), "priceDimensions")), 'pricePerUnit.USD')) # return price # # Path: pricing/spot_pricing.py # class SpotPricing(object): # def __init__(self): # self.ec2 = boto3.client('ec2') # # # this is an estimate based on recent prices # # http://stackoverflow.com/questions/11780262/calculate-running-cumulative-cost-of-ec2-spot-instance # @memoized # def get_spot_instance_pricing(self, instance_type, start_time, end_time, availability_zone, spot_instance_request_id=None): # # don't fetch any more since this is an approximation of hourly cost anyway # # we can only report the accumulated cost for the time period we examine, # # not the total time. # # max_results = 30 # result = self.ec2.describe_spot_price_history(InstanceTypes=[instance_type], StartTime=start_time, EndTime=end_time, # AvailabilityZone=availability_zone, MaxResults = max_results) # total_cost = 0.0 # total_seconds = (end_time - start_time).total_seconds() # total_hours = total_seconds / (60*60) # computed_seconds = 0 # # last_time = end_time # for price in result["SpotPriceHistory"]: # price["SpotPrice"] = float(price["SpotPrice"]) # # available_seconds = (last_time - price["Timestamp"]).total_seconds() # remaining_seconds = total_seconds - computed_seconds # used_seconds = min(available_seconds, remaining_seconds) # # total_cost += (price["SpotPrice"] / (60 * 60)) * used_seconds # computed_seconds += used_seconds # # last_time = price["Timestamp"] # # return float("{0:.3f}".format((total_cost / (computed_seconds / (60.0 * 60.0))))) . Output only the next line.
return "unknown"
Given the code snippet: <|code_start|> @override_settings(USE_TZ=True) class CreateOrgTests(TestCase): fixtures = ["users.json", "orgs.json"] def setUp(self): self.user = User.objects.get(username="dave") def test_create_organization(self): acme = create_organization( self.user, "Acme", org_defaults={"slug": "acme-slug"} ) self.assertTrue(isinstance(acme, Organization)) self.assertEqual(self.user, acme.owner.organization_user.user) <|code_end|> , generate the next line using the imports in this file: from functools import partial from django.contrib.auth.models import User from django.test import TestCase from django.test.utils import override_settings from organizations.models import Organization from organizations.utils import create_organization from organizations.utils import model_field_attr from test_abstract.models import CustomOrganization from test_accounts.models import Account and context (functions, classes, or occasionally code) from other files: # Path: test_abstract/models.py # class CustomOrganization(AbstractOrganization): # street_address = models.CharField(max_length=100, default="") # city = models.CharField(max_length=100, default="") # # Path: test_accounts/models.py # class Account(OrganizationBase): # monthly_subscription = models.IntegerField(default=1000) . Output only the next line.
self.assertTrue(acme.owner.organization_user.is_admin)
Predict the next line for this snippet: <|code_start|> @override_settings(USE_TZ=True) class CreateOrgTests(TestCase): fixtures = ["users.json", "orgs.json"] def setUp(self): self.user = User.objects.get(username="dave") def test_create_organization(self): acme = create_organization( self.user, "Acme", org_defaults={"slug": "acme-slug"} ) <|code_end|> with the help of current file imports: from functools import partial from django.contrib.auth.models import User from django.test import TestCase from django.test.utils import override_settings from organizations.models import Organization from organizations.utils import create_organization from organizations.utils import model_field_attr from test_abstract.models import CustomOrganization from test_accounts.models import Account and context from other files: # Path: test_abstract/models.py # class CustomOrganization(AbstractOrganization): # street_address = models.CharField(max_length=100, default="") # city = models.CharField(max_length=100, default="") # # Path: test_accounts/models.py # class Account(OrganizationBase): # monthly_subscription = models.IntegerField(default=1000) , which may contain function names, class names, or code. Output only the next line.
self.assertTrue(isinstance(acme, Organization))
Given the following code snippet before the placeholder: <|code_start|>def extra_org_user(org_organization): new_user = User.objects.create(username="NotYou", email="not@you.com") org_organization.add_user(new_user) yield new_user @pytest.fixture def invitee_user(): yield User.objects.create_user( "newmember", email="jd@123.com", password="password123" ) class TestUserReminderView: @pytest.mark.parametrize("method", [("get"), ("post")]) def test_bad_request_for_active_user( self, rf, account_account, account_user, invitee_user, method ): class OrgUserReminderView(base.BaseOrganizationUserRemind): org_model = Account user_model = AccountUser request = getattr(rf, method)("/", user=account_user) kwargs = {"organization_pk": account_account.pk, "user_pk": account_user.pk} response = OrgUserReminderView.as_view()(request, **kwargs) assert response.status_code == 410 def test_organization_user_reminder( self, rf, account_account, account_user, invitee_user ): <|code_end|> , predict the next line using imports from the current file: from django.contrib.auth.models import User from django.core.exceptions import ImproperlyConfigured from django.core.exceptions import ObjectDoesNotExist from django.http import Http404 from django.test import TestCase from django.test.client import RequestFactory from django.test.utils import override_settings from django.urls import reverse from organizations.models import Organization from organizations.models import OrganizationUser from organizations.utils import create_organization from organizations.views import base from test_accounts.models import Account from test_accounts.models import AccountUser from tests.utils import request_factory_login import pytest and context including class names, function names, and sometimes code from other files: # Path: test_accounts/models.py # class Account(OrganizationBase): # monthly_subscription = models.IntegerField(default=1000) # # Path: test_accounts/models.py # class AccountUser(OrganizationUserBase): # user_type = models.CharField(max_length=1, default="") # # Path: tests/utils.py # def request_factory_login(factory, user=None, method="request", **kwargs): # """Based on this gist: https://gist.github.com/964472""" # # engine = import_module(settings.SESSION_ENGINE) # request = getattr(factory, method)(**kwargs) # # request.session = engine.SessionStore() # # request.session[SESSION_KEY] = user.pk # request.user = user or AnonymousUser() # return request . Output only the next line.
class OrgUserReminderView(base.BaseOrganizationUserRemind):
Given the following code snippet before the placeholder: <|code_start|> @pytest.fixture def account_user(): yield User.objects.create(username="AccountUser", email="akjdkj@kjdk.com") @pytest.fixture def account_account(account_user): yield create_organization(account_user, "Acme", org_model=Account) @pytest.fixture def org_organization(account_user): yield create_organization(account_user, "Acme", org_model=Organization) @pytest.fixture def extra_org_user(org_organization): new_user = User.objects.create(username="NotYou", email="not@you.com") <|code_end|> , predict the next line using imports from the current file: from django.contrib.auth.models import User from django.core.exceptions import ImproperlyConfigured from django.core.exceptions import ObjectDoesNotExist from django.http import Http404 from django.test import TestCase from django.test.client import RequestFactory from django.test.utils import override_settings from django.urls import reverse from organizations.models import Organization from organizations.models import OrganizationUser from organizations.utils import create_organization from organizations.views import base from test_accounts.models import Account from test_accounts.models import AccountUser from tests.utils import request_factory_login import pytest and context including class names, function names, and sometimes code from other files: # Path: test_accounts/models.py # class Account(OrganizationBase): # monthly_subscription = models.IntegerField(default=1000) # # Path: test_accounts/models.py # class AccountUser(OrganizationUserBase): # user_type = models.CharField(max_length=1, default="") # # Path: tests/utils.py # def request_factory_login(factory, user=None, method="request", **kwargs): # """Based on this gist: https://gist.github.com/964472""" # # engine = import_module(settings.SESSION_ENGINE) # request = getattr(factory, method)(**kwargs) # # request.session = engine.SessionStore() # # request.session[SESSION_KEY] = user.pk # request.user = user or AnonymousUser() # return request . Output only the next line.
org_organization.add_user(new_user)
Next line prediction: <|code_start|> @pytest.fixture def account_user(): yield User.objects.create(username="AccountUser", email="akjdkj@kjdk.com") @pytest.fixture def account_account(account_user): yield create_organization(account_user, "Acme", org_model=Account) <|code_end|> . Use current file imports: (from django.contrib.auth.models import User from django.core.exceptions import ImproperlyConfigured from django.core.exceptions import ObjectDoesNotExist from django.http import Http404 from django.test import TestCase from django.test.client import RequestFactory from django.test.utils import override_settings from django.urls import reverse from organizations.models import Organization from organizations.models import OrganizationUser from organizations.utils import create_organization from organizations.views import base from test_accounts.models import Account from test_accounts.models import AccountUser from tests.utils import request_factory_login import pytest) and context including class names, function names, or small code snippets from other files: # Path: test_accounts/models.py # class Account(OrganizationBase): # monthly_subscription = models.IntegerField(default=1000) # # Path: test_accounts/models.py # class AccountUser(OrganizationUserBase): # user_type = models.CharField(max_length=1, default="") # # Path: tests/utils.py # def request_factory_login(factory, user=None, method="request", **kwargs): # """Based on this gist: https://gist.github.com/964472""" # # engine = import_module(settings.SESSION_ENGINE) # request = getattr(factory, method)(**kwargs) # # request.session = engine.SessionStore() # # request.session[SESSION_KEY] = user.pk # request.user = user or AnonymousUser() # return request . Output only the next line.
@pytest.fixture
Given the code snippet: <|code_start|> @override_settings(USE_TZ=True) class BaseTests(TestCase): def test_generate_username(self): self.assertTrue(BaseBackend().get_username()) @override_settings( INSTALLED_APPS=[ "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sites", "test_accounts", ], <|code_end|> , generate the next line using the imports in this file: import uuid import pytest from django.contrib.auth.models import User from django.contrib.auth.tokens import PasswordResetTokenGenerator from django.core import mail from django.http import Http404 from django.http import QueryDict from django.test import TestCase from django.test.client import RequestFactory from django.test.utils import override_settings from django.urls import reverse from organizations.backends.defaults import BaseBackend from organizations.backends.defaults import InvitationBackend from organizations.backends.defaults import RegistrationBackend from organizations.models import Organization from tests.utils import request_factory_login from django.conf import settings from organizations.backends import invitation_backend from organizations.backends import registration_backend and context (functions, classes, or occasionally code) from other files: # Path: tests/utils.py # def request_factory_login(factory, user=None, method="request", **kwargs): # """Based on this gist: https://gist.github.com/964472""" # # engine = import_module(settings.SESSION_ENGINE) # request = getattr(factory, method)(**kwargs) # # request.session = engine.SessionStore() # # request.session[SESSION_KEY] = user.pk # request.user = user or AnonymousUser() # return request . Output only the next line.
USE_TZ=True,