Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Given the code snippet: <|code_start|> success_url = reverse_lazy('feeds_list') def get_initial(self): source = self.request.GET.get('source') feed = self.request.GET.get('feed') if source == 'subtome' and feed: return { 'feed_url': feed } def get_form_kwargs(self, **kwargs): kwargs = super(FeedCreateView, self).get_form_kwargs(**kwargs) kwargs['user'] = self.request.user return kwargs def form_valid(self, form): obj = form.save(commit=False) obj.created_by = self.request.user return super(FeedCreateView, self).form_valid(form) class FeedUpdateView(LoginRequiredMixin, UpdateView): model = Feed form_class = FeedCreateForm success_url = '/feeds/edit/%(id)s/' def get_form_kwargs(self, **kwargs): kwargs = super(FeedUpdateView, self).get_form_kwargs(**kwargs) kwargs['user'] = self.request.user <|code_end|> , generate the next line using the imports in this file: from django.views.generic import ListView, CreateView, DeleteView, UpdateView from django.core.urlresolvers import reverse_lazy from django.shortcuts import redirect from braces.views import LoginRequiredMixin from .models import Feed from .forms import FeedCreateForm and context (functions, classes, or occasionally code) from other files: # Path: apps/feeds/models.py # class Feed(models.Model): # feed_url = models.URLField() # list_id = models.IntegerField(blank=True, null=True) # created_by = models.ForeignKey(settings.AUTH_USER_MODEL) # # date_created = models.DateTimeField(auto_now_add=True) # date_modified = models.DateTimeField(auto_now=True) # # class Meta: # unique_together = ('feed_url', 'created_by') # # def __unicode__(self): # return self.feed_url # # Path: apps/feeds/forms.py # class FeedCreateForm(forms.ModelForm): # list_id = forms.ChoiceField(label='List (optional)', required=False) # # class Meta: # model = Feed # fields = ('feed_url', 'list_id') # # def __init__(self, user, *args, **kwargs): # super(FeedCreateForm, self).__init__(*args, **kwargs) # # self.user = user # kippt = user.kippt_client() # meta, lists = kippt.lists() # # LIST_CHOICES = [('', 'Choose a list to store feed items')] # # for kippt_list in lists: # LIST_CHOICES.append((kippt_list['id'], kippt_list['title'])) # # self.fields['list_id'].choices = LIST_CHOICES # # def clean_feed_url(self): # feed_url = self.cleaned_data.get('feed_url') # # feed = feedparser.parse(feed_url) # # if feed.bozo: # raise forms.ValidationError('Invalid Feed URL') # # if not self.instance.pk: # feeds = Feed.objects.filter(created_by=self.user, # feed_url=feed_url) # # if feeds.exists(): # raise forms.ValidationError('Already subscribed to this feed') # # return feed_url # # def clean_list_id(self): # list_id = self.cleaned_data.get('list_id') # # if not list_id or self.user.list_id == int(list_id): # return None # # return list_id # # def save(self, commit=True): # feed = super(FeedCreateForm, self).save(commit=False) # # if commit: # feed.save() # # Subscription.objects.subscribe( # topic=feed.feed_url, # hub=settings.SUPERFEEDR_HUB, # verify='async' # ) # # return feed . Output only the next line.
return kwargs
Predict the next line after this snippet: <|code_start|> self.cleaned_data['api_token'] = user['api_token'] return self.cleaned_data def save(self, commit=True): user, created = KipptUser.objects.get_or_create( username=self.cleaned_data['username'], ) user.api_token = self.cleaned_data['api_token'] user.save() if created: user.set_password(None) return user, created class KipptUserSetupForm(forms.ModelForm): list_id = forms.ChoiceField(label='Default list') class Meta: model = KipptUser fields = ('list_id',) def __init__(self, *args, **kwargs): super(KipptUserSetupForm, self).__init__(*args, **kwargs) kippt = self.instance.kippt_client() <|code_end|> using the current file's imports: from django import forms from kippt import Kippt from .models import KipptUser and any relevant context from other files: # Path: apps/auth/models.py # class KipptUser(AbstractUser): # """ # Defines our custom user model and fields # # """ # api_token = models.CharField(max_length=255) # list_id = models.IntegerField(blank=True, null=True) # # def __unicode__(self): # return self.username # # def kippt_client(self): # return Kippt(self.username, api_token=self.api_token) . Output only the next line.
meta, lists = kippt.lists()
Here is a snippet: <|code_start|>#!/usr/bin/python # -*- coding: utf-8 -*- log = logging.getLogger(__name__) def read_config(scan_config): config_path = os.path.join( os.path.dirname(os.path.realpath(sys.argv[0])), "config.json") if os.path.isfile(config_path): config['CONFIG_PATH'] = config_path <|code_end|> . Write the next line using the current file imports: import logging import sys import json import random import string import os from threading import Thread from pogom import config from pogom.app import Pogom from pogom.models import create_tables from pogom.scan import Scanner, ScanConfig from pogom.utils import get_args, get_encryption_lib_path and context from other files: # Path: pogom/utils.py # def get_args(): # parser = argparse.ArgumentParser() # parser.add_argument('-H', '--host', help='Set web server listening host', default='127.0.0.1') # parser.add_argument('-P', '--port', type=int, help='Set web server listening port', default=5000) # parser.add_argument('--db', help='Connection String to be used. (default: sqlite)', # default='sqlite') # parser.add_argument('-d', '--debug', type=str.lower, help='Debug Level [info|debug]', default=None) # # return parser.parse_args() # # def get_encryption_lib_path(): # # win32 doesn't mean necessarily 32 bits # if sys.platform == "win32" or sys.platform == "cygwin": # if platform.architecture()[0] == '64bit': # lib_name = "encrypt64bit.dll" # else: # lib_name = "encrypt32bit.dll" # # elif sys.platform == "darwin": # lib_name = "libencrypt-osx-64.so" # # elif os.uname()[4].startswith("arm") and platform.architecture()[0] == '32bit': # lib_name = "libencrypt-linux-arm-32.so" # # elif os.uname()[4].startswith("aarch64") and platform.architecture()[0] == '64bit': # lib_name = "libencrypt-linux-arm-64.so" # # elif sys.platform.startswith('linux'): # if "centos" in platform.platform(): # if platform.architecture()[0] == '64bit': # lib_name = "libencrypt-centos-x86-64.so" # else: # lib_name = "libencrypt-linux-x86-32.so" # else: # if platform.architecture()[0] == '64bit': # lib_name = "libencrypt-linux-x86-64.so" # else: # lib_name = "libencrypt-linux-x86-32.so" # # elif sys.platform.startswith('freebsd'): # lib_name = "libencrypt-freebsd-64.so" # # else: # err = "Unexpected/unsupported platform '{}'".format(sys.platform) # log.error(err) # raise Exception(err) # # lib_path = os.path.join(os.path.dirname(__file__), "libencrypt", lib_name) # # if not os.path.isfile(lib_path): # err = "Could not find {} encryption library {}".format(sys.platform, lib_path) # log.error(err) # raise Exception(err) # # return lib_path , which may include functions, classes, or code. Output only the next line.
try:
Given the following code snippet before the placeholder: <|code_start|> if parse_version(ks_version) < parse_version('0.7'): raise Exception("Incompatible Kaitai Struct Python API: 0.7 or later is required, but you have %s" % (ks_version)) class Ipv6Packet(KaitaiStruct): def __init__(self, _io, _parent=None, _root=None): self._io = _io self._parent = _parent self._root = _root if _root else self self._read() def _read(self): self.version = self._io.read_bits_int(4) self.traffic_class = self._io.read_bits_int(8) self.flow_label = self._io.read_bits_int(20) self._io.align_to_byte() self.payload_length = self._io.read_u2be() self.next_header_type = self._io.read_u1() self.hop_limit = self._io.read_u1() self.src_ipv6_addr = self._io.read_bytes(16) self.dst_ipv6_addr = self._io.read_bytes(16) _on = self.next_header_type if _on == 17: self.next_header = UdpDatagram(self._io) elif _on == 0: self.next_header = self._root.OptionHopByHop(self._io, self, self._root) elif _on == 4: self.next_header = Ipv4Packet(self._io) elif _on == 6: self.next_header = TcpSegment(self._io) <|code_end|> , predict the next line using imports from the current file: from pkg_resources import parse_version from kaitaistruct import __version__ as ks_version, KaitaiStruct, KaitaiStream, BytesIO from .udp_datagram import UdpDatagram from .tcp_segment import TcpSegment from .ipv4_packet import Ipv4Packet and context including class names, function names, and sometimes code from other files: # Path: phasortoolbox/parser/pcap/udp_datagram.py # class UdpDatagram(KaitaiStruct): # """UDP is a simple stateless transport layer (AKA OSI layer 4) # protocol, one of the core Internet protocols. It provides source and # destination ports, basic checksumming, but provides not guarantees # of delivery, order of packets, or duplicate delivery. # """ # def __init__(self, _io, _parent=None, _root=None): # self._io = _io # self._parent = _parent # self._root = _root if _root else self # self._read() # # def _read(self): # self.src_port = self._io.read_u2be() # self.dst_port = self._io.read_u2be() # self.length = self._io.read_u2be() # self.checksum = self._io.read_u2be() # self.body = self._io.read_bytes_full() # # Path: phasortoolbox/parser/pcap/tcp_segment.py # class TcpSegment(KaitaiStruct): # def __init__(self, _io, _parent=None, _root=None): # self._io = _io # self._parent = _parent # self._root = _root if _root else self # self._read() # # def _read(self): # self.src_port = self._io.read_u2be() # self.dst_port = self._io.read_u2be() # self.seq_num = self._io.read_u4be() # self.ack_num = self._io.read_u4be() # self.data_offset = self._io.read_bits_int(4) # self.b13 = self._io.read_bits_int(12) # self.window_size = self._io.read_u2be() # self.checksum = self._io.read_u2be() # self.urgent_pointer = self._io.read_u2be() # self.options = self._io.read_bytes(self.data_offset * 4 - 20) # self.body = self._io.read_bytes_full() . Output only the next line.
elif _on == 59:
Using the snippet: <|code_start|> elif _on == 4: self.next_header = Ipv4Packet(self._io) elif _on == 6: self.next_header = TcpSegment(self._io) elif _on == 59: self.next_header = self._root.NoNextHeader(self._io, self, self._root) self.rest = self._io.read_bytes_full() class NoNextHeader(KaitaiStruct): def __init__(self, _io, _parent=None, _root=None): self._io = _io self._parent = _parent self._root = _root if _root else self self._read() def _read(self): pass class OptionHopByHop(KaitaiStruct): def __init__(self, _io, _parent=None, _root=None): self._io = _io self._parent = _parent self._root = _root if _root else self self._read() def _read(self): self.next_header_type = self._io.read_u1() self.hdr_ext_len = self._io.read_u1() self.body = self._io.read_bytes((self.hdr_ext_len - 1)) <|code_end|> , determine the next line of code. You have imports: from pkg_resources import parse_version from kaitaistruct import __version__ as ks_version, KaitaiStruct, KaitaiStream, BytesIO from .udp_datagram import UdpDatagram from .tcp_segment import TcpSegment from .ipv4_packet import Ipv4Packet and context (class names, function names, or code) available: # Path: phasortoolbox/parser/pcap/udp_datagram.py # class UdpDatagram(KaitaiStruct): # """UDP is a simple stateless transport layer (AKA OSI layer 4) # protocol, one of the core Internet protocols. It provides source and # destination ports, basic checksumming, but provides not guarantees # of delivery, order of packets, or duplicate delivery. # """ # def __init__(self, _io, _parent=None, _root=None): # self._io = _io # self._parent = _parent # self._root = _root if _root else self # self._read() # # def _read(self): # self.src_port = self._io.read_u2be() # self.dst_port = self._io.read_u2be() # self.length = self._io.read_u2be() # self.checksum = self._io.read_u2be() # self.body = self._io.read_bytes_full() # # Path: phasortoolbox/parser/pcap/tcp_segment.py # class TcpSegment(KaitaiStruct): # def __init__(self, _io, _parent=None, _root=None): # self._io = _io # self._parent = _parent # self._root = _root if _root else self # self._read() # # def _read(self): # self.src_port = self._io.read_u2be() # self.dst_port = self._io.read_u2be() # self.seq_num = self._io.read_u4be() # self.ack_num = self._io.read_u4be() # self.data_offset = self._io.read_bits_int(4) # self.b13 = self._io.read_bits_int(12) # self.window_size = self._io.read_u2be() # self.checksum = self._io.read_u2be() # self.urgent_pointer = self._io.read_u2be() # self.options = self._io.read_bytes(self.data_offset * 4 - 20) # self.body = self._io.read_bytes_full() . Output only the next line.
_on = self.next_header_type
Using the snippet: <|code_start|>sys.path.append("../../") MockRPi = MagicMock() MockSpidev = MagicMock() modules = { <|code_end|> , determine the next line of code. You have imports: import sys from unittest.mock import patch, MagicMock from gfxlcd.driver.ssd1306.spi import SPI from gfxlcd.driver.ssd1306.ssd1306 import SSD1306 and context (class names, function names, or code) available: # Path: gfxlcd/driver/ssd1306/spi.py # class SPI(Driver): # """SPI driver""" # def __init__(self): # self.pins = { # 'RST': 13, # 'DC': 6, # } # self.spi = None # # def init(self): # """init sequence""" # for pin in self.pins: # GPIO.setup(self.pins[pin], GPIO.OUT) # GPIO.output(self.pins[pin], 0) # # spi = spidev.SpiDev() # spi.open(0, 0) # spi.max_speed_hz = 8000000 # spi.mode = 0 # self.spi = spi # # def reset(self): # """reset device""" # GPIO.output(self.pins['RST'], 1) # time.sleep(0.025) # GPIO.output(self.pins['RST'], 0) # time.sleep(0.025) # GPIO.output(self.pins['RST'], 1) # time.sleep(0.025) # # def cmd(self, data, enable=None): # """send command to device""" # GPIO.output(self.pins['DC'], 0) # self.spi.xfer2([data]) # # def data(self, data, enable=None): # """send data to device""" # GPIO.output(self.pins['DC'], 1) # self.spi.xfer2([data]) # GPIO.output(self.pins['DC'], 0) # # Path: gfxlcd/driver/ssd1306/ssd1306.py # class SSD1306(Page, Chip): # """Class for an LCD with SSD306 chip""" # rotations = { # 0: { # 'sgmt': 0xa1, # 'com': 0xc8 # }, # 90: { # 'sgmt': 0xa0, # 'com': 0xc8 # }, # 180: { # 'sgmt': 0xa0, # 'com': 0xc0 # }, # 270: { # 'sgmt': 0xa1, # 'com': 0xc0 # } # } # # def __init__(self, width, height, driver, auto_flush=False): # Chip.__init__(self, width, height, driver, auto_flush) # Page.__init__(self, driver) # self.rotation = 0 # # def init(self): # """inits a device""" # self.driver.init() # Page.init(self) # Chip.init(self) # self.driver.reset() # self.driver.cmd(0xae) # turn off panel # self.driver.cmd(0x00) # set low column address # self.driver.cmd(0x10) # set high column address # self.driver.cmd(0x40) # set start line address # # self.driver.cmd(0x20) # addr mode # self.driver.cmd(0x02) # horizontal # # self.driver.cmd(0xb0) # set page address # self.driver.cmd(0x81) # set contrast control register # self.driver.cmd(0xff) # # a0/a1, a1 = segment 127 to 0, a0:0 to seg127 # self.driver.cmd(self.rotations[self.rotation]['sgmt']) # # # c8/c0 set com(N-1)to com0 c0:com0 to com(N-1) # self.driver.cmd(self.rotations[self.rotation]['com']) # # self.driver.cmd(0xa6) # set normal display, a6 - normal, a7 - inverted # # self.driver.cmd(0xa8) # set multiplex ratio(16to63) # self.driver.cmd(0x3f) # 1/64 duty # # self.driver.cmd(0xd3) # set display offset # self.driver.cmd(0x00) # not offset # # # set display clock divide ratio/oscillator frequency # self.driver.cmd(0xd5) # self.driver.cmd(0x80) # set divide ratio # # self.driver.cmd(0xd9) # set pre-charge period # self.driver.cmd(0xf1) # self.driver.cmd(0xda) # set com pins hardware configuration # self.driver.cmd(0x12) # # self.driver.cmd(0xdb) # set vcomh # self.driver.cmd(0x40) # # self.driver.cmd(0x8d) # charge pump # self.driver.cmd(0x14) # enable charge pump # self.driver.cmd(0xaf) # turn on panel # # def flush(self, force=None): # """flush buffer to device # :force - boolean|None""" # if force is None: # force = self.options['auto_flush'] # if force: # if self.rotation == 0 or self.rotation == 180: # height, width = self.height, self.width # else: # width, height = self.height, self.width # for j in range(0, height//8): # self.set_area(0, j, width-1, j+1) # for i in range(0, width): # self.driver.data(self.get_page_value(i, j)) # # def set_area(self, pos_x1, pos_y1, pos_x2, pos_y2): # """set area to work on""" # self.driver.cmd(0x22) # self.driver.cmd(0xb0 + pos_y1) # self.driver.cmd(0xb0 + pos_y2) # self.driver.cmd(0x21) # self.driver.cmd(pos_x1) # self.driver.cmd(pos_x2) # # def draw_pixel(self, pos_x, pos_y, color=None): # """draw a pixel at x,y""" # if self.rotation == 90 or self.rotation == 270: # pos_x, pos_y = pos_y, pos_x # Page.draw_pixel(self, pos_x, pos_y, color) . Output only the next line.
"RPi": MockRPi,
Based on the snippet: <|code_start|>sys.path.append("../../") RPi.GPIO.setmode(RPi.GPIO.BCM) lcd_oled = SSD1306(128, 64, SPI()) lcd_oled.init() lcd_oled.auto_flush = False image_file = Image.open("assets/dsp2017_101_64.png") lcd_oled.threshold = 50 <|code_end|> , predict the immediate next line with the help of imports: import RPi.GPIO import sys from PIL import Image from gfxlcd.driver.ssd1306.spi import SPI from gfxlcd.driver.ssd1306.ssd1306 import SSD1306 and context (classes, functions, sometimes code) from other files: # Path: gfxlcd/driver/ssd1306/spi.py # class SPI(Driver): # """SPI driver""" # def __init__(self): # self.pins = { # 'RST': 13, # 'DC': 6, # } # self.spi = None # # def init(self): # """init sequence""" # for pin in self.pins: # GPIO.setup(self.pins[pin], GPIO.OUT) # GPIO.output(self.pins[pin], 0) # # spi = spidev.SpiDev() # spi.open(0, 0) # spi.max_speed_hz = 8000000 # spi.mode = 0 # self.spi = spi # # def reset(self): # """reset device""" # GPIO.output(self.pins['RST'], 1) # time.sleep(0.025) # GPIO.output(self.pins['RST'], 0) # time.sleep(0.025) # GPIO.output(self.pins['RST'], 1) # time.sleep(0.025) # # def cmd(self, data, enable=None): # """send command to device""" # GPIO.output(self.pins['DC'], 0) # self.spi.xfer2([data]) # # def data(self, data, enable=None): # """send data to device""" # GPIO.output(self.pins['DC'], 1) # self.spi.xfer2([data]) # GPIO.output(self.pins['DC'], 0) # # Path: gfxlcd/driver/ssd1306/ssd1306.py # class SSD1306(Page, Chip): # """Class for an LCD with SSD306 chip""" # rotations = { # 0: { # 'sgmt': 0xa1, # 'com': 0xc8 # }, # 90: { # 'sgmt': 0xa0, # 'com': 0xc8 # }, # 180: { # 'sgmt': 0xa0, # 'com': 0xc0 # }, # 270: { # 'sgmt': 0xa1, # 'com': 0xc0 # } # } # # def __init__(self, width, height, driver, auto_flush=False): # Chip.__init__(self, width, height, driver, auto_flush) # Page.__init__(self, driver) # self.rotation = 0 # # def init(self): # """inits a device""" # self.driver.init() # Page.init(self) # Chip.init(self) # self.driver.reset() # self.driver.cmd(0xae) # turn off panel # self.driver.cmd(0x00) # set low column address # self.driver.cmd(0x10) # set high column address # self.driver.cmd(0x40) # set start line address # # self.driver.cmd(0x20) # addr mode # self.driver.cmd(0x02) # horizontal # # self.driver.cmd(0xb0) # set page address # self.driver.cmd(0x81) # set contrast control register # self.driver.cmd(0xff) # # a0/a1, a1 = segment 127 to 0, a0:0 to seg127 # self.driver.cmd(self.rotations[self.rotation]['sgmt']) # # # c8/c0 set com(N-1)to com0 c0:com0 to com(N-1) # self.driver.cmd(self.rotations[self.rotation]['com']) # # self.driver.cmd(0xa6) # set normal display, a6 - normal, a7 - inverted # # self.driver.cmd(0xa8) # set multiplex ratio(16to63) # self.driver.cmd(0x3f) # 1/64 duty # # self.driver.cmd(0xd3) # set display offset # self.driver.cmd(0x00) # not offset # # # set display clock divide ratio/oscillator frequency # self.driver.cmd(0xd5) # self.driver.cmd(0x80) # set divide ratio # # self.driver.cmd(0xd9) # set pre-charge period # self.driver.cmd(0xf1) # self.driver.cmd(0xda) # set com pins hardware configuration # self.driver.cmd(0x12) # # self.driver.cmd(0xdb) # set vcomh # self.driver.cmd(0x40) # # self.driver.cmd(0x8d) # charge pump # self.driver.cmd(0x14) # enable charge pump # self.driver.cmd(0xaf) # turn on panel # # def flush(self, force=None): # """flush buffer to device # :force - boolean|None""" # if force is None: # force = self.options['auto_flush'] # if force: # if self.rotation == 0 or self.rotation == 180: # height, width = self.height, self.width # else: # width, height = self.height, self.width # for j in range(0, height//8): # self.set_area(0, j, width-1, j+1) # for i in range(0, width): # self.driver.data(self.get_page_value(i, j)) # # def set_area(self, pos_x1, pos_y1, pos_x2, pos_y2): # """set area to work on""" # self.driver.cmd(0x22) # self.driver.cmd(0xb0 + pos_y1) # self.driver.cmd(0xb0 + pos_y2) # self.driver.cmd(0x21) # self.driver.cmd(pos_x1) # self.driver.cmd(pos_x2) # # def draw_pixel(self, pos_x, pos_y, color=None): # """draw a pixel at x,y""" # if self.rotation == 90 or self.rotation == 270: # pos_x, pos_y = pos_y, pos_x # Page.draw_pixel(self, pos_x, pos_y, color) . Output only the next line.
lcd_oled.threshold = 0
Based on the snippet: <|code_start|>sys.path.append("../../") RPi.GPIO.setmode(RPi.GPIO.BCM) lcd_oled = SSD1306(128, 64, SPI()) <|code_end|> , predict the immediate next line with the help of imports: import RPi.GPIO import sys from PIL import Image from gfxlcd.driver.ssd1306.spi import SPI from gfxlcd.driver.ssd1306.ssd1306 import SSD1306 and context (classes, functions, sometimes code) from other files: # Path: gfxlcd/driver/ssd1306/spi.py # class SPI(Driver): # """SPI driver""" # def __init__(self): # self.pins = { # 'RST': 13, # 'DC': 6, # } # self.spi = None # # def init(self): # """init sequence""" # for pin in self.pins: # GPIO.setup(self.pins[pin], GPIO.OUT) # GPIO.output(self.pins[pin], 0) # # spi = spidev.SpiDev() # spi.open(0, 0) # spi.max_speed_hz = 8000000 # spi.mode = 0 # self.spi = spi # # def reset(self): # """reset device""" # GPIO.output(self.pins['RST'], 1) # time.sleep(0.025) # GPIO.output(self.pins['RST'], 0) # time.sleep(0.025) # GPIO.output(self.pins['RST'], 1) # time.sleep(0.025) # # def cmd(self, data, enable=None): # """send command to device""" # GPIO.output(self.pins['DC'], 0) # self.spi.xfer2([data]) # # def data(self, data, enable=None): # """send data to device""" # GPIO.output(self.pins['DC'], 1) # self.spi.xfer2([data]) # GPIO.output(self.pins['DC'], 0) # # Path: gfxlcd/driver/ssd1306/ssd1306.py # class SSD1306(Page, Chip): # """Class for an LCD with SSD306 chip""" # rotations = { # 0: { # 'sgmt': 0xa1, # 'com': 0xc8 # }, # 90: { # 'sgmt': 0xa0, # 'com': 0xc8 # }, # 180: { # 'sgmt': 0xa0, # 'com': 0xc0 # }, # 270: { # 'sgmt': 0xa1, # 'com': 0xc0 # } # } # # def __init__(self, width, height, driver, auto_flush=False): # Chip.__init__(self, width, height, driver, auto_flush) # Page.__init__(self, driver) # self.rotation = 0 # # def init(self): # """inits a device""" # self.driver.init() # Page.init(self) # Chip.init(self) # self.driver.reset() # self.driver.cmd(0xae) # turn off panel # self.driver.cmd(0x00) # set low column address # self.driver.cmd(0x10) # set high column address # self.driver.cmd(0x40) # set start line address # # self.driver.cmd(0x20) # addr mode # self.driver.cmd(0x02) # horizontal # # self.driver.cmd(0xb0) # set page address # self.driver.cmd(0x81) # set contrast control register # self.driver.cmd(0xff) # # a0/a1, a1 = segment 127 to 0, a0:0 to seg127 # self.driver.cmd(self.rotations[self.rotation]['sgmt']) # # # c8/c0 set com(N-1)to com0 c0:com0 to com(N-1) # self.driver.cmd(self.rotations[self.rotation]['com']) # # self.driver.cmd(0xa6) # set normal display, a6 - normal, a7 - inverted # # self.driver.cmd(0xa8) # set multiplex ratio(16to63) # self.driver.cmd(0x3f) # 1/64 duty # # self.driver.cmd(0xd3) # set display offset # self.driver.cmd(0x00) # not offset # # # set display clock divide ratio/oscillator frequency # self.driver.cmd(0xd5) # self.driver.cmd(0x80) # set divide ratio # # self.driver.cmd(0xd9) # set pre-charge period # self.driver.cmd(0xf1) # self.driver.cmd(0xda) # set com pins hardware configuration # self.driver.cmd(0x12) # # self.driver.cmd(0xdb) # set vcomh # self.driver.cmd(0x40) # # self.driver.cmd(0x8d) # charge pump # self.driver.cmd(0x14) # enable charge pump # self.driver.cmd(0xaf) # turn on panel # # def flush(self, force=None): # """flush buffer to device # :force - boolean|None""" # if force is None: # force = self.options['auto_flush'] # if force: # if self.rotation == 0 or self.rotation == 180: # height, width = self.height, self.width # else: # width, height = self.height, self.width # for j in range(0, height//8): # self.set_area(0, j, width-1, j+1) # for i in range(0, width): # self.driver.data(self.get_page_value(i, j)) # # def set_area(self, pos_x1, pos_y1, pos_x2, pos_y2): # """set area to work on""" # self.driver.cmd(0x22) # self.driver.cmd(0xb0 + pos_y1) # self.driver.cmd(0xb0 + pos_y2) # self.driver.cmd(0x21) # self.driver.cmd(pos_x1) # self.driver.cmd(pos_x2) # # def draw_pixel(self, pos_x, pos_y, color=None): # """draw a pixel at x,y""" # if self.rotation == 90 or self.rotation == 270: # pos_x, pos_y = pos_y, pos_x # Page.draw_pixel(self, pos_x, pos_y, color) . Output only the next line.
lcd_oled.init()
Given the following code snippet before the placeholder: <|code_start|>sys.path.append("../../") RPi.GPIO.setmode(RPi.GPIO.BCM) def hole(o, x, y): o.draw_pixel(x+1, y) <|code_end|> , predict the next line using imports from the current file: import RPi.GPIO import sys import random from gfxlcd.driver.ssd1306.spi import SPI from gfxlcd.driver.ssd1306.ssd1306 import SSD1306 and context including class names, function names, and sometimes code from other files: # Path: gfxlcd/driver/ssd1306/spi.py # class SPI(Driver): # """SPI driver""" # def __init__(self): # self.pins = { # 'RST': 13, # 'DC': 6, # } # self.spi = None # # def init(self): # """init sequence""" # for pin in self.pins: # GPIO.setup(self.pins[pin], GPIO.OUT) # GPIO.output(self.pins[pin], 0) # # spi = spidev.SpiDev() # spi.open(0, 0) # spi.max_speed_hz = 8000000 # spi.mode = 0 # self.spi = spi # # def reset(self): # """reset device""" # GPIO.output(self.pins['RST'], 1) # time.sleep(0.025) # GPIO.output(self.pins['RST'], 0) # time.sleep(0.025) # GPIO.output(self.pins['RST'], 1) # time.sleep(0.025) # # def cmd(self, data, enable=None): # """send command to device""" # GPIO.output(self.pins['DC'], 0) # self.spi.xfer2([data]) # # def data(self, data, enable=None): # """send data to device""" # GPIO.output(self.pins['DC'], 1) # self.spi.xfer2([data]) # GPIO.output(self.pins['DC'], 0) # # Path: gfxlcd/driver/ssd1306/ssd1306.py # class SSD1306(Page, Chip): # """Class for an LCD with SSD306 chip""" # rotations = { # 0: { # 'sgmt': 0xa1, # 'com': 0xc8 # }, # 90: { # 'sgmt': 0xa0, # 'com': 0xc8 # }, # 180: { # 'sgmt': 0xa0, # 'com': 0xc0 # }, # 270: { # 'sgmt': 0xa1, # 'com': 0xc0 # } # } # # def __init__(self, width, height, driver, auto_flush=False): # Chip.__init__(self, width, height, driver, auto_flush) # Page.__init__(self, driver) # self.rotation = 0 # # def init(self): # """inits a device""" # self.driver.init() # Page.init(self) # Chip.init(self) # self.driver.reset() # self.driver.cmd(0xae) # turn off panel # self.driver.cmd(0x00) # set low column address # self.driver.cmd(0x10) # set high column address # self.driver.cmd(0x40) # set start line address # # self.driver.cmd(0x20) # addr mode # self.driver.cmd(0x02) # horizontal # # self.driver.cmd(0xb0) # set page address # self.driver.cmd(0x81) # set contrast control register # self.driver.cmd(0xff) # # a0/a1, a1 = segment 127 to 0, a0:0 to seg127 # self.driver.cmd(self.rotations[self.rotation]['sgmt']) # # # c8/c0 set com(N-1)to com0 c0:com0 to com(N-1) # self.driver.cmd(self.rotations[self.rotation]['com']) # # self.driver.cmd(0xa6) # set normal display, a6 - normal, a7 - inverted # # self.driver.cmd(0xa8) # set multiplex ratio(16to63) # self.driver.cmd(0x3f) # 1/64 duty # # self.driver.cmd(0xd3) # set display offset # self.driver.cmd(0x00) # not offset # # # set display clock divide ratio/oscillator frequency # self.driver.cmd(0xd5) # self.driver.cmd(0x80) # set divide ratio # # self.driver.cmd(0xd9) # set pre-charge period # self.driver.cmd(0xf1) # self.driver.cmd(0xda) # set com pins hardware configuration # self.driver.cmd(0x12) # # self.driver.cmd(0xdb) # set vcomh # self.driver.cmd(0x40) # # self.driver.cmd(0x8d) # charge pump # self.driver.cmd(0x14) # enable charge pump # self.driver.cmd(0xaf) # turn on panel # # def flush(self, force=None): # """flush buffer to device # :force - boolean|None""" # if force is None: # force = self.options['auto_flush'] # if force: # if self.rotation == 0 or self.rotation == 180: # height, width = self.height, self.width # else: # width, height = self.height, self.width # for j in range(0, height//8): # self.set_area(0, j, width-1, j+1) # for i in range(0, width): # self.driver.data(self.get_page_value(i, j)) # # def set_area(self, pos_x1, pos_y1, pos_x2, pos_y2): # """set area to work on""" # self.driver.cmd(0x22) # self.driver.cmd(0xb0 + pos_y1) # self.driver.cmd(0xb0 + pos_y2) # self.driver.cmd(0x21) # self.driver.cmd(pos_x1) # self.driver.cmd(pos_x2) # # def draw_pixel(self, pos_x, pos_y, color=None): # """draw a pixel at x,y""" # if self.rotation == 90 or self.rotation == 270: # pos_x, pos_y = pos_y, pos_x # Page.draw_pixel(self, pos_x, pos_y, color) . Output only the next line.
o.draw_pixel(x+2, y)
Based on the snippet: <|code_start|>sys.path.append("../../") RPi.GPIO.setmode(RPi.GPIO.BCM) lcd_oled = SSD1306(128, 64, SPI()) lcd_oled.rotation = 270 lcd_oled.init() lcd_oled.auto_flush = False <|code_end|> , predict the immediate next line with the help of imports: import RPi.GPIO import sys from PIL import Image from gfxlcd.driver.ssd1306.spi import SPI from gfxlcd.driver.ssd1306.ssd1306 import SSD1306 and context (classes, functions, sometimes code) from other files: # Path: gfxlcd/driver/ssd1306/spi.py # class SPI(Driver): # """SPI driver""" # def __init__(self): # self.pins = { # 'RST': 13, # 'DC': 6, # } # self.spi = None # # def init(self): # """init sequence""" # for pin in self.pins: # GPIO.setup(self.pins[pin], GPIO.OUT) # GPIO.output(self.pins[pin], 0) # # spi = spidev.SpiDev() # spi.open(0, 0) # spi.max_speed_hz = 8000000 # spi.mode = 0 # self.spi = spi # # def reset(self): # """reset device""" # GPIO.output(self.pins['RST'], 1) # time.sleep(0.025) # GPIO.output(self.pins['RST'], 0) # time.sleep(0.025) # GPIO.output(self.pins['RST'], 1) # time.sleep(0.025) # # def cmd(self, data, enable=None): # """send command to device""" # GPIO.output(self.pins['DC'], 0) # self.spi.xfer2([data]) # # def data(self, data, enable=None): # """send data to device""" # GPIO.output(self.pins['DC'], 1) # self.spi.xfer2([data]) # GPIO.output(self.pins['DC'], 0) # # Path: gfxlcd/driver/ssd1306/ssd1306.py # class SSD1306(Page, Chip): # """Class for an LCD with SSD306 chip""" # rotations = { # 0: { # 'sgmt': 0xa1, # 'com': 0xc8 # }, # 90: { # 'sgmt': 0xa0, # 'com': 0xc8 # }, # 180: { # 'sgmt': 0xa0, # 'com': 0xc0 # }, # 270: { # 'sgmt': 0xa1, # 'com': 0xc0 # } # } # # def __init__(self, width, height, driver, auto_flush=False): # Chip.__init__(self, width, height, driver, auto_flush) # Page.__init__(self, driver) # self.rotation = 0 # # def init(self): # """inits a device""" # self.driver.init() # Page.init(self) # Chip.init(self) # self.driver.reset() # self.driver.cmd(0xae) # turn off panel # self.driver.cmd(0x00) # set low column address # self.driver.cmd(0x10) # set high column address # self.driver.cmd(0x40) # set start line address # # self.driver.cmd(0x20) # addr mode # self.driver.cmd(0x02) # horizontal # # self.driver.cmd(0xb0) # set page address # self.driver.cmd(0x81) # set contrast control register # self.driver.cmd(0xff) # # a0/a1, a1 = segment 127 to 0, a0:0 to seg127 # self.driver.cmd(self.rotations[self.rotation]['sgmt']) # # # c8/c0 set com(N-1)to com0 c0:com0 to com(N-1) # self.driver.cmd(self.rotations[self.rotation]['com']) # # self.driver.cmd(0xa6) # set normal display, a6 - normal, a7 - inverted # # self.driver.cmd(0xa8) # set multiplex ratio(16to63) # self.driver.cmd(0x3f) # 1/64 duty # # self.driver.cmd(0xd3) # set display offset # self.driver.cmd(0x00) # not offset # # # set display clock divide ratio/oscillator frequency # self.driver.cmd(0xd5) # self.driver.cmd(0x80) # set divide ratio # # self.driver.cmd(0xd9) # set pre-charge period # self.driver.cmd(0xf1) # self.driver.cmd(0xda) # set com pins hardware configuration # self.driver.cmd(0x12) # # self.driver.cmd(0xdb) # set vcomh # self.driver.cmd(0x40) # # self.driver.cmd(0x8d) # charge pump # self.driver.cmd(0x14) # enable charge pump # self.driver.cmd(0xaf) # turn on panel # # def flush(self, force=None): # """flush buffer to device # :force - boolean|None""" # if force is None: # force = self.options['auto_flush'] # if force: # if self.rotation == 0 or self.rotation == 180: # height, width = self.height, self.width # else: # width, height = self.height, self.width # for j in range(0, height//8): # self.set_area(0, j, width-1, j+1) # for i in range(0, width): # self.driver.data(self.get_page_value(i, j)) # # def set_area(self, pos_x1, pos_y1, pos_x2, pos_y2): # """set area to work on""" # self.driver.cmd(0x22) # self.driver.cmd(0xb0 + pos_y1) # self.driver.cmd(0xb0 + pos_y2) # self.driver.cmd(0x21) # self.driver.cmd(pos_x1) # self.driver.cmd(pos_x2) # # def draw_pixel(self, pos_x, pos_y, color=None): # """draw a pixel at x,y""" # if self.rotation == 90 or self.rotation == 270: # pos_x, pos_y = pos_y, pos_x # Page.draw_pixel(self, pos_x, pos_y, color) . Output only the next line.
image_file = Image.open("assets/20x20.png")
Here is a snippet: <|code_start|>sys.path.append("../../") RPi.GPIO.setmode(RPi.GPIO.BCM) lcd_oled = SSD1306(128, 64, SPI()) lcd_oled.rotation = 270 <|code_end|> . Write the next line using the current file imports: import RPi.GPIO import sys from PIL import Image from gfxlcd.driver.ssd1306.spi import SPI from gfxlcd.driver.ssd1306.ssd1306 import SSD1306 and context from other files: # Path: gfxlcd/driver/ssd1306/spi.py # class SPI(Driver): # """SPI driver""" # def __init__(self): # self.pins = { # 'RST': 13, # 'DC': 6, # } # self.spi = None # # def init(self): # """init sequence""" # for pin in self.pins: # GPIO.setup(self.pins[pin], GPIO.OUT) # GPIO.output(self.pins[pin], 0) # # spi = spidev.SpiDev() # spi.open(0, 0) # spi.max_speed_hz = 8000000 # spi.mode = 0 # self.spi = spi # # def reset(self): # """reset device""" # GPIO.output(self.pins['RST'], 1) # time.sleep(0.025) # GPIO.output(self.pins['RST'], 0) # time.sleep(0.025) # GPIO.output(self.pins['RST'], 1) # time.sleep(0.025) # # def cmd(self, data, enable=None): # """send command to device""" # GPIO.output(self.pins['DC'], 0) # self.spi.xfer2([data]) # # def data(self, data, enable=None): # """send data to device""" # GPIO.output(self.pins['DC'], 1) # self.spi.xfer2([data]) # GPIO.output(self.pins['DC'], 0) # # Path: gfxlcd/driver/ssd1306/ssd1306.py # class SSD1306(Page, Chip): # """Class for an LCD with SSD306 chip""" # rotations = { # 0: { # 'sgmt': 0xa1, # 'com': 0xc8 # }, # 90: { # 'sgmt': 0xa0, # 'com': 0xc8 # }, # 180: { # 'sgmt': 0xa0, # 'com': 0xc0 # }, # 270: { # 'sgmt': 0xa1, # 'com': 0xc0 # } # } # # def __init__(self, width, height, driver, auto_flush=False): # Chip.__init__(self, width, height, driver, auto_flush) # Page.__init__(self, driver) # self.rotation = 0 # # def init(self): # """inits a device""" # self.driver.init() # Page.init(self) # Chip.init(self) # self.driver.reset() # self.driver.cmd(0xae) # turn off panel # self.driver.cmd(0x00) # set low column address # self.driver.cmd(0x10) # set high column address # self.driver.cmd(0x40) # set start line address # # self.driver.cmd(0x20) # addr mode # self.driver.cmd(0x02) # horizontal # # self.driver.cmd(0xb0) # set page address # self.driver.cmd(0x81) # set contrast control register # self.driver.cmd(0xff) # # a0/a1, a1 = segment 127 to 0, a0:0 to seg127 # self.driver.cmd(self.rotations[self.rotation]['sgmt']) # # # c8/c0 set com(N-1)to com0 c0:com0 to com(N-1) # self.driver.cmd(self.rotations[self.rotation]['com']) # # self.driver.cmd(0xa6) # set normal display, a6 - normal, a7 - inverted # # self.driver.cmd(0xa8) # set multiplex ratio(16to63) # self.driver.cmd(0x3f) # 1/64 duty # # self.driver.cmd(0xd3) # set display offset # self.driver.cmd(0x00) # not offset # # # set display clock divide ratio/oscillator frequency # self.driver.cmd(0xd5) # self.driver.cmd(0x80) # set divide ratio # # self.driver.cmd(0xd9) # set pre-charge period # self.driver.cmd(0xf1) # self.driver.cmd(0xda) # set com pins hardware configuration # self.driver.cmd(0x12) # # self.driver.cmd(0xdb) # set vcomh # self.driver.cmd(0x40) # # self.driver.cmd(0x8d) # charge pump # self.driver.cmd(0x14) # enable charge pump # self.driver.cmd(0xaf) # turn on panel # # def flush(self, force=None): # """flush buffer to device # :force - boolean|None""" # if force is None: # force = self.options['auto_flush'] # if force: # if self.rotation == 0 or self.rotation == 180: # height, width = self.height, self.width # else: # width, height = self.height, self.width # for j in range(0, height//8): # self.set_area(0, j, width-1, j+1) # for i in range(0, width): # self.driver.data(self.get_page_value(i, j)) # # def set_area(self, pos_x1, pos_y1, pos_x2, pos_y2): # """set area to work on""" # self.driver.cmd(0x22) # self.driver.cmd(0xb0 + pos_y1) # self.driver.cmd(0xb0 + pos_y2) # self.driver.cmd(0x21) # self.driver.cmd(pos_x1) # self.driver.cmd(pos_x2) # # def draw_pixel(self, pos_x, pos_y, color=None): # """draw a pixel at x,y""" # if self.rotation == 90 or self.rotation == 270: # pos_x, pos_y = pos_y, pos_x # Page.draw_pixel(self, pos_x, pos_y, color) , which may include functions, classes, or code. Output only the next line.
lcd_oled.init()
Next line prediction: <|code_start|>sys.path.append("../../") class TestPageDrawing(object): def setUp(self): self.lcd = NullPage(10, 16, None, False) <|code_end|> . Use current file imports: (import sys from nose.tools import assert_equal from gfxlcd.driver.null.null_page import NullPage) and context including class names, function names, or small code snippets from other files: # Path: gfxlcd/driver/null/null_page.py # class NullPage(Page, Chip): # """Test chip driver for page drawing""" # def __init__(self, width, height, driver, auto_flush=True): # Chip.__init__(self, width, height, driver, auto_flush) # Page.__init__(self, driver) # self.rotation = 0 # self.buffer = [] # self.area = { # 'start_x': 0, # 'start_y': 0, # 'end_x': width-1, # 'end_y': height-1 # } # # def init(self): # """inits a device""" # Page.init(self) # Chip.init(self) # # def flush(self, force=None): # """flush buffer to device # :force - boolean|None""" # return self.buffer # # def set_area(self, pos_x1, pos_y1, pos_x2, pos_y2): # """set area to work on""" # self.area = { # 'start_x': pos_x1, # 'start_y': pos_y1, # 'end_x': pos_x2, # 'end_y': pos_y2 # } . Output only the next line.
self.lcd.init()
Given the following code snippet before the placeholder: <|code_start|>__author__ = 'kosci' sys.path.append("../../") class TestChip(object): def setUp(self): self.lcd = NullPage(10, 16, None, False) def test_rotate_by_0(self): <|code_end|> , predict the next line using imports from the current file: import sys from nose.tools import assert_equal from gfxlcd.driver.null.null_page import NullPage and context including class names, function names, and sometimes code from other files: # Path: gfxlcd/driver/null/null_page.py # class NullPage(Page, Chip): # """Test chip driver for page drawing""" # def __init__(self, width, height, driver, auto_flush=True): # Chip.__init__(self, width, height, driver, auto_flush) # Page.__init__(self, driver) # self.rotation = 0 # self.buffer = [] # self.area = { # 'start_x': 0, # 'start_y': 0, # 'end_x': width-1, # 'end_y': height-1 # } # # def init(self): # """inits a device""" # Page.init(self) # Chip.init(self) # # def flush(self, force=None): # """flush buffer to device # :force - boolean|None""" # return self.buffer # # def set_area(self, pos_x1, pos_y1, pos_x2, pos_y2): # """set area to work on""" # self.area = { # 'start_x': pos_x1, # 'start_y': pos_y1, # 'end_x': pos_x2, # 'end_y': pos_y2 # } . Output only the next line.
self.lcd.rotation = 0
Given the following code snippet before the placeholder: <|code_start|>__author__ = 'kosci' sys.path.append("../../") class TestChip(object): def setUp(self): self.gfx_lcd = NullPage(132, 16, None, False) self.drv = HD44780(self.gfx_lcd) self.output = [" ".ljust(16, " ") for i in range(0, 2)] <|code_end|> , predict the next line using imports from the current file: import sys from nose.tools import assert_equal from gfxlcd.driver.null.null_page import NullPage from gfxlcd.driver.hd44780 import HD44780 from charlcd.buffered import CharLCD and context including class names, function names, and sometimes code from other files: # Path: gfxlcd/driver/null/null_page.py # class NullPage(Page, Chip): # """Test chip driver for page drawing""" # def __init__(self, width, height, driver, auto_flush=True): # Chip.__init__(self, width, height, driver, auto_flush) # Page.__init__(self, driver) # self.rotation = 0 # self.buffer = [] # self.area = { # 'start_x': 0, # 'start_y': 0, # 'end_x': width-1, # 'end_y': height-1 # } # # def init(self): # """inits a device""" # Page.init(self) # Chip.init(self) # # def flush(self, force=None): # """flush buffer to device # :force - boolean|None""" # return self.buffer # # def set_area(self, pos_x1, pos_y1, pos_x2, pos_y2): # """set area to work on""" # self.area = { # 'start_x': pos_x1, # 'start_y': pos_y1, # 'end_x': pos_x2, # 'end_y': pos_y2 # } # # Path: gfxlcd/driver/hd44780.py # class HD44780(BaseDriver, FlushEvent): # """HD44780 driver for GfxLCD""" # def __init__(self, gfxlcd, lcd_flush=False): # """Class init""" # self.gfxlcd = gfxlcd # self.mode = 0 # self.initialized = False # self.lcd_flush = lcd_flush # self.font = self.gfxlcd.options['font'] # self.width = self.gfxlcd.width // self.font.size[0] # self.height = self.gfxlcd.height // self.font.size[1] # self.pins = { # 'E2': None # } # self.position = { # 'x': 0, # 'y': 0 # } # self.address = [] # # def init(self): # """init function""" # if self.initialized: # return # for address in range(self.height): # self.address.append(100 + (address * self.width)) # # self.gfxlcd.init() # self.initialized = True # # def cmd(self, char, enable=0): # """write command - set cursor position""" # if char < 100: # return # char -= 100 # pos_y = char // self.width # pos_x = char - (pos_y * self.width) # self.position = { # 'x': pos_x * self.font.size[0], # 'y': pos_y * self.font.size[1] # } # # def shutdown(self): # """shutdown procedure""" # pass # # def send(self, enable=0): # """send ack command""" # pass # # def write(self, char, enable=0): # """write data to lcd""" # pass # # def char(self, char, enable=0): # """write char to lcd""" # self.gfxlcd.draw_text( # self.position['x'], self.position['y'], char, True # ) # self._increase_x() # # def set_mode(self, mode): # """sets driver mode. 4/8 bit""" # self.mode = mode # # def _increase_x(self): # self.position['x'] += self.font.size[0] # # def get_line_address(self, idx): # return self.address[idx] # # def pre_flush(self, buffer): # pass # # def post_flush(self, buffer): # """called after flush()""" # if self.lcd_flush: # self.gfxlcd.flush(True) . Output only the next line.
def get_lcd(self):
Continue the code snippet: <|code_start|> class TestChip(object): def setUp(self): self.gfx_lcd = NullPage(132, 16, None, False) self.drv = HD44780(self.gfx_lcd) self.output = [" ".ljust(16, " ") for i in range(0, 2)] def get_lcd(self): lcd = CharLCD(self.drv.width, self.drv.height, self.drv, 0, 0) lcd.init() return lcd def test_get_size_in_chars(self): assert_equal(16, self.drv.width) assert_equal(2, self.drv.height) def test_init_small_hd44780(self): lcd = CharLCD(self.drv.width, self.drv.height, self.drv, 0, 0) lcd.init() def test_write_to_buffer(self): lcd = self.get_lcd() lcd.write('Hello') lcd.write(' world', 0, 1) self.output[0] = "Hello" + " ".ljust(11, " ") self.output[1] = " world" + " ".ljust(6, " ") assert_equal(lcd.buffer, self.output) def test_flush(self): lcd = self.get_lcd() <|code_end|> . Use current file imports: import sys from nose.tools import assert_equal from gfxlcd.driver.null.null_page import NullPage from gfxlcd.driver.hd44780 import HD44780 from charlcd.buffered import CharLCD and context (classes, functions, or code) from other files: # Path: gfxlcd/driver/null/null_page.py # class NullPage(Page, Chip): # """Test chip driver for page drawing""" # def __init__(self, width, height, driver, auto_flush=True): # Chip.__init__(self, width, height, driver, auto_flush) # Page.__init__(self, driver) # self.rotation = 0 # self.buffer = [] # self.area = { # 'start_x': 0, # 'start_y': 0, # 'end_x': width-1, # 'end_y': height-1 # } # # def init(self): # """inits a device""" # Page.init(self) # Chip.init(self) # # def flush(self, force=None): # """flush buffer to device # :force - boolean|None""" # return self.buffer # # def set_area(self, pos_x1, pos_y1, pos_x2, pos_y2): # """set area to work on""" # self.area = { # 'start_x': pos_x1, # 'start_y': pos_y1, # 'end_x': pos_x2, # 'end_y': pos_y2 # } # # Path: gfxlcd/driver/hd44780.py # class HD44780(BaseDriver, FlushEvent): # """HD44780 driver for GfxLCD""" # def __init__(self, gfxlcd, lcd_flush=False): # """Class init""" # self.gfxlcd = gfxlcd # self.mode = 0 # self.initialized = False # self.lcd_flush = lcd_flush # self.font = self.gfxlcd.options['font'] # self.width = self.gfxlcd.width // self.font.size[0] # self.height = self.gfxlcd.height // self.font.size[1] # self.pins = { # 'E2': None # } # self.position = { # 'x': 0, # 'y': 0 # } # self.address = [] # # def init(self): # """init function""" # if self.initialized: # return # for address in range(self.height): # self.address.append(100 + (address * self.width)) # # self.gfxlcd.init() # self.initialized = True # # def cmd(self, char, enable=0): # """write command - set cursor position""" # if char < 100: # return # char -= 100 # pos_y = char // self.width # pos_x = char - (pos_y * self.width) # self.position = { # 'x': pos_x * self.font.size[0], # 'y': pos_y * self.font.size[1] # } # # def shutdown(self): # """shutdown procedure""" # pass # # def send(self, enable=0): # """send ack command""" # pass # # def write(self, char, enable=0): # """write data to lcd""" # pass # # def char(self, char, enable=0): # """write char to lcd""" # self.gfxlcd.draw_text( # self.position['x'], self.position['y'], char, True # ) # self._increase_x() # # def set_mode(self, mode): # """sets driver mode. 4/8 bit""" # self.mode = mode # # def _increase_x(self): # self.position['x'] += self.font.size[0] # # def get_line_address(self, idx): # return self.address[idx] # # def pre_flush(self, buffer): # pass # # def post_flush(self, buffer): # """called after flush()""" # if self.lcd_flush: # self.gfxlcd.flush(True) . Output only the next line.
lcd.write('Hello')
Here is a snippet: <|code_start|> buffer[8][14] = self.color_white buffer[9][15] = self.color_white assert_equal(self.drv.buffer, buffer) def test_draw_diagonal_line_even_steps_even_rest(self): self.lcd.draw_line(0, 0, 9, 5) buffer = self.get_buffer() buffer[0][0] = self.color_white buffer[1][1] = self.color_white buffer[2][1] = self.color_white buffer[3][2] = self.color_white buffer[4][2] = self.color_white buffer[5][3] = self.color_white buffer[6][3] = self.color_white buffer[7][4] = self.color_white buffer[8][4] = self.color_white buffer[9][5] = self.color_white assert_equal(self.drv.buffer, buffer) def test_draw_diagonal_line_odd_steps_even_rest(self): self.lcd.draw_line(0, 0, 9, 6) buffer = self.get_buffer() buffer[0][0] = self.color_white buffer[1][1] = self.color_white buffer[2][2] = self.color_white buffer[3][2] = self.color_white buffer[4][3] = self.color_white buffer[5][3] = self.color_white buffer[6][4] = self.color_white buffer[7][4] = self.color_white <|code_end|> . Write the next line using the current file imports: import sys from nose.tools import assert_equal from gfxlcd.driver.null.null_area import NullArea from gfxlcd.driver.null.area_driver import AreaDriver and context from other files: # Path: gfxlcd/driver/null/null_area.py # class NullArea(Area, Chip): # """Test chip driver for area drawing""" # def __init__(self, width, height, driver, auto_flush=True): # Chip.__init__(self, width, height, driver, auto_flush) # Area.__init__(self, driver) # self.rotation = 0 # # def _convert_color(self, color): # """color color""" # return color # # def init(self): # """init display""" # self.driver.init() # Area.init(self) # Chip.init(self) # self.driver.reset() # # def _set_area(self, pos_x1, pos_y1, pos_x2, pos_y2): # """set area to work on""" # self.driver.area = { # 'start_x': pos_x1, # 'start_y': pos_y1, # 'end_x': pos_x2, # 'end_y': pos_y2 # } # self.driver.pointer = (0, 0) # # Path: gfxlcd/driver/null/area_driver.py # class AreaDriver(Driver): # """Null communication driver""" # def __init__(self, width, height): # self.height = height # self.width = width # self.buffer = [[0] * self.height for x in range(self.width)] # self.area = { # 'start_x': 0, # 'start_y': 0, # 'end_x': width, # 'end_y': height # } # self.pointer = (0, 0) # # def init(self): # """initialize pins""" # pass # # def reset(self): # """reset a display""" # pass # # def cmd(self, data, enable): # """send command to display""" # pass # # def data(self, data, enable): # """send data to display""" # app_x, app_y = self.pointer # self.buffer[ # self.area['start_x'] + app_x][self.area['start_y'] + app_y # ] = data # self._inc_pointer() # # def _inc_pointer(self): # app_x, app_y = self.pointer # app_x += 1 # if self.area['start_x'] + app_x > self.area['end_x']: # app_x = 0 # app_y += 1 # # if self.area['start_y'] + app_y > self.area['end_y']: # app_x = 0 # app_y = 0 # # self.pointer = (app_x, app_y) , which may include functions, classes, or code. Output only the next line.
buffer[8][5] = self.color_white
Using the snippet: <|code_start|> self.lcd.draw_line(1, 1, 8, 1) self.lcd.draw_line(1, 1, 1, 14) buffer = self.get_buffer() buffer[1][1] = self.color_white buffer[2][1] = self.color_white buffer[3][1] = self.color_white buffer[4][1] = self.color_white buffer[5][1] = self.color_white buffer[6][1] = self.color_white buffer[7][1] = self.color_white buffer[8][1] = self.color_white buffer[1][1] = self.color_white buffer[1][2] = self.color_white buffer[1][3] = self.color_white buffer[1][4] = self.color_white buffer[1][5] = self.color_white buffer[1][6] = self.color_white buffer[1][7] = self.color_white buffer[1][8] = self.color_white buffer[1][9] = self.color_white buffer[1][10] = self.color_white buffer[1][11] = self.color_white buffer[1][12] = self.color_white buffer[1][13] = self.color_white buffer[1][14] = self.color_white assert_equal(self.drv.buffer, buffer) def test_draw_diagonal_line(self): self.lcd.draw_line(0, 0, 9, 1) buffer = self.get_buffer() <|code_end|> , determine the next line of code. You have imports: import sys from nose.tools import assert_equal from gfxlcd.driver.null.null_area import NullArea from gfxlcd.driver.null.area_driver import AreaDriver and context (class names, function names, or code) available: # Path: gfxlcd/driver/null/null_area.py # class NullArea(Area, Chip): # """Test chip driver for area drawing""" # def __init__(self, width, height, driver, auto_flush=True): # Chip.__init__(self, width, height, driver, auto_flush) # Area.__init__(self, driver) # self.rotation = 0 # # def _convert_color(self, color): # """color color""" # return color # # def init(self): # """init display""" # self.driver.init() # Area.init(self) # Chip.init(self) # self.driver.reset() # # def _set_area(self, pos_x1, pos_y1, pos_x2, pos_y2): # """set area to work on""" # self.driver.area = { # 'start_x': pos_x1, # 'start_y': pos_y1, # 'end_x': pos_x2, # 'end_y': pos_y2 # } # self.driver.pointer = (0, 0) # # Path: gfxlcd/driver/null/area_driver.py # class AreaDriver(Driver): # """Null communication driver""" # def __init__(self, width, height): # self.height = height # self.width = width # self.buffer = [[0] * self.height for x in range(self.width)] # self.area = { # 'start_x': 0, # 'start_y': 0, # 'end_x': width, # 'end_y': height # } # self.pointer = (0, 0) # # def init(self): # """initialize pins""" # pass # # def reset(self): # """reset a display""" # pass # # def cmd(self, data, enable): # """send command to display""" # pass # # def data(self, data, enable): # """send data to display""" # app_x, app_y = self.pointer # self.buffer[ # self.area['start_x'] + app_x][self.area['start_y'] + app_y # ] = data # self._inc_pointer() # # def _inc_pointer(self): # app_x, app_y = self.pointer # app_x += 1 # if self.area['start_x'] + app_x > self.area['end_x']: # app_x = 0 # app_y += 1 # # if self.area['start_y'] + app_y > self.area['end_y']: # app_x = 0 # app_y = 0 # # self.pointer = (app_x, app_y) . Output only the next line.
buffer[0][0] = self.color_white
Next line prediction: <|code_start|>from __future__ import absolute_import from __future__ import print_function class Network(Model): def __init__(self, dim, batch_norm, dropout, rec_dropout, header, partition, ihm_pos, target_repl=False, depth=1, input_dim=76, size_coef=4, **kwargs): print("==> not used params in network class:", kwargs.keys()) self.dim = dim self.batch_norm = batch_norm self.dropout = dropout self.rec_dropout = rec_dropout self.depth = depth <|code_end|> . Use current file imports: (from keras.models import Model from keras.layers import Input, Dense, LSTM, Masking, Dropout from keras.layers.wrappers import TimeDistributed from mimic3models.keras_utils import Slice, GetTimestep, LastTimestep, ExtendMask from keras.layers.merge import Concatenate, Multiply) and context including class names, function names, or small code snippets from other files: # Path: mimic3models/keras_utils.py # class DecompensationMetrics(keras.callbacks.Callback): # class InHospitalMortalityMetrics(keras.callbacks.Callback): # class PhenotypingMetrics(keras.callbacks.Callback): # class LengthOfStayMetrics(keras.callbacks.Callback): # class MultitaskMetrics(keras.callbacks.Callback): # class CollectAttetion(Layer): # class Slice(Layer): # class GetTimestep(Layer): # class ExtendMask(Layer): # def __init__(self, train_data_gen, val_data_gen, deep_supervision, # batch_size=32, early_stopping=True, verbose=2): # def calc_metrics(self, data_gen, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def __init__(self, train_data, val_data, target_repl, batch_size=32, early_stopping=True, verbose=2): # def calc_metrics(self, data, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def __init__(self, train_data_gen, val_data_gen, batch_size=32, # early_stopping=True, verbose=2): # def calc_metrics(self, data_gen, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def __init__(self, train_data_gen, val_data_gen, partition, batch_size=32, # early_stopping=True, verbose=2): # def calc_metrics(self, data_gen, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def __init__(self, train_data_gen, val_data_gen, partition, # batch_size=32, early_stopping=True, verbose=2): # def calc_metrics(self, data_gen, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def softmax(x, axis, mask=None): # def _collect_attention(x, a, mask): # def __init__(self, **kwargs): # def call(self, inputs, mask=None): # def compute_output_shape(self, input_shape): # def compute_mask(self, input, input_mask=None): # def __init__(self, indices, **kwargs): # def call(self, x, mask=None): # def compute_output_shape(self, input_shape): # def compute_mask(self, input, input_mask=None): # def get_config(self): # def __init__(self, pos=-1, **kwargs): # def call(self, x, mask=None): # def compute_output_shape(self, input_shape): # def compute_mask(self, input, input_mask=None): # def get_config(self): # def __init__(self, add_epsilon=False, **kwargs): # def call(self, x, mask=None): # def compute_output_shape(self, input_shape): # def compute_mask(self, input, input_mask=None): # def get_config(self): # B = self.batch_size . Output only the next line.
self.size_coef = size_coef
Given snippet: <|code_start|> inputs = [X, ihm_M, decomp_M, los_M] # Preprocess each channel cX = [] for ch in channels: cX.append(Slice(ch)(mX)) pX = [] # LSTM processed version of cX for x in cX: p = x for i in range(depth): p = LSTM(units=dim, activation='tanh', return_sequences=True, dropout=dropout, recurrent_dropout=rec_dropout)(p) pX.append(p) # Concatenate processed channels Z = Concatenate(axis=2)(pX) # Main part of the network for i in range(depth): Z = LSTM(units=int(size_coef*dim), activation='tanh', return_sequences=True, dropout=dropout, recurrent_dropout=rec_dropout)(Z) L = Z <|code_end|> , continue by predicting the next line. Consider current file imports: from keras.models import Model from keras.layers import Input, Dense, LSTM, Masking, Dropout from keras.layers.wrappers import TimeDistributed from mimic3models.keras_utils import Slice, GetTimestep, LastTimestep, ExtendMask from keras.layers.merge import Concatenate, Multiply and context: # Path: mimic3models/keras_utils.py # class DecompensationMetrics(keras.callbacks.Callback): # class InHospitalMortalityMetrics(keras.callbacks.Callback): # class PhenotypingMetrics(keras.callbacks.Callback): # class LengthOfStayMetrics(keras.callbacks.Callback): # class MultitaskMetrics(keras.callbacks.Callback): # class CollectAttetion(Layer): # class Slice(Layer): # class GetTimestep(Layer): # class ExtendMask(Layer): # def __init__(self, train_data_gen, val_data_gen, deep_supervision, # batch_size=32, early_stopping=True, verbose=2): # def calc_metrics(self, data_gen, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def __init__(self, train_data, val_data, target_repl, batch_size=32, early_stopping=True, verbose=2): # def calc_metrics(self, data, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def __init__(self, train_data_gen, val_data_gen, batch_size=32, # early_stopping=True, verbose=2): # def calc_metrics(self, data_gen, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def __init__(self, train_data_gen, val_data_gen, partition, batch_size=32, # early_stopping=True, verbose=2): # def calc_metrics(self, data_gen, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def __init__(self, train_data_gen, val_data_gen, partition, # batch_size=32, early_stopping=True, verbose=2): # def calc_metrics(self, data_gen, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def softmax(x, axis, mask=None): # def _collect_attention(x, a, mask): # def __init__(self, **kwargs): # def call(self, inputs, mask=None): # def compute_output_shape(self, input_shape): # def compute_mask(self, input, input_mask=None): # def __init__(self, indices, **kwargs): # def call(self, x, mask=None): # def compute_output_shape(self, input_shape): # def compute_mask(self, input, input_mask=None): # def get_config(self): # def __init__(self, pos=-1, **kwargs): # def call(self, x, mask=None): # def compute_output_shape(self, input_shape): # def compute_mask(self, input, input_mask=None): # def get_config(self): # def __init__(self, add_epsilon=False, **kwargs): # def call(self, x, mask=None): # def compute_output_shape(self, input_shape): # def compute_mask(self, input, input_mask=None): # def get_config(self): # B = self.batch_size which might include code, classes, or functions. Output only the next line.
if dropout > 0:
Based on the snippet: <|code_start|> if pos != -1: channel_names.add(ch[:pos]) else: channel_names.add(ch) channel_names = sorted(list(channel_names)) print("==> found {} channels: {}".format(len(channel_names), channel_names)) channels = [] # each channel is a list of columns for ch in channel_names: indices = range(len(header)) indices = list(filter(lambda i: header[i].find(ch) != -1, indices)) channels.append(indices) # Input layers and masking X = Input(shape=(None, input_dim), name='X') mX = Masking()(X) # Masks ihm_M = Input(shape=(1,), name='ihm_M') decomp_M = Input(shape=(None,), name='decomp_M') los_M = Input(shape=(None,), name='los_M') inputs = [X, ihm_M, decomp_M, los_M] # Preprocess each channel cX = [] for ch in channels: cX.append(Slice(ch)(mX)) pX = [] # LSTM processed version of cX for x in cX: <|code_end|> , predict the immediate next line with the help of imports: from keras.models import Model from keras.layers import Input, Dense, LSTM, Masking, Dropout from keras.layers.wrappers import TimeDistributed from mimic3models.keras_utils import Slice, GetTimestep, LastTimestep, ExtendMask from keras.layers.merge import Concatenate, Multiply and context (classes, functions, sometimes code) from other files: # Path: mimic3models/keras_utils.py # class DecompensationMetrics(keras.callbacks.Callback): # class InHospitalMortalityMetrics(keras.callbacks.Callback): # class PhenotypingMetrics(keras.callbacks.Callback): # class LengthOfStayMetrics(keras.callbacks.Callback): # class MultitaskMetrics(keras.callbacks.Callback): # class CollectAttetion(Layer): # class Slice(Layer): # class GetTimestep(Layer): # class ExtendMask(Layer): # def __init__(self, train_data_gen, val_data_gen, deep_supervision, # batch_size=32, early_stopping=True, verbose=2): # def calc_metrics(self, data_gen, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def __init__(self, train_data, val_data, target_repl, batch_size=32, early_stopping=True, verbose=2): # def calc_metrics(self, data, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def __init__(self, train_data_gen, val_data_gen, batch_size=32, # early_stopping=True, verbose=2): # def calc_metrics(self, data_gen, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def __init__(self, train_data_gen, val_data_gen, partition, batch_size=32, # early_stopping=True, verbose=2): # def calc_metrics(self, data_gen, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def __init__(self, train_data_gen, val_data_gen, partition, # batch_size=32, early_stopping=True, verbose=2): # def calc_metrics(self, data_gen, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def softmax(x, axis, mask=None): # def _collect_attention(x, a, mask): # def __init__(self, **kwargs): # def call(self, inputs, mask=None): # def compute_output_shape(self, input_shape): # def compute_mask(self, input, input_mask=None): # def __init__(self, indices, **kwargs): # def call(self, x, mask=None): # def compute_output_shape(self, input_shape): # def compute_mask(self, input, input_mask=None): # def get_config(self): # def __init__(self, pos=-1, **kwargs): # def call(self, x, mask=None): # def compute_output_shape(self, input_shape): # def compute_mask(self, input, input_mask=None): # def get_config(self): # def __init__(self, add_epsilon=False, **kwargs): # def call(self, x, mask=None): # def compute_output_shape(self, input_shape): # def compute_mask(self, input, input_mask=None): # def get_config(self): # B = self.batch_size . Output only the next line.
p = x
Given the code snippet: <|code_start|> ihm_M = Input(shape=(1,), name='ihm_M') decomp_M = Input(shape=(None,), name='decomp_M') los_M = Input(shape=(None,), name='los_M') inputs = [X, ihm_M, decomp_M, los_M] # Preprocess each channel cX = [] for ch in channels: cX.append(Slice(ch)(mX)) pX = [] # LSTM processed version of cX for x in cX: p = x for i in range(depth): p = LSTM(units=dim, activation='tanh', return_sequences=True, dropout=dropout, recurrent_dropout=rec_dropout)(p) pX.append(p) # Concatenate processed channels Z = Concatenate(axis=2)(pX) # Main part of the network for i in range(depth): Z = LSTM(units=int(size_coef*dim), activation='tanh', return_sequences=True, dropout=dropout, <|code_end|> , generate the next line using the imports in this file: from keras.models import Model from keras.layers import Input, Dense, LSTM, Masking, Dropout from keras.layers.wrappers import TimeDistributed from mimic3models.keras_utils import Slice, GetTimestep, LastTimestep, ExtendMask from keras.layers.merge import Concatenate, Multiply and context (functions, classes, or occasionally code) from other files: # Path: mimic3models/keras_utils.py # class DecompensationMetrics(keras.callbacks.Callback): # class InHospitalMortalityMetrics(keras.callbacks.Callback): # class PhenotypingMetrics(keras.callbacks.Callback): # class LengthOfStayMetrics(keras.callbacks.Callback): # class MultitaskMetrics(keras.callbacks.Callback): # class CollectAttetion(Layer): # class Slice(Layer): # class GetTimestep(Layer): # class ExtendMask(Layer): # def __init__(self, train_data_gen, val_data_gen, deep_supervision, # batch_size=32, early_stopping=True, verbose=2): # def calc_metrics(self, data_gen, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def __init__(self, train_data, val_data, target_repl, batch_size=32, early_stopping=True, verbose=2): # def calc_metrics(self, data, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def __init__(self, train_data_gen, val_data_gen, batch_size=32, # early_stopping=True, verbose=2): # def calc_metrics(self, data_gen, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def __init__(self, train_data_gen, val_data_gen, partition, batch_size=32, # early_stopping=True, verbose=2): # def calc_metrics(self, data_gen, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def __init__(self, train_data_gen, val_data_gen, partition, # batch_size=32, early_stopping=True, verbose=2): # def calc_metrics(self, data_gen, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def softmax(x, axis, mask=None): # def _collect_attention(x, a, mask): # def __init__(self, **kwargs): # def call(self, inputs, mask=None): # def compute_output_shape(self, input_shape): # def compute_mask(self, input, input_mask=None): # def __init__(self, indices, **kwargs): # def call(self, x, mask=None): # def compute_output_shape(self, input_shape): # def compute_mask(self, input, input_mask=None): # def get_config(self): # def __init__(self, pos=-1, **kwargs): # def call(self, x, mask=None): # def compute_output_shape(self, input_shape): # def compute_mask(self, input, input_mask=None): # def get_config(self): # def __init__(self, add_epsilon=False, **kwargs): # def call(self, x, mask=None): # def compute_output_shape(self, input_shape): # def compute_mask(self, input, input_mask=None): # def get_config(self): # B = self.batch_size . Output only the next line.
recurrent_dropout=rec_dropout)(Z)
Predict the next line for this snippet: <|code_start|>def read_and_extract_features(reader, count, period, features): read_chunk_size = 1000 Xs = [] ys = [] names = [] ts = [] for i in range(0, count, read_chunk_size): j = min(count, i + read_chunk_size) ret = common_utils.read_chunk(reader, j - i) X = common_utils.extract_features_from_rawdata(ret['X'], ret['header'], period, features) Xs.append(X) ys += ret['y'] names += ret['name'] ts += ret['t'] Xs = np.concatenate(Xs, axis=0) bins = np.array([one_hot(metrics.get_bin_custom(x, n_bins)) for x in ys]) return (Xs, bins, ys, names, ts) def main(): parser = argparse.ArgumentParser() parser.add_argument('--period', type=str, default='all', help='specifies which period extract features from', choices=['first4days', 'first8days', 'last12hours', 'first25percent', 'first50percent', 'all']) parser.add_argument('--features', type=str, default='all', help='specifies what features to extract', choices=['all', 'len', 'all_but_len']) parser.add_argument('--grid-search', dest='grid_search', action='store_true') parser.add_argument('--no-grid-search', dest='grid_search', action='store_false') parser.set_defaults(grid_search=False) parser.add_argument('--data', type=str, help='Path to the data of length-of-stay task', default=os.path.join(os.path.dirname(__file__), '../../../data/length-of-stay/')) <|code_end|> with the help of current file imports: from sklearn.preprocessing import Imputer, StandardScaler from sklearn.linear_model import LogisticRegression from mimic3benchmark.readers import LengthOfStayReader from mimic3models import common_utils from mimic3models import metrics from mimic3models.length_of_stay.utils import save_results import numpy as np import argparse import os import json and context from other files: # Path: mimic3benchmark/readers.py # class LengthOfStayReader(Reader): # def __init__(self, dataset_dir, listfile=None): # """ Reader for length of stay prediction task. # # :param dataset_dir: Directory where timeseries files are stored. # :param listfile: Path to a listfile. If this parameter is left `None` then # `dataset_dir/listfile.csv` will be used. # """ # Reader.__init__(self, dataset_dir, listfile) # self._data = [line.split(',') for line in self._data] # self._data = [(x, float(t), float(y)) for (x, t, y) in self._data] # # def _read_timeseries(self, ts_filename, time_bound): # ret = [] # with open(os.path.join(self._dataset_dir, ts_filename), "r") as tsfile: # header = tsfile.readline().strip().split(',') # assert header[0] == "Hours" # for line in tsfile: # mas = line.strip().split(',') # t = float(mas[0]) # if t > time_bound + 1e-6: # break # ret.append(np.array(mas)) # return (np.stack(ret), header) # # def read_example(self, index): # """ Reads the example with given index. # # :param index: Index of the line of the listfile to read (counting starts from 0). # :return: Dictionary with the following keys: # X : np.array # 2D array containing all events. Each row corresponds to a moment. # First column is the time and other columns correspond to different # variables. # t : float # Length of the data in hours. Note, in general, it is not equal to the # timestamp of last event. # y : float # Remaining time in ICU. # header : array of strings # Names of the columns. The ordering of the columns is always the same. # name: Name of the sample. # """ # if index < 0 or index >= len(self._data): # raise ValueError("Index must be from 0 (inclusive) to number of lines (exclusive).") # # name = self._data[index][0] # t = self._data[index][1] # y = self._data[index][2] # (X, header) = self._read_timeseries(name, t) # # return {"X": X, # "t": t, # "y": y, # "header": header, # "name": name} # # Path: mimic3models/common_utils.py # def convert_to_dict(data, header, channel_info): # def extract_features_from_rawdata(chunk, header, period, features): # def read_chunk(reader, chunk_size): # def sort_and_shuffle(data, batch_size): # def add_common_arguments(parser): # def __init__(self, dataset_dir, listfile=None, small_part=False): # def _read_timeseries(self, ts_filename): # def create_directory(directory): # def pad_zeros(arr, min_length=None): # class DeepSupervisionDataLoader: # # Path: mimic3models/metrics.py # def print_metrics_binary(y_true, predictions, verbose=1): # def print_metrics_multilabel(y_true, predictions, verbose=1): # def mean_absolute_percentage_error(y_true, y_pred): # def print_metrics_regression(y_true, predictions, verbose=1): # def get_bin_log(x, nbins, one_hot=False): # def get_estimate_log(prediction, nbins): # def print_metrics_log_bins(y_true, predictions, verbose=1): # def get_bin_custom(x, nbins, one_hot=False): # def get_estimate_custom(prediction, nbins): # def print_metrics_custom_bins(y_true, predictions, verbose=1): # class LogBins: # class CustomBins: # # Path: mimic3models/length_of_stay/utils.py # def save_results(names, ts, pred, y_true, path): # common_utils.create_directory(os.path.dirname(path)) # with open(path, 'w') as f: # f.write("stay,period_length,prediction,y_true\n") # for (name, t, x, y) in zip(names, ts, pred, y_true): # f.write("{},{:.6f},{:.6f},{:.6f}\n".format(name, t, x, y)) , which may contain function names, class names, or code. Output only the next line.
parser.add_argument('--output_dir', type=str, help='Directory relative which all output files are stored',
Given the following code snippet before the placeholder: <|code_start|> result_dir = os.path.join(args.output_dir, 'cf_results') common_utils.create_directory(result_dir) for (penalty, C) in zip(penalties, coefs): model_name = '{}.{}.{}.C{}'.format(args.period, args.features, penalty, C) train_activations = np.zeros(shape=train_y.shape, dtype=float) val_activations = np.zeros(shape=val_y.shape, dtype=float) test_activations = np.zeros(shape=test_y.shape, dtype=float) for task_id in range(n_bins): logreg = LogisticRegression(penalty=penalty, C=C, random_state=42) logreg.fit(train_X, train_y[:, task_id]) train_preds = logreg.predict_proba(train_X) train_activations[:, task_id] = train_preds[:, 1] val_preds = logreg.predict_proba(val_X) val_activations[:, task_id] = val_preds[:, 1] test_preds = logreg.predict_proba(test_X) test_activations[:, task_id] = test_preds[:, 1] train_predictions = np.array([metrics.get_estimate_custom(x, n_bins) for x in train_activations]) val_predictions = np.array([metrics.get_estimate_custom(x, n_bins) for x in val_activations]) test_predictions = np.array([metrics.get_estimate_custom(x, n_bins) for x in test_activations]) with open(os.path.join(result_dir, 'train_{}.json'.format(model_name)), 'w') as f: ret = metrics.print_metrics_custom_bins(train_actual, train_predictions) ret = {k: float(v) for k, v in ret.items()} <|code_end|> , predict the next line using imports from the current file: from sklearn.preprocessing import Imputer, StandardScaler from sklearn.linear_model import LogisticRegression from mimic3benchmark.readers import LengthOfStayReader from mimic3models import common_utils from mimic3models import metrics from mimic3models.length_of_stay.utils import save_results import numpy as np import argparse import os import json and context including class names, function names, and sometimes code from other files: # Path: mimic3benchmark/readers.py # class LengthOfStayReader(Reader): # def __init__(self, dataset_dir, listfile=None): # """ Reader for length of stay prediction task. # # :param dataset_dir: Directory where timeseries files are stored. # :param listfile: Path to a listfile. If this parameter is left `None` then # `dataset_dir/listfile.csv` will be used. # """ # Reader.__init__(self, dataset_dir, listfile) # self._data = [line.split(',') for line in self._data] # self._data = [(x, float(t), float(y)) for (x, t, y) in self._data] # # def _read_timeseries(self, ts_filename, time_bound): # ret = [] # with open(os.path.join(self._dataset_dir, ts_filename), "r") as tsfile: # header = tsfile.readline().strip().split(',') # assert header[0] == "Hours" # for line in tsfile: # mas = line.strip().split(',') # t = float(mas[0]) # if t > time_bound + 1e-6: # break # ret.append(np.array(mas)) # return (np.stack(ret), header) # # def read_example(self, index): # """ Reads the example with given index. # # :param index: Index of the line of the listfile to read (counting starts from 0). # :return: Dictionary with the following keys: # X : np.array # 2D array containing all events. Each row corresponds to a moment. # First column is the time and other columns correspond to different # variables. # t : float # Length of the data in hours. Note, in general, it is not equal to the # timestamp of last event. # y : float # Remaining time in ICU. # header : array of strings # Names of the columns. The ordering of the columns is always the same. # name: Name of the sample. # """ # if index < 0 or index >= len(self._data): # raise ValueError("Index must be from 0 (inclusive) to number of lines (exclusive).") # # name = self._data[index][0] # t = self._data[index][1] # y = self._data[index][2] # (X, header) = self._read_timeseries(name, t) # # return {"X": X, # "t": t, # "y": y, # "header": header, # "name": name} # # Path: mimic3models/common_utils.py # def convert_to_dict(data, header, channel_info): # def extract_features_from_rawdata(chunk, header, period, features): # def read_chunk(reader, chunk_size): # def sort_and_shuffle(data, batch_size): # def add_common_arguments(parser): # def __init__(self, dataset_dir, listfile=None, small_part=False): # def _read_timeseries(self, ts_filename): # def create_directory(directory): # def pad_zeros(arr, min_length=None): # class DeepSupervisionDataLoader: # # Path: mimic3models/metrics.py # def print_metrics_binary(y_true, predictions, verbose=1): # def print_metrics_multilabel(y_true, predictions, verbose=1): # def mean_absolute_percentage_error(y_true, y_pred): # def print_metrics_regression(y_true, predictions, verbose=1): # def get_bin_log(x, nbins, one_hot=False): # def get_estimate_log(prediction, nbins): # def print_metrics_log_bins(y_true, predictions, verbose=1): # def get_bin_custom(x, nbins, one_hot=False): # def get_estimate_custom(prediction, nbins): # def print_metrics_custom_bins(y_true, predictions, verbose=1): # class LogBins: # class CustomBins: # # Path: mimic3models/length_of_stay/utils.py # def save_results(names, ts, pred, y_true, path): # common_utils.create_directory(os.path.dirname(path)) # with open(path, 'w') as f: # f.write("stay,period_length,prediction,y_true\n") # for (name, t, x, y) in zip(names, ts, pred, y_true): # f.write("{},{:.6f},{:.6f},{:.6f}\n".format(name, t, x, y)) . Output only the next line.
json.dump(ret, f)
Given the code snippet: <|code_start|> val_reader = LengthOfStayReader(dataset_dir=os.path.join(args.data, 'train'), listfile=os.path.join(args.data, 'val_listfile.csv')) test_reader = LengthOfStayReader(dataset_dir=os.path.join(args.data, 'test'), listfile=os.path.join(args.data, 'test_listfile.csv')) print('Reading data and extracting features ...') n_train = min(100000, train_reader.get_number_of_examples()) n_val = min(100000, val_reader.get_number_of_examples()) (train_X, train_y, train_actual, train_names, train_ts) = read_and_extract_features( train_reader, n_train, args.period, args.features) (val_X, val_y, val_actual, val_names, val_ts) = read_and_extract_features( val_reader, n_val, args.period, args.features) (test_X, test_y, test_actual, test_names, test_ts) = read_and_extract_features( test_reader, test_reader.get_number_of_examples(), args.period, args.features) print("train set shape: {}".format(train_X.shape)) print("validation set shape: {}".format(val_X.shape)) print("test set shape: {}".format(test_X.shape)) print('Imputing missing values ...') imputer = Imputer(missing_values=np.nan, strategy='mean', axis=0, verbose=0, copy=True) imputer.fit(train_X) train_X = np.array(imputer.transform(train_X), dtype=np.float32) val_X = np.array(imputer.transform(val_X), dtype=np.float32) test_X = np.array(imputer.transform(test_X), dtype=np.float32) <|code_end|> , generate the next line using the imports in this file: from sklearn.preprocessing import Imputer, StandardScaler from sklearn.linear_model import LogisticRegression from mimic3benchmark.readers import LengthOfStayReader from mimic3models import common_utils from mimic3models import metrics from mimic3models.length_of_stay.utils import save_results import numpy as np import argparse import os import json and context (functions, classes, or occasionally code) from other files: # Path: mimic3benchmark/readers.py # class LengthOfStayReader(Reader): # def __init__(self, dataset_dir, listfile=None): # """ Reader for length of stay prediction task. # # :param dataset_dir: Directory where timeseries files are stored. # :param listfile: Path to a listfile. If this parameter is left `None` then # `dataset_dir/listfile.csv` will be used. # """ # Reader.__init__(self, dataset_dir, listfile) # self._data = [line.split(',') for line in self._data] # self._data = [(x, float(t), float(y)) for (x, t, y) in self._data] # # def _read_timeseries(self, ts_filename, time_bound): # ret = [] # with open(os.path.join(self._dataset_dir, ts_filename), "r") as tsfile: # header = tsfile.readline().strip().split(',') # assert header[0] == "Hours" # for line in tsfile: # mas = line.strip().split(',') # t = float(mas[0]) # if t > time_bound + 1e-6: # break # ret.append(np.array(mas)) # return (np.stack(ret), header) # # def read_example(self, index): # """ Reads the example with given index. # # :param index: Index of the line of the listfile to read (counting starts from 0). # :return: Dictionary with the following keys: # X : np.array # 2D array containing all events. Each row corresponds to a moment. # First column is the time and other columns correspond to different # variables. # t : float # Length of the data in hours. Note, in general, it is not equal to the # timestamp of last event. # y : float # Remaining time in ICU. # header : array of strings # Names of the columns. The ordering of the columns is always the same. # name: Name of the sample. # """ # if index < 0 or index >= len(self._data): # raise ValueError("Index must be from 0 (inclusive) to number of lines (exclusive).") # # name = self._data[index][0] # t = self._data[index][1] # y = self._data[index][2] # (X, header) = self._read_timeseries(name, t) # # return {"X": X, # "t": t, # "y": y, # "header": header, # "name": name} # # Path: mimic3models/common_utils.py # def convert_to_dict(data, header, channel_info): # def extract_features_from_rawdata(chunk, header, period, features): # def read_chunk(reader, chunk_size): # def sort_and_shuffle(data, batch_size): # def add_common_arguments(parser): # def __init__(self, dataset_dir, listfile=None, small_part=False): # def _read_timeseries(self, ts_filename): # def create_directory(directory): # def pad_zeros(arr, min_length=None): # class DeepSupervisionDataLoader: # # Path: mimic3models/metrics.py # def print_metrics_binary(y_true, predictions, verbose=1): # def print_metrics_multilabel(y_true, predictions, verbose=1): # def mean_absolute_percentage_error(y_true, y_pred): # def print_metrics_regression(y_true, predictions, verbose=1): # def get_bin_log(x, nbins, one_hot=False): # def get_estimate_log(prediction, nbins): # def print_metrics_log_bins(y_true, predictions, verbose=1): # def get_bin_custom(x, nbins, one_hot=False): # def get_estimate_custom(prediction, nbins): # def print_metrics_custom_bins(y_true, predictions, verbose=1): # class LogBins: # class CustomBins: # # Path: mimic3models/length_of_stay/utils.py # def save_results(names, ts, pred, y_true, path): # common_utils.create_directory(os.path.dirname(path)) # with open(path, 'w') as f: # f.write("stay,period_length,prediction,y_true\n") # for (name, t, x, y) in zip(names, ts, pred, y_true): # f.write("{},{:.6f},{:.6f},{:.6f}\n".format(name, t, x, y)) . Output only the next line.
print('Normalizing the data to have zero mean and unit variance ...')
Given the following code snippet before the placeholder: <|code_start|>from __future__ import absolute_import from __future__ import print_function def read_and_extract_features(reader, count, period, features): read_chunk_size = 1000 <|code_end|> , predict the next line using imports from the current file: from sklearn.preprocessing import Imputer, StandardScaler from sklearn.linear_model import LinearRegression from mimic3benchmark.readers import LengthOfStayReader from mimic3models import common_utils from mimic3models.metrics import print_metrics_regression from mimic3models.length_of_stay.utils import save_results import os import numpy as np import argparse import json and context including class names, function names, and sometimes code from other files: # Path: mimic3benchmark/readers.py # class LengthOfStayReader(Reader): # def __init__(self, dataset_dir, listfile=None): # """ Reader for length of stay prediction task. # # :param dataset_dir: Directory where timeseries files are stored. # :param listfile: Path to a listfile. If this parameter is left `None` then # `dataset_dir/listfile.csv` will be used. # """ # Reader.__init__(self, dataset_dir, listfile) # self._data = [line.split(',') for line in self._data] # self._data = [(x, float(t), float(y)) for (x, t, y) in self._data] # # def _read_timeseries(self, ts_filename, time_bound): # ret = [] # with open(os.path.join(self._dataset_dir, ts_filename), "r") as tsfile: # header = tsfile.readline().strip().split(',') # assert header[0] == "Hours" # for line in tsfile: # mas = line.strip().split(',') # t = float(mas[0]) # if t > time_bound + 1e-6: # break # ret.append(np.array(mas)) # return (np.stack(ret), header) # # def read_example(self, index): # """ Reads the example with given index. # # :param index: Index of the line of the listfile to read (counting starts from 0). # :return: Dictionary with the following keys: # X : np.array # 2D array containing all events. Each row corresponds to a moment. # First column is the time and other columns correspond to different # variables. # t : float # Length of the data in hours. Note, in general, it is not equal to the # timestamp of last event. # y : float # Remaining time in ICU. # header : array of strings # Names of the columns. The ordering of the columns is always the same. # name: Name of the sample. # """ # if index < 0 or index >= len(self._data): # raise ValueError("Index must be from 0 (inclusive) to number of lines (exclusive).") # # name = self._data[index][0] # t = self._data[index][1] # y = self._data[index][2] # (X, header) = self._read_timeseries(name, t) # # return {"X": X, # "t": t, # "y": y, # "header": header, # "name": name} # # Path: mimic3models/common_utils.py # def convert_to_dict(data, header, channel_info): # def extract_features_from_rawdata(chunk, header, period, features): # def read_chunk(reader, chunk_size): # def sort_and_shuffle(data, batch_size): # def add_common_arguments(parser): # def __init__(self, dataset_dir, listfile=None, small_part=False): # def _read_timeseries(self, ts_filename): # def create_directory(directory): # def pad_zeros(arr, min_length=None): # class DeepSupervisionDataLoader: # # Path: mimic3models/metrics.py # def print_metrics_regression(y_true, predictions, verbose=1): # predictions = np.array(predictions) # predictions = np.maximum(predictions, 0).flatten() # y_true = np.array(y_true) # # y_true_bins = [get_bin_custom(x, CustomBins.nbins) for x in y_true] # prediction_bins = [get_bin_custom(x, CustomBins.nbins) for x in predictions] # cf = metrics.confusion_matrix(y_true_bins, prediction_bins) # if verbose: # print("Custom bins confusion matrix:") # print(cf) # # kappa = metrics.cohen_kappa_score(y_true_bins, prediction_bins, # weights='linear') # mad = metrics.mean_absolute_error(y_true, predictions) # mse = metrics.mean_squared_error(y_true, predictions) # mape = mean_absolute_percentage_error(y_true, predictions) # # if verbose: # print("Mean absolute deviation (MAD) = {}".format(mad)) # print("Mean squared error (MSE) = {}".format(mse)) # print("Mean absolute percentage error (MAPE) = {}".format(mape)) # print("Cohen kappa score = {}".format(kappa)) # # return {"mad": mad, # "mse": mse, # "mape": mape, # "kappa": kappa} # # Path: mimic3models/length_of_stay/utils.py # def save_results(names, ts, pred, y_true, path): # common_utils.create_directory(os.path.dirname(path)) # with open(path, 'w') as f: # f.write("stay,period_length,prediction,y_true\n") # for (name, t, x, y) in zip(names, ts, pred, y_true): # f.write("{},{:.6f},{:.6f},{:.6f}\n".format(name, t, x, y)) . Output only the next line.
Xs = []
Based on the snippet: <|code_start|> parser.add_argument('--prefix', type=str, default="", help='optional prefix of network name') parser.add_argument('--dropout', type=float, default=0.0) parser.add_argument('--rec_dropout', type=float, default=0.0, help="dropout rate for recurrent connections") parser.add_argument('--batch_norm', type=bool, default=False, help='batch normalization') parser.add_argument('--timestep', type=float, default=1.0, help="fixed timestep used in the dataset") parser.add_argument('--imputation', type=str, default='previous') parser.add_argument('--small_part', dest='small_part', action='store_true') parser.add_argument('--whole_data', dest='small_part', action='store_false') parser.add_argument('--optimizer', type=str, default='adam') parser.add_argument('--lr', type=float, default=0.001, help='learning rate') parser.add_argument('--beta_1', type=float, default=0.9, help='beta_1 param for Adam optimizer') parser.add_argument('--verbose', type=int, default=2) parser.add_argument('--size_coef', type=float, default=4.0) parser.add_argument('--normalizer_state', type=str, default=None, help='Path to a state file of a normalizer. Leave none if you want to ' 'use one of the provided ones.') parser.set_defaults(small_part=False) class DeepSupervisionDataLoader: r""" Data loader for decompensation and length of stay task. Reads all the data for one patient at once. Parameters <|code_end|> , predict the immediate next line with the help of imports: import numpy as np import os import json import random from mimic3models.feature_extractor import extract_features and context (classes, functions, sometimes code) from other files: # Path: mimic3models/feature_extractor.py # def extract_features(data_raw, period, features): # period = periods_map[period] # functions = functions_map[features] # return np.array([extract_features_single_episode(x, period, functions) # for x in data_raw]) . Output only the next line.
----------
Predict the next line for this snippet: <|code_start|> print('Normalizing the data to have zero mean and unit variance ...') scaler = StandardScaler() scaler.fit(train_X) train_X = scaler.transform(train_X) val_X = scaler.transform(val_X) test_X = scaler.transform(test_X) n_tasks = 25 result_dir = os.path.join(args.output_dir, 'results') common_utils.create_directory(result_dir) for (penalty, C) in zip(penalties, coefs): model_name = '{}.{}.{}.C{}'.format(args.period, args.features, penalty, C) train_activations = np.zeros(shape=train_y.shape, dtype=float) val_activations = np.zeros(shape=val_y.shape, dtype=float) test_activations = np.zeros(shape=test_y.shape, dtype=float) for task_id in range(n_tasks): print('Starting task {}'.format(task_id)) logreg = LogisticRegression(penalty=penalty, C=C, random_state=42) logreg.fit(train_X, train_y[:, task_id]) train_preds = logreg.predict_proba(train_X) train_activations[:, task_id] = train_preds[:, 1] val_preds = logreg.predict_proba(val_X) val_activations[:, task_id] = val_preds[:, 1] <|code_end|> with the help of current file imports: from sklearn.preprocessing import Imputer, StandardScaler from sklearn.linear_model import LogisticRegression from mimic3benchmark.readers import PhenotypingReader from mimic3models import common_utils from mimic3models import metrics from mimic3models.phenotyping.utils import save_results import numpy as np import argparse import os import json and context from other files: # Path: mimic3benchmark/readers.py # class PhenotypingReader(Reader): # def __init__(self, dataset_dir, listfile=None): # """ Reader for phenotype classification task. # # :param dataset_dir: Directory where timeseries files are stored. # :param listfile: Path to a listfile. If this parameter is left `None` then # `dataset_dir/listfile.csv` will be used. # """ # Reader.__init__(self, dataset_dir, listfile) # self._data = [line.split(',') for line in self._data] # self._data = [(mas[0], float(mas[1]), list(map(int, mas[2:]))) for mas in self._data] # # def _read_timeseries(self, ts_filename): # ret = [] # with open(os.path.join(self._dataset_dir, ts_filename), "r") as tsfile: # header = tsfile.readline().strip().split(',') # assert header[0] == "Hours" # for line in tsfile: # mas = line.strip().split(',') # ret.append(np.array(mas)) # return (np.stack(ret), header) # # def read_example(self, index): # """ Reads the example with given index. # # :param index: Index of the line of the listfile to read (counting starts from 0). # :return: Dictionary with the following keys: # X : np.array # 2D array containing all events. Each row corresponds to a moment. # First column is the time and other columns correspond to different # variables. # t : float # Length of the data in hours. Note, in general, it is not equal to the # timestamp of last event. # y : array of ints # Phenotype labels. # header : array of strings # Names of the columns. The ordering of the columns is always the same. # name: Name of the sample. # """ # if index < 0 or index >= len(self._data): # raise ValueError("Index must be from 0 (inclusive) to number of lines (exclusive).") # # name = self._data[index][0] # t = self._data[index][1] # y = self._data[index][2] # (X, header) = self._read_timeseries(name) # # return {"X": X, # "t": t, # "y": y, # "header": header, # "name": name} # # Path: mimic3models/common_utils.py # def convert_to_dict(data, header, channel_info): # def extract_features_from_rawdata(chunk, header, period, features): # def read_chunk(reader, chunk_size): # def sort_and_shuffle(data, batch_size): # def add_common_arguments(parser): # def __init__(self, dataset_dir, listfile=None, small_part=False): # def _read_timeseries(self, ts_filename): # def create_directory(directory): # def pad_zeros(arr, min_length=None): # class DeepSupervisionDataLoader: # # Path: mimic3models/metrics.py # def print_metrics_binary(y_true, predictions, verbose=1): # def print_metrics_multilabel(y_true, predictions, verbose=1): # def mean_absolute_percentage_error(y_true, y_pred): # def print_metrics_regression(y_true, predictions, verbose=1): # def get_bin_log(x, nbins, one_hot=False): # def get_estimate_log(prediction, nbins): # def print_metrics_log_bins(y_true, predictions, verbose=1): # def get_bin_custom(x, nbins, one_hot=False): # def get_estimate_custom(prediction, nbins): # def print_metrics_custom_bins(y_true, predictions, verbose=1): # class LogBins: # class CustomBins: # # Path: mimic3models/phenotyping/utils.py # def save_results(names, ts, predictions, labels, path): # n_tasks = 25 # common_utils.create_directory(os.path.dirname(path)) # with open(path, 'w') as f: # header = ["stay", "period_length"] # header += ["pred_{}".format(x) for x in range(1, n_tasks + 1)] # header += ["label_{}".format(x) for x in range(1, n_tasks + 1)] # header = ",".join(header) # f.write(header + '\n') # for name, t, pred, y in zip(names, ts, predictions, labels): # line = [name] # line += ["{:.6f}".format(t)] # line += ["{:.6f}".format(a) for a in pred] # line += [str(a) for a in y] # line = ",".join(line) # f.write(line + '\n') , which may contain function names, class names, or code. Output only the next line.
test_preds = logreg.predict_proba(test_X)
Next line prediction: <|code_start|> data[:, 0] = np.array(df['prediction']) data[:, 1] = np.array(df['y_true_l']) results = dict() results['n_iters'] = args.n_iters ret = print_metrics_binary(data[:, 1], data[:, 0], verbose=0) for (m, k) in metrics: results[m] = dict() results[m]['value'] = ret[k] results[m]['runs'] = [] for i in range(args.n_iters): cur_data = sk_utils.resample(data, n_samples=len(data)) ret = print_metrics_binary(cur_data[:, 1], cur_data[:, 0], verbose=0) for (m, k) in metrics: results[m]['runs'].append(ret[k]) for (m, k) in metrics: runs = results[m]['runs'] results[m]['mean'] = np.mean(runs) results[m]['median'] = np.median(runs) results[m]['std'] = np.std(runs) results[m]['2.5% percentile'] = np.percentile(runs, 2.5) results[m]['97.5% percentile'] = np.percentile(runs, 97.5) del results[m]['runs'] print("Saving the results in {} ...".format(args.save_file)) with open(args.save_file, 'w') as f: json.dump(results, f) <|code_end|> . Use current file imports: (from mimic3models.metrics import print_metrics_binary import sklearn.utils as sk_utils import numpy as np import pandas as pd import argparse import json import os) and context including class names, function names, or small code snippets from other files: # Path: mimic3models/metrics.py # def print_metrics_binary(y_true, predictions, verbose=1): # predictions = np.array(predictions) # if len(predictions.shape) == 1: # predictions = np.stack([1 - predictions, predictions]).transpose((1, 0)) # # cf = metrics.confusion_matrix(y_true, predictions.argmax(axis=1)) # if verbose: # print("confusion matrix:") # print(cf) # cf = cf.astype(np.float32) # # acc = (cf[0][0] + cf[1][1]) / np.sum(cf) # prec0 = cf[0][0] / (cf[0][0] + cf[1][0]) # prec1 = cf[1][1] / (cf[1][1] + cf[0][1]) # rec0 = cf[0][0] / (cf[0][0] + cf[0][1]) # rec1 = cf[1][1] / (cf[1][1] + cf[1][0]) # auroc = metrics.roc_auc_score(y_true, predictions[:, 1]) # # (precisions, recalls, thresholds) = metrics.precision_recall_curve(y_true, predictions[:, 1]) # auprc = metrics.auc(recalls, precisions) # minpse = np.max([min(x, y) for (x, y) in zip(precisions, recalls)]) # # if verbose: # print("accuracy = {}".format(acc)) # print("precision class 0 = {}".format(prec0)) # print("precision class 1 = {}".format(prec1)) # print("recall class 0 = {}".format(rec0)) # print("recall class 1 = {}".format(rec1)) # print("AUC of ROC = {}".format(auroc)) # print("AUC of PRC = {}".format(auprc)) # print("min(+P, Se) = {}".format(minpse)) # # return {"acc": acc, # "prec0": prec0, # "prec1": prec1, # "rec0": rec0, # "rec1": rec1, # "auroc": auroc, # "auprc": auprc, # "minpse": minpse} . Output only the next line.
print(results)
Given the code snippet: <|code_start|> parser = argparse.ArgumentParser(description='Extract per-subject data from MIMIC-III CSV files.') parser.add_argument('mimic3_path', type=str, help='Directory containing MIMIC-III CSV files.') parser.add_argument('output_path', type=str, help='Directory where per-subject data should be written.') parser.add_argument('--event_tables', '-e', type=str, nargs='+', help='Tables from which to read events.', default=['CHARTEVENTS', 'LABEVENTS', 'OUTPUTEVENTS']) parser.add_argument('--phenotype_definitions', '-p', type=str, default=os.path.join(os.path.dirname(__file__), '../resources/hcup_ccs_2015_definitions.yaml'), help='YAML file with phenotype definitions.') parser.add_argument('--itemids_file', '-i', type=str, help='CSV containing list of ITEMIDs to keep.') parser.add_argument('--verbose', '-v', dest='verbose', action='store_true', help='Verbosity in output') parser.add_argument('--quiet', '-q', dest='verbose', action='store_false', help='Suspend printing of details') parser.set_defaults(verbose=True) parser.add_argument('--test', action='store_true', help='TEST MODE: process only 1000 subjects, 1000000 events.') args, _ = parser.parse_known_args() try: os.makedirs(args.output_path) except: pass patients = read_patients_table(args.mimic3_path) admits = read_admissions_table(args.mimic3_path) stays = read_icustays_table(args.mimic3_path) if args.verbose: print('START:\n\tICUSTAY_IDs: {}\n\tHADM_IDs: {}\n\tSUBJECT_IDs: {}'.format(stays.ICUSTAY_ID.unique().shape[0], stays.HADM_ID.unique().shape[0], stays.SUBJECT_ID.unique().shape[0])) stays = remove_icustays_with_transfers(stays) <|code_end|> , generate the next line using the imports in this file: import argparse import yaml from mimic3benchmark.mimic3csv import * from mimic3benchmark.preprocessing import add_hcup_ccs_2015_groups, make_phenotype_label_matrix from mimic3benchmark.util import dataframe_from_csv and context (functions, classes, or occasionally code) from other files: # Path: mimic3benchmark/preprocessing.py # def add_hcup_ccs_2015_groups(diagnoses, definitions): # def_map = {} # for dx in definitions: # for code in definitions[dx]['codes']: # def_map[code] = (dx, definitions[dx]['use_in_benchmark']) # diagnoses['HCUP_CCS_2015'] = diagnoses.ICD9_CODE.apply(lambda c: def_map[c][0] if c in def_map else None) # diagnoses['USE_IN_BENCHMARK'] = diagnoses.ICD9_CODE.apply(lambda c: int(def_map[c][1]) if c in def_map else None) # return diagnoses # # def make_phenotype_label_matrix(phenotypes, stays=None): # phenotypes = phenotypes[['ICUSTAY_ID', 'HCUP_CCS_2015']].loc[phenotypes.USE_IN_BENCHMARK > 0].drop_duplicates() # phenotypes['VALUE'] = 1 # phenotypes = phenotypes.pivot(index='ICUSTAY_ID', columns='HCUP_CCS_2015', values='VALUE') # if stays is not None: # phenotypes = phenotypes.reindex(stays.ICUSTAY_ID.sort_values()) # return phenotypes.fillna(0).astype(int).sort_index(axis=0).sort_index(axis=1) # # Path: mimic3benchmark/util.py # def dataframe_from_csv(path, header=0, index_col=0): # return pd.read_csv(path, header=header, index_col=index_col) . Output only the next line.
if args.verbose:
Given the following code snippet before the placeholder: <|code_start|> pred_df = pd.read_csv(args.prediction, index_col=False, dtype={'period_length': np.float32, 'y_true': np.float32}) test_df = pd.read_csv(args.test_listfile, index_col=False, dtype={'period_length': np.float32, 'y_true': np.float32}) df = test_df.merge(pred_df, left_on=['stay', 'period_length'], right_on=['stay', 'period_length'], how='left', suffixes=['_l', '_r']) assert (df['prediction'].isnull().sum() == 0) assert (df['y_true_l'].equals(df['y_true_r'])) metrics = [('Kappa', 'kappa'), ('MAD', 'mad'), ('MSE', 'mse'), ('MAPE', 'mape')] data = np.zeros((df.shape[0], 2)) data[:, 0] = np.array(df['prediction']) data[:, 1] = np.array(df['y_true_l']) results = dict() results['n_iters'] = args.n_iters ret = print_metrics_regression(data[:, 1], data[:, 0], verbose=0) for (m, k) in metrics: results[m] = dict() results[m]['value'] = ret[k] results[m]['runs'] = [] for i in range(args.n_iters): cur_data = sk_utils.resample(data, n_samples=len(data)) ret = print_metrics_regression(cur_data[:, 1], cur_data[:, 0], verbose=0) <|code_end|> , predict the next line using imports from the current file: from mimic3models.metrics import print_metrics_regression import sklearn.utils as sk_utils import numpy as np import pandas as pd import argparse import json import os and context including class names, function names, and sometimes code from other files: # Path: mimic3models/metrics.py # def print_metrics_regression(y_true, predictions, verbose=1): # predictions = np.array(predictions) # predictions = np.maximum(predictions, 0).flatten() # y_true = np.array(y_true) # # y_true_bins = [get_bin_custom(x, CustomBins.nbins) for x in y_true] # prediction_bins = [get_bin_custom(x, CustomBins.nbins) for x in predictions] # cf = metrics.confusion_matrix(y_true_bins, prediction_bins) # if verbose: # print("Custom bins confusion matrix:") # print(cf) # # kappa = metrics.cohen_kappa_score(y_true_bins, prediction_bins, # weights='linear') # mad = metrics.mean_absolute_error(y_true, predictions) # mse = metrics.mean_squared_error(y_true, predictions) # mape = mean_absolute_percentage_error(y_true, predictions) # # if verbose: # print("Mean absolute deviation (MAD) = {}".format(mad)) # print("Mean squared error (MSE) = {}".format(mse)) # print("Mean absolute percentage error (MAPE) = {}".format(mape)) # print("Cohen kappa score = {}".format(kappa)) # # return {"mad": mad, # "mse": mse, # "mape": mape, # "kappa": kappa} . Output only the next line.
for (m, k) in metrics:
Given the code snippet: <|code_start|> test_df = pd.read_csv(args.test_listfile, index_col=False) df = test_df.merge(pred_df, left_on='stay', right_on='stay', how='left', suffixes=['_l', '_r']) assert (df['prediction'].isnull().sum() == 0) assert (df['y_true_l'].equals(df['y_true_r'])) metrics = [('AUC of ROC', 'auroc'), ('AUC of PRC', 'auprc'), ('min(+P, Se)', 'minpse')] data = np.zeros((df.shape[0], 2)) data[:, 0] = np.array(df['prediction']) data[:, 1] = np.array(df['y_true_l']) results = dict() results['n_iters'] = args.n_iters ret = print_metrics_binary(data[:, 1], data[:, 0], verbose=0) for (m, k) in metrics: results[m] = dict() results[m]['value'] = ret[k] results[m]['runs'] = [] for i in range(args.n_iters): cur_data = sk_utils.resample(data, n_samples=len(data)) ret = print_metrics_binary(cur_data[:, 1], cur_data[:, 0], verbose=0) for (m, k) in metrics: results[m]['runs'].append(ret[k]) for (m, k) in metrics: runs = results[m]['runs'] <|code_end|> , generate the next line using the imports in this file: from mimic3models.metrics import print_metrics_binary import sklearn.utils as sk_utils import numpy as np import pandas as pd import argparse import json import os and context (functions, classes, or occasionally code) from other files: # Path: mimic3models/metrics.py # def print_metrics_binary(y_true, predictions, verbose=1): # predictions = np.array(predictions) # if len(predictions.shape) == 1: # predictions = np.stack([1 - predictions, predictions]).transpose((1, 0)) # # cf = metrics.confusion_matrix(y_true, predictions.argmax(axis=1)) # if verbose: # print("confusion matrix:") # print(cf) # cf = cf.astype(np.float32) # # acc = (cf[0][0] + cf[1][1]) / np.sum(cf) # prec0 = cf[0][0] / (cf[0][0] + cf[1][0]) # prec1 = cf[1][1] / (cf[1][1] + cf[0][1]) # rec0 = cf[0][0] / (cf[0][0] + cf[0][1]) # rec1 = cf[1][1] / (cf[1][1] + cf[1][0]) # auroc = metrics.roc_auc_score(y_true, predictions[:, 1]) # # (precisions, recalls, thresholds) = metrics.precision_recall_curve(y_true, predictions[:, 1]) # auprc = metrics.auc(recalls, precisions) # minpse = np.max([min(x, y) for (x, y) in zip(precisions, recalls)]) # # if verbose: # print("accuracy = {}".format(acc)) # print("precision class 0 = {}".format(prec0)) # print("precision class 1 = {}".format(prec1)) # print("recall class 0 = {}".format(rec0)) # print("recall class 1 = {}".format(rec1)) # print("AUC of ROC = {}".format(auroc)) # print("AUC of PRC = {}".format(auprc)) # print("min(+P, Se) = {}".format(minpse)) # # return {"acc": acc, # "prec0": prec0, # "prec1": prec1, # "rec0": rec0, # "rec1": rec1, # "auroc": auroc, # "auprc": auprc, # "minpse": minpse} . Output only the next line.
results[m]['mean'] = np.mean(runs)
Here is a snippet: <|code_start|> class BatchGen(object): def __init__(self, reader, discretizer, normalizer, batch_size, steps, shuffle, return_names=False): self.reader = reader self.discretizer = discretizer self.normalizer = normalizer self.batch_size = batch_size self.shuffle = shuffle self.return_names = return_names if steps is None: self.n_examples = reader.get_number_of_examples() self.steps = (self.n_examples + batch_size - 1) // batch_size else: self.n_examples = steps * batch_size self.steps = steps self.chunk_size = min(1024, self.steps) * batch_size self.lock = threading.Lock() self.generator = self._generator() def _generator(self): B = self.batch_size while True: if self.shuffle: self.reader.random_shuffle() remaining = self.n_examples while remaining > 0: <|code_end|> . Write the next line using the current file imports: from mimic3models import common_utils import threading import os import numpy as np import random and context from other files: # Path: mimic3models/common_utils.py # def convert_to_dict(data, header, channel_info): # def extract_features_from_rawdata(chunk, header, period, features): # def read_chunk(reader, chunk_size): # def sort_and_shuffle(data, batch_size): # def add_common_arguments(parser): # def __init__(self, dataset_dir, listfile=None, small_part=False): # def _read_timeseries(self, ts_filename): # def create_directory(directory): # def pad_zeros(arr, min_length=None): # class DeepSupervisionDataLoader: , which may include functions, classes, or code. Output only the next line.
current_size = min(self.chunk_size, remaining)
Here is a snippet: <|code_start|> stays.INTIME = pd.to_datetime(stays.INTIME) stays.OUTTIME = pd.to_datetime(stays.OUTTIME) stays.DOB = pd.to_datetime(stays.DOB) stays.DOD = pd.to_datetime(stays.DOD) stays.DEATHTIME = pd.to_datetime(stays.DEATHTIME) stays.sort_values(by=['INTIME', 'OUTTIME'], inplace=True) return stays def read_diagnoses(subject_path): return dataframe_from_csv(os.path.join(subject_path, 'diagnoses.csv'), index_col=None) def read_events(subject_path, remove_null=True): events = dataframe_from_csv(os.path.join(subject_path, 'events.csv'), index_col=None) if remove_null: events = events[events.VALUE.notnull()] events.CHARTTIME = pd.to_datetime(events.CHARTTIME) events.HADM_ID = events.HADM_ID.fillna(value=-1).astype(int) events.ICUSTAY_ID = events.ICUSTAY_ID.fillna(value=-1).astype(int) events.VALUEUOM = events.VALUEUOM.fillna('').astype(str) # events.sort_values(by=['CHARTTIME', 'ITEMID', 'ICUSTAY_ID'], inplace=True) return events def get_events_for_stay(events, icustayid, intime=None, outtime=None): idx = (events.ICUSTAY_ID == icustayid) if intime is not None and outtime is not None: idx = idx | ((events.CHARTTIME >= intime) & (events.CHARTTIME <= outtime)) events = events[idx] <|code_end|> . Write the next line using the current file imports: import numpy as np import os import pandas as pd from mimic3benchmark.util import dataframe_from_csv and context from other files: # Path: mimic3benchmark/util.py # def dataframe_from_csv(path, header=0, index_col=0): # return pd.read_csv(path, header=header, index_col=index_col) , which may include functions, classes, or code. Output only the next line.
del events['ICUSTAY_ID']
Predict the next line for this snippet: <|code_start|>from __future__ import absolute_import from __future__ import print_function def main(): parser = argparse.ArgumentParser() parser.add_argument('prediction', type=str) parser.add_argument('--test_listfile', type=str, default=os.path.join(os.path.dirname(__file__), '../../data/phenotyping/test/listfile.csv')) parser.add_argument('--n_iters', type=int, default=10000) parser.add_argument('--save_file', type=str, default='pheno_results.json') args = parser.parse_args() pred_df = pd.read_csv(args.prediction, index_col=False, dtype={'period_length': np.float32}) test_df = pd.read_csv(args.test_listfile, index_col=False, dtype={'period_length': np.float32}) n_tasks = 25 labels_cols = ["label_{}".format(i) for i in range(1, n_tasks + 1)] test_df.columns = list(test_df.columns[:2]) + labels_cols df = test_df.merge(pred_df, left_on='stay', right_on='stay', how='left', suffixes=['_l', '_r']) assert (df['pred_1'].isnull().sum() == 0) <|code_end|> with the help of current file imports: from mimic3models.metrics import print_metrics_multilabel, print_metrics_binary import sklearn.utils as sk_utils import numpy as np import pandas as pd import argparse import json import os and context from other files: # Path: mimic3models/metrics.py # def print_metrics_multilabel(y_true, predictions, verbose=1): # y_true = np.array(y_true) # predictions = np.array(predictions) # # auc_scores = metrics.roc_auc_score(y_true, predictions, average=None) # ave_auc_micro = metrics.roc_auc_score(y_true, predictions, # average="micro") # ave_auc_macro = metrics.roc_auc_score(y_true, predictions, # average="macro") # ave_auc_weighted = metrics.roc_auc_score(y_true, predictions, # average="weighted") # # if verbose: # print("ROC AUC scores for labels:", auc_scores) # print("ave_auc_micro = {}".format(ave_auc_micro)) # print("ave_auc_macro = {}".format(ave_auc_macro)) # print("ave_auc_weighted = {}".format(ave_auc_weighted)) # # return {"auc_scores": auc_scores, # "ave_auc_micro": ave_auc_micro, # "ave_auc_macro": ave_auc_macro, # "ave_auc_weighted": ave_auc_weighted} # # def print_metrics_binary(y_true, predictions, verbose=1): # predictions = np.array(predictions) # if len(predictions.shape) == 1: # predictions = np.stack([1 - predictions, predictions]).transpose((1, 0)) # # cf = metrics.confusion_matrix(y_true, predictions.argmax(axis=1)) # if verbose: # print("confusion matrix:") # print(cf) # cf = cf.astype(np.float32) # # acc = (cf[0][0] + cf[1][1]) / np.sum(cf) # prec0 = cf[0][0] / (cf[0][0] + cf[1][0]) # prec1 = cf[1][1] / (cf[1][1] + cf[0][1]) # rec0 = cf[0][0] / (cf[0][0] + cf[0][1]) # rec1 = cf[1][1] / (cf[1][1] + cf[1][0]) # auroc = metrics.roc_auc_score(y_true, predictions[:, 1]) # # (precisions, recalls, thresholds) = metrics.precision_recall_curve(y_true, predictions[:, 1]) # auprc = metrics.auc(recalls, precisions) # minpse = np.max([min(x, y) for (x, y) in zip(precisions, recalls)]) # # if verbose: # print("accuracy = {}".format(acc)) # print("precision class 0 = {}".format(prec0)) # print("precision class 1 = {}".format(prec1)) # print("recall class 0 = {}".format(rec0)) # print("recall class 1 = {}".format(rec1)) # print("AUC of ROC = {}".format(auroc)) # print("AUC of PRC = {}".format(auprc)) # print("min(+P, Se) = {}".format(minpse)) # # return {"acc": acc, # "prec0": prec0, # "prec1": prec1, # "rec0": rec0, # "rec1": rec1, # "auroc": auroc, # "auprc": auprc, # "minpse": minpse} , which may contain function names, class names, or code. Output only the next line.
assert (df['period_length_l'].equals(df['period_length_r']))
Continue the code snippet: <|code_start|> parser = argparse.ArgumentParser() parser.add_argument('prediction', type=str) parser.add_argument('--test_listfile', type=str, default=os.path.join(os.path.dirname(__file__), '../../data/phenotyping/test/listfile.csv')) parser.add_argument('--n_iters', type=int, default=10000) parser.add_argument('--save_file', type=str, default='pheno_results.json') args = parser.parse_args() pred_df = pd.read_csv(args.prediction, index_col=False, dtype={'period_length': np.float32}) test_df = pd.read_csv(args.test_listfile, index_col=False, dtype={'period_length': np.float32}) n_tasks = 25 labels_cols = ["label_{}".format(i) for i in range(1, n_tasks + 1)] test_df.columns = list(test_df.columns[:2]) + labels_cols df = test_df.merge(pred_df, left_on='stay', right_on='stay', how='left', suffixes=['_l', '_r']) assert (df['pred_1'].isnull().sum() == 0) assert (df['period_length_l'].equals(df['period_length_r'])) for i in range(1, n_tasks + 1): assert (df['label_{}_l'.format(i)].equals(df['label_{}_r'.format(i)])) metrics = [('Macro ROC AUC', 'ave_auc_macro'), ('Micro ROC AUC', 'ave_auc_micro'), ('Weighted ROC AUC', 'ave_auc_weighted')] data = np.zeros((df.shape[0], 50)) for i in range(1, n_tasks + 1): data[:, i - 1] = df['pred_{}'.format(i)] data[:, 25 + i - 1] = df['label_{}_l'.format(i)] <|code_end|> . Use current file imports: from mimic3models.metrics import print_metrics_multilabel, print_metrics_binary import sklearn.utils as sk_utils import numpy as np import pandas as pd import argparse import json import os and context (classes, functions, or code) from other files: # Path: mimic3models/metrics.py # def print_metrics_multilabel(y_true, predictions, verbose=1): # y_true = np.array(y_true) # predictions = np.array(predictions) # # auc_scores = metrics.roc_auc_score(y_true, predictions, average=None) # ave_auc_micro = metrics.roc_auc_score(y_true, predictions, # average="micro") # ave_auc_macro = metrics.roc_auc_score(y_true, predictions, # average="macro") # ave_auc_weighted = metrics.roc_auc_score(y_true, predictions, # average="weighted") # # if verbose: # print("ROC AUC scores for labels:", auc_scores) # print("ave_auc_micro = {}".format(ave_auc_micro)) # print("ave_auc_macro = {}".format(ave_auc_macro)) # print("ave_auc_weighted = {}".format(ave_auc_weighted)) # # return {"auc_scores": auc_scores, # "ave_auc_micro": ave_auc_micro, # "ave_auc_macro": ave_auc_macro, # "ave_auc_weighted": ave_auc_weighted} # # def print_metrics_binary(y_true, predictions, verbose=1): # predictions = np.array(predictions) # if len(predictions.shape) == 1: # predictions = np.stack([1 - predictions, predictions]).transpose((1, 0)) # # cf = metrics.confusion_matrix(y_true, predictions.argmax(axis=1)) # if verbose: # print("confusion matrix:") # print(cf) # cf = cf.astype(np.float32) # # acc = (cf[0][0] + cf[1][1]) / np.sum(cf) # prec0 = cf[0][0] / (cf[0][0] + cf[1][0]) # prec1 = cf[1][1] / (cf[1][1] + cf[0][1]) # rec0 = cf[0][0] / (cf[0][0] + cf[0][1]) # rec1 = cf[1][1] / (cf[1][1] + cf[1][0]) # auroc = metrics.roc_auc_score(y_true, predictions[:, 1]) # # (precisions, recalls, thresholds) = metrics.precision_recall_curve(y_true, predictions[:, 1]) # auprc = metrics.auc(recalls, precisions) # minpse = np.max([min(x, y) for (x, y) in zip(precisions, recalls)]) # # if verbose: # print("accuracy = {}".format(acc)) # print("precision class 0 = {}".format(prec0)) # print("precision class 1 = {}".format(prec1)) # print("recall class 0 = {}".format(rec0)) # print("recall class 1 = {}".format(rec1)) # print("AUC of ROC = {}".format(auroc)) # print("AUC of PRC = {}".format(auprc)) # print("min(+P, Se) = {}".format(minpse)) # # return {"acc": acc, # "prec0": prec0, # "prec1": prec1, # "rec0": rec0, # "rec1": rec1, # "auroc": auroc, # "auprc": auprc, # "minpse": minpse} . Output only the next line.
results = dict()
Given snippet: <|code_start|> self.steps = (N + batch_size - 1) // batch_size self.lock = threading.Lock() ret = common_utils.read_chunk(reader, N) Xs = ret['X'] ts = ret['t'] ihms = ret['ihm'] loss = ret['los'] phenos = ret['pheno'] decomps = ret['decomp'] self.data = dict() self.data['pheno_ts'] = ts self.data['names'] = ret['name'] self.data['decomp_ts'] = [] self.data['los_ts'] = [] for i in range(N): self.data['decomp_ts'].append([pos for pos, m in enumerate(decomps[i][0]) if m == 1]) self.data['los_ts'].append([pos for pos, m in enumerate(loss[i][0]) if m == 1]) (Xs[i], ihms[i], decomps[i], loss[i], phenos[i]) = \ self._preprocess_single(Xs[i], ts[i], ihms[i], decomps[i], loss[i], phenos[i]) self.data['X'] = Xs self.data['ihm_M'] = [x[0] for x in ihms] self.data['ihm_y'] = [x[1] for x in ihms] self.data['decomp_M'] = [x[0] for x in decomps] self.data['decomp_y'] = [x[1] for x in decomps] self.data['los_M'] = [x[0] for x in loss] self.data['los_y'] = [x[1] for x in loss] <|code_end|> , continue by predicting the next line. Consider current file imports: from mimic3models import metrics from mimic3models import common_utils import numpy as np import threading import random and context: # Path: mimic3models/metrics.py # def print_metrics_binary(y_true, predictions, verbose=1): # def print_metrics_multilabel(y_true, predictions, verbose=1): # def mean_absolute_percentage_error(y_true, y_pred): # def print_metrics_regression(y_true, predictions, verbose=1): # def get_bin_log(x, nbins, one_hot=False): # def get_estimate_log(prediction, nbins): # def print_metrics_log_bins(y_true, predictions, verbose=1): # def get_bin_custom(x, nbins, one_hot=False): # def get_estimate_custom(prediction, nbins): # def print_metrics_custom_bins(y_true, predictions, verbose=1): # class LogBins: # class CustomBins: # # Path: mimic3models/common_utils.py # def convert_to_dict(data, header, channel_info): # def extract_features_from_rawdata(chunk, header, period, features): # def read_chunk(reader, chunk_size): # def sort_and_shuffle(data, batch_size): # def add_common_arguments(parser): # def __init__(self, dataset_dir, listfile=None, small_part=False): # def _read_timeseries(self, ts_filename): # def create_directory(directory): # def pad_zeros(arr, min_length=None): # class DeepSupervisionDataLoader: which might include code, classes, or functions. Output only the next line.
self.data['pheno_y'] = phenos
Predict the next line after this snippet: <|code_start|> los_M = common_utils.pad_zeros(los_M, min_length=self.ihm_pos + 1) los_y = self.data['los_y'][i:i+B] los_y_true = common_utils.pad_zeros(los_y, min_length=self.ihm_pos + 1) if self.partition == 'log': los_y = [np.array([metrics.get_bin_log(x, 10) for x in z]) for z in los_y] if self.partition == 'custom': los_y = [np.array([metrics.get_bin_custom(x, 10) for x in z]) for z in los_y] los_y = common_utils.pad_zeros(los_y, min_length=self.ihm_pos + 1) los_y = np.expand_dims(los_y, axis=-1) # (B, T, 1) outputs.append(los_y) # pheno pheno_y = np.array(self.data['pheno_y'][i:i+B]) outputs.append(pheno_y) if self.target_repl: pheno_seq = np.expand_dims(pheno_y, axis=1).repeat(T, axis=1) # (B, T, 25) outputs.append(pheno_seq) inputs = [X, ihm_M, decomp_M, los_M] if self.return_y_true: batch_data = (inputs, outputs, los_y_true) else: batch_data = (inputs, outputs) if not self.return_names: yield batch_data else: yield {'data': batch_data, <|code_end|> using the current file's imports: from mimic3models import metrics from mimic3models import common_utils import numpy as np import threading import random and any relevant context from other files: # Path: mimic3models/metrics.py # def print_metrics_binary(y_true, predictions, verbose=1): # def print_metrics_multilabel(y_true, predictions, verbose=1): # def mean_absolute_percentage_error(y_true, y_pred): # def print_metrics_regression(y_true, predictions, verbose=1): # def get_bin_log(x, nbins, one_hot=False): # def get_estimate_log(prediction, nbins): # def print_metrics_log_bins(y_true, predictions, verbose=1): # def get_bin_custom(x, nbins, one_hot=False): # def get_estimate_custom(prediction, nbins): # def print_metrics_custom_bins(y_true, predictions, verbose=1): # class LogBins: # class CustomBins: # # Path: mimic3models/common_utils.py # def convert_to_dict(data, header, channel_info): # def extract_features_from_rawdata(chunk, header, period, features): # def read_chunk(reader, chunk_size): # def sort_and_shuffle(data, batch_size): # def add_common_arguments(parser): # def __init__(self, dataset_dir, listfile=None, small_part=False): # def _read_timeseries(self, ts_filename): # def create_directory(directory): # def pad_zeros(arr, min_length=None): # class DeepSupervisionDataLoader: . Output only the next line.
'names': self.data['names'][i:i+B],
Using the snippet: <|code_start|> Xs = ret["X"] ts = ret["t"] ys = ret["y"] names = ret["name"] Xs = preprocess_chunk(Xs, ts, self.discretizer, self.normalizer) (Xs, ys, ts, names) = common_utils.sort_and_shuffle([Xs, ys, ts, names], B) for i in range(0, current_size, B): X = common_utils.pad_zeros(Xs[i:i + B]) y = ys[i:i+B] y_true = np.array(y) batch_names = names[i:i+B] batch_ts = ts[i:i+B] if self.partition == 'log': y = [metrics.get_bin_log(x, 10) for x in y] if self.partition == 'custom': y = [metrics.get_bin_custom(x, 10) for x in y] y = np.array(y) if self.return_y_true: batch_data = (X, y, y_true) else: batch_data = (X, y) if not self.return_names: yield batch_data else: <|code_end|> , determine the next line of code. You have imports: from mimic3models import metrics from mimic3models import common_utils import threading import os import numpy as np import random and context (class names, function names, or code) available: # Path: mimic3models/metrics.py # def print_metrics_binary(y_true, predictions, verbose=1): # def print_metrics_multilabel(y_true, predictions, verbose=1): # def mean_absolute_percentage_error(y_true, y_pred): # def print_metrics_regression(y_true, predictions, verbose=1): # def get_bin_log(x, nbins, one_hot=False): # def get_estimate_log(prediction, nbins): # def print_metrics_log_bins(y_true, predictions, verbose=1): # def get_bin_custom(x, nbins, one_hot=False): # def get_estimate_custom(prediction, nbins): # def print_metrics_custom_bins(y_true, predictions, verbose=1): # class LogBins: # class CustomBins: # # Path: mimic3models/common_utils.py # def convert_to_dict(data, header, channel_info): # def extract_features_from_rawdata(chunk, header, period, features): # def read_chunk(reader, chunk_size): # def sort_and_shuffle(data, batch_size): # def add_common_arguments(parser): # def __init__(self, dataset_dir, listfile=None, small_part=False): # def _read_timeseries(self, ts_filename): # def create_directory(directory): # def pad_zeros(arr, min_length=None): # class DeepSupervisionDataLoader: . Output only the next line.
yield {"data": batch_data, "names": batch_names, "ts": batch_ts}
Given the following code snippet before the placeholder: <|code_start|> assert np.sum(mask) > 0 assert len(X) == len(mask) and len(X) == len(y) self.data = [[Xs, masks], ys] self.names = names self.ts = ts def _generator(self): B = self.batch_size while True: if self.shuffle: N = len(self.data[1]) order = list(range(N)) random.shuffle(order) tmp_data = [[[None]*N, [None]*N], [None]*N] tmp_names = [None] * N tmp_ts = [None] * N for i in range(N): tmp_data[0][0][i] = self.data[0][0][order[i]] tmp_data[0][1][i] = self.data[0][1][order[i]] tmp_data[1][i] = self.data[1][order[i]] tmp_names[i] = self.names[order[i]] tmp_ts[i] = self.ts[order[i]] self.data = tmp_data self.names = tmp_names self.ts = tmp_ts else: # sort entirely Xs = self.data[0][0] <|code_end|> , predict the next line using imports from the current file: from mimic3models import metrics from mimic3models import common_utils import threading import os import numpy as np import random and context including class names, function names, and sometimes code from other files: # Path: mimic3models/metrics.py # def print_metrics_binary(y_true, predictions, verbose=1): # def print_metrics_multilabel(y_true, predictions, verbose=1): # def mean_absolute_percentage_error(y_true, y_pred): # def print_metrics_regression(y_true, predictions, verbose=1): # def get_bin_log(x, nbins, one_hot=False): # def get_estimate_log(prediction, nbins): # def print_metrics_log_bins(y_true, predictions, verbose=1): # def get_bin_custom(x, nbins, one_hot=False): # def get_estimate_custom(prediction, nbins): # def print_metrics_custom_bins(y_true, predictions, verbose=1): # class LogBins: # class CustomBins: # # Path: mimic3models/common_utils.py # def convert_to_dict(data, header, channel_info): # def extract_features_from_rawdata(chunk, header, period, features): # def read_chunk(reader, chunk_size): # def sort_and_shuffle(data, batch_size): # def add_common_arguments(parser): # def __init__(self, dataset_dir, listfile=None, small_part=False): # def _read_timeseries(self, ts_filename): # def create_directory(directory): # def pad_zeros(arr, min_length=None): # class DeepSupervisionDataLoader: . Output only the next line.
masks = self.data[0][1]
Predict the next line for this snippet: <|code_start|> def add_hcup_ccs_2015_groups(diagnoses, definitions): def_map = {} for dx in definitions: for code in definitions[dx]['codes']: def_map[code] = (dx, definitions[dx]['use_in_benchmark']) diagnoses['HCUP_CCS_2015'] = diagnoses.ICD9_CODE.apply(lambda c: def_map[c][0] if c in def_map else None) diagnoses['USE_IN_BENCHMARK'] = diagnoses.ICD9_CODE.apply(lambda c: int(def_map[c][1]) if c in def_map else None) return diagnoses def make_phenotype_label_matrix(phenotypes, stays=None): phenotypes = phenotypes[['ICUSTAY_ID', 'HCUP_CCS_2015']].loc[phenotypes.USE_IN_BENCHMARK > 0].drop_duplicates() phenotypes['VALUE'] = 1 phenotypes = phenotypes.pivot(index='ICUSTAY_ID', columns='HCUP_CCS_2015', values='VALUE') if stays is not None: phenotypes = phenotypes.reindex(stays.ICUSTAY_ID.sort_values()) return phenotypes.fillna(0).astype(int).sort_index(axis=0).sort_index(axis=1) ################################### # Time series preprocessing ################################### def read_itemid_to_variable_map(fn, variable_column='LEVEL2'): var_map = dataframe_from_csv(fn, index_col=None).fillna('').astype(str) # var_map[variable_column] = var_map[variable_column].apply(lambda s: s.lower()) var_map.COUNT = var_map.COUNT.astype(int) var_map = var_map[(var_map[variable_column] != '') & (var_map.COUNT > 0)] var_map = var_map[(var_map.STATUS == 'ready')] <|code_end|> with the help of current file imports: import numpy as np import re import traceback from pandas import DataFrame, Series from mimic3benchmark.util import dataframe_from_csv and context from other files: # Path: mimic3benchmark/util.py # def dataframe_from_csv(path, header=0, index_col=0): # return pd.read_csv(path, header=header, index_col=index_col) , which may contain function names, class names, or code. Output only the next line.
var_map.ITEMID = var_map.ITEMID.astype(int)
Based on the snippet: <|code_start|> for k, v in ret.items(): logs[dataset + '_' + k] = v history.append(ret) def on_epoch_end(self, epoch, logs={}): print("\n==>predicting on train") self.calc_metrics(self.train_data, self.train_history, 'train', logs) print("\n==>predicting on validation") self.calc_metrics(self.val_data, self.val_history, 'val', logs) if self.early_stopping: max_auc = np.max([x["auroc"] for x in self.val_history]) cur_auc = self.val_history[-1]["auroc"] if max_auc > 0.85 and cur_auc < 0.83: self.model.stop_training = True class PhenotypingMetrics(keras.callbacks.Callback): def __init__(self, train_data_gen, val_data_gen, batch_size=32, early_stopping=True, verbose=2): super(PhenotypingMetrics, self).__init__() self.train_data_gen = train_data_gen self.val_data_gen = val_data_gen self.batch_size = batch_size self.early_stopping = early_stopping self.verbose = verbose self.train_history = [] self.val_history = [] def calc_metrics(self, data_gen, history, dataset, logs): <|code_end|> , predict the immediate next line with the help of imports: import numpy as np import keras import keras.backend as K import tensorflow as tf from mimic3models import metrics from keras.layers import Layer and context (classes, functions, sometimes code) from other files: # Path: mimic3models/metrics.py # def print_metrics_binary(y_true, predictions, verbose=1): # def print_metrics_multilabel(y_true, predictions, verbose=1): # def mean_absolute_percentage_error(y_true, y_pred): # def print_metrics_regression(y_true, predictions, verbose=1): # def get_bin_log(x, nbins, one_hot=False): # def get_estimate_log(prediction, nbins): # def print_metrics_log_bins(y_true, predictions, verbose=1): # def get_bin_custom(x, nbins, one_hot=False): # def get_estimate_custom(prediction, nbins): # def print_metrics_custom_bins(y_true, predictions, verbose=1): # class LogBins: # class CustomBins: . Output only the next line.
y_true = []
Given the code snippet: <|code_start|> inputs.append(M) # Configurations is_bidirectional = True if deep_supervision: is_bidirectional = False # Main part of the network for i in range(depth - 1): num_units = dim if is_bidirectional: num_units = num_units // 2 lstm = LSTM(units=num_units, activation='tanh', return_sequences=True, recurrent_dropout=rec_dropout, dropout=dropout) if is_bidirectional: mX = Bidirectional(lstm)(mX) else: mX = lstm(mX) # Output module of the network return_sequences = (target_repl or deep_supervision) L = LSTM(units=dim, activation='tanh', return_sequences=return_sequences, dropout=dropout, <|code_end|> , generate the next line using the imports in this file: from keras.models import Model from keras.layers import Input, Dense, LSTM, Masking, Dropout from keras.layers.wrappers import Bidirectional, TimeDistributed from mimic3models.keras_utils import LastTimestep from mimic3models.keras_utils import ExtendMask and context (functions, classes, or occasionally code) from other files: # Path: mimic3models/keras_utils.py # class DecompensationMetrics(keras.callbacks.Callback): # class InHospitalMortalityMetrics(keras.callbacks.Callback): # class PhenotypingMetrics(keras.callbacks.Callback): # class LengthOfStayMetrics(keras.callbacks.Callback): # class MultitaskMetrics(keras.callbacks.Callback): # class CollectAttetion(Layer): # class Slice(Layer): # class GetTimestep(Layer): # class ExtendMask(Layer): # def __init__(self, train_data_gen, val_data_gen, deep_supervision, # batch_size=32, early_stopping=True, verbose=2): # def calc_metrics(self, data_gen, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def __init__(self, train_data, val_data, target_repl, batch_size=32, early_stopping=True, verbose=2): # def calc_metrics(self, data, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def __init__(self, train_data_gen, val_data_gen, batch_size=32, # early_stopping=True, verbose=2): # def calc_metrics(self, data_gen, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def __init__(self, train_data_gen, val_data_gen, partition, batch_size=32, # early_stopping=True, verbose=2): # def calc_metrics(self, data_gen, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def __init__(self, train_data_gen, val_data_gen, partition, # batch_size=32, early_stopping=True, verbose=2): # def calc_metrics(self, data_gen, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def softmax(x, axis, mask=None): # def _collect_attention(x, a, mask): # def __init__(self, **kwargs): # def call(self, inputs, mask=None): # def compute_output_shape(self, input_shape): # def compute_mask(self, input, input_mask=None): # def __init__(self, indices, **kwargs): # def call(self, x, mask=None): # def compute_output_shape(self, input_shape): # def compute_mask(self, input, input_mask=None): # def get_config(self): # def __init__(self, pos=-1, **kwargs): # def call(self, x, mask=None): # def compute_output_shape(self, input_shape): # def compute_mask(self, input, input_mask=None): # def get_config(self): # def __init__(self, add_epsilon=False, **kwargs): # def call(self, x, mask=None): # def compute_output_shape(self, input_shape): # def compute_mask(self, input, input_mask=None): # def get_config(self): # B = self.batch_size # # Path: mimic3models/keras_utils.py # class ExtendMask(Layer): # """ Inputs: [X, M] # Output: X # Output_mask: M # """ # # def __init__(self, add_epsilon=False, **kwargs): # self.supports_masking = True # self.add_epsilon = add_epsilon # super(ExtendMask, self).__init__(**kwargs) # # def call(self, x, mask=None): # return x[0] # # def compute_output_shape(self, input_shape): # return input_shape[0] # # def compute_mask(self, input, input_mask=None): # if self.add_epsilon: # return input[1] + K.epsilon() # return input[1] # # def get_config(self): # return {'add_epsilon': self.add_epsilon} . Output only the next line.
recurrent_dropout=rec_dropout)(mX)
Given snippet: <|code_start|> # Main part of the network for i in range(depth - 1): num_units = dim if is_bidirectional: num_units = num_units // 2 lstm = LSTM(units=num_units, activation='tanh', return_sequences=True, recurrent_dropout=rec_dropout, dropout=dropout) if is_bidirectional: mX = Bidirectional(lstm)(mX) else: mX = lstm(mX) # Output module of the network return_sequences = (target_repl or deep_supervision) L = LSTM(units=dim, activation='tanh', return_sequences=return_sequences, dropout=dropout, recurrent_dropout=rec_dropout)(mX) if dropout > 0: L = Dropout(dropout)(L) if target_repl: y = TimeDistributed(Dense(num_classes, activation=final_activation), <|code_end|> , continue by predicting the next line. Consider current file imports: from keras.models import Model from keras.layers import Input, Dense, LSTM, Masking, Dropout from keras.layers.wrappers import Bidirectional, TimeDistributed from mimic3models.keras_utils import LastTimestep from mimic3models.keras_utils import ExtendMask and context: # Path: mimic3models/keras_utils.py # class DecompensationMetrics(keras.callbacks.Callback): # class InHospitalMortalityMetrics(keras.callbacks.Callback): # class PhenotypingMetrics(keras.callbacks.Callback): # class LengthOfStayMetrics(keras.callbacks.Callback): # class MultitaskMetrics(keras.callbacks.Callback): # class CollectAttetion(Layer): # class Slice(Layer): # class GetTimestep(Layer): # class ExtendMask(Layer): # def __init__(self, train_data_gen, val_data_gen, deep_supervision, # batch_size=32, early_stopping=True, verbose=2): # def calc_metrics(self, data_gen, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def __init__(self, train_data, val_data, target_repl, batch_size=32, early_stopping=True, verbose=2): # def calc_metrics(self, data, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def __init__(self, train_data_gen, val_data_gen, batch_size=32, # early_stopping=True, verbose=2): # def calc_metrics(self, data_gen, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def __init__(self, train_data_gen, val_data_gen, partition, batch_size=32, # early_stopping=True, verbose=2): # def calc_metrics(self, data_gen, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def __init__(self, train_data_gen, val_data_gen, partition, # batch_size=32, early_stopping=True, verbose=2): # def calc_metrics(self, data_gen, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def softmax(x, axis, mask=None): # def _collect_attention(x, a, mask): # def __init__(self, **kwargs): # def call(self, inputs, mask=None): # def compute_output_shape(self, input_shape): # def compute_mask(self, input, input_mask=None): # def __init__(self, indices, **kwargs): # def call(self, x, mask=None): # def compute_output_shape(self, input_shape): # def compute_mask(self, input, input_mask=None): # def get_config(self): # def __init__(self, pos=-1, **kwargs): # def call(self, x, mask=None): # def compute_output_shape(self, input_shape): # def compute_mask(self, input, input_mask=None): # def get_config(self): # def __init__(self, add_epsilon=False, **kwargs): # def call(self, x, mask=None): # def compute_output_shape(self, input_shape): # def compute_mask(self, input, input_mask=None): # def get_config(self): # B = self.batch_size # # Path: mimic3models/keras_utils.py # class ExtendMask(Layer): # """ Inputs: [X, M] # Output: X # Output_mask: M # """ # # def __init__(self, add_epsilon=False, **kwargs): # self.supports_masking = True # self.add_epsilon = add_epsilon # super(ExtendMask, self).__init__(**kwargs) # # def call(self, x, mask=None): # return x[0] # # def compute_output_shape(self, input_shape): # return input_shape[0] # # def compute_mask(self, input, input_mask=None): # if self.add_epsilon: # return input[1] + K.epsilon() # return input[1] # # def get_config(self): # return {'add_epsilon': self.add_epsilon} which might include code, classes, or functions. Output only the next line.
name='seq')(L)
Here is a snippet: <|code_start|> dn = os.path.join(output_path, str(subject_id)) try: os.makedirs(dn) except: pass diagnoses[diagnoses.SUBJECT_ID == subject_id].sort_values(by=['ICUSTAY_ID', 'SEQ_NUM'])\ .to_csv(os.path.join(dn, 'diagnoses.csv'), index=False) def read_events_table_and_break_up_by_subject(mimic3_path, table, output_path, items_to_keep=None, subjects_to_keep=None): obs_header = ['SUBJECT_ID', 'HADM_ID', 'ICUSTAY_ID', 'CHARTTIME', 'ITEMID', 'VALUE', 'VALUEUOM'] if items_to_keep is not None: items_to_keep = set([str(s) for s in items_to_keep]) if subjects_to_keep is not None: subjects_to_keep = set([str(s) for s in subjects_to_keep]) class DataStats(object): def __init__(self): self.curr_subject_id = '' self.curr_obs = [] data_stats = DataStats() def write_current_observations(): dn = os.path.join(output_path, str(data_stats.curr_subject_id)) try: os.makedirs(dn) except: <|code_end|> . Write the next line using the current file imports: import csv import numpy as np import os import pandas as pd from tqdm import tqdm from mimic3benchmark.util import dataframe_from_csv and context from other files: # Path: mimic3benchmark/util.py # def dataframe_from_csv(path, header=0, index_col=0): # return pd.read_csv(path, header=header, index_col=index_col) , which may include functions, classes, or code. Output only the next line.
pass
Predict the next line for this snippet: <|code_start|> self.ts = tmp_ts else: # sort entirely X = self.data[0] y = self.data[1] (X, y, self.names, self.ts) = common_utils.sort_and_shuffle([X, y, self.names, self.ts], B) self.data = [X, y] self.data[1] = np.array(self.data[1]) # this is important for Keras for i in range(0, len(self.data[0]), B): x = self.data[0][i:i+B] y = self.data[1][i:i+B] names = self.names[i:i + B] ts = self.ts[i:i + B] x = common_utils.pad_zeros(x) y = np.array(y) # (B, 25) if self.target_repl: y_rep = np.expand_dims(y, axis=1).repeat(x.shape[1], axis=1) # (B, T, 25) batch_data = (x, [y, y_rep]) else: batch_data = (x, y) if not self.return_names: yield batch_data else: yield {"data": batch_data, "names": names, "ts": ts} def __iter__(self): <|code_end|> with the help of current file imports: import numpy as np import threading import random import os from mimic3models import common_utils and context from other files: # Path: mimic3models/common_utils.py # def convert_to_dict(data, header, channel_info): # def extract_features_from_rawdata(chunk, header, period, features): # def read_chunk(reader, chunk_size): # def sort_and_shuffle(data, batch_size): # def add_common_arguments(parser): # def __init__(self, dataset_dir, listfile=None, small_part=False): # def _read_timeseries(self, ts_filename): # def create_directory(directory): # def pad_zeros(arr, min_length=None): # class DeepSupervisionDataLoader: , which may contain function names, class names, or code. Output only the next line.
return self.generator
Predict the next line after this snippet: <|code_start|> self.dim = dim self.batch_norm = batch_norm self.dropout = dropout self.rec_dropout = rec_dropout self.depth = depth self.size_coef = size_coef if task in ['decomp', 'ihm', 'ph']: final_activation = 'sigmoid' elif task in ['los']: if num_classes == 1: final_activation = 'relu' else: final_activation = 'softmax' else: raise ValueError("Wrong value for task") print("==> not used params in network class:", kwargs.keys()) # Parse channels channel_names = set() for ch in header: if ch.find("mask->") != -1: continue pos = ch.find("->") if pos != -1: channel_names.add(ch[:pos]) else: channel_names.add(ch) <|code_end|> using the current file's imports: from keras.models import Model from keras.layers import Input, Dense, LSTM, Masking, Dropout from keras.layers.wrappers import Bidirectional, TimeDistributed from mimic3models.keras_utils import Slice, LastTimestep from keras.layers.merge import Concatenate from mimic3models.keras_utils import ExtendMask and any relevant context from other files: # Path: mimic3models/keras_utils.py # class DecompensationMetrics(keras.callbacks.Callback): # class InHospitalMortalityMetrics(keras.callbacks.Callback): # class PhenotypingMetrics(keras.callbacks.Callback): # class LengthOfStayMetrics(keras.callbacks.Callback): # class MultitaskMetrics(keras.callbacks.Callback): # class CollectAttetion(Layer): # class Slice(Layer): # class GetTimestep(Layer): # class ExtendMask(Layer): # def __init__(self, train_data_gen, val_data_gen, deep_supervision, # batch_size=32, early_stopping=True, verbose=2): # def calc_metrics(self, data_gen, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def __init__(self, train_data, val_data, target_repl, batch_size=32, early_stopping=True, verbose=2): # def calc_metrics(self, data, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def __init__(self, train_data_gen, val_data_gen, batch_size=32, # early_stopping=True, verbose=2): # def calc_metrics(self, data_gen, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def __init__(self, train_data_gen, val_data_gen, partition, batch_size=32, # early_stopping=True, verbose=2): # def calc_metrics(self, data_gen, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def __init__(self, train_data_gen, val_data_gen, partition, # batch_size=32, early_stopping=True, verbose=2): # def calc_metrics(self, data_gen, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def softmax(x, axis, mask=None): # def _collect_attention(x, a, mask): # def __init__(self, **kwargs): # def call(self, inputs, mask=None): # def compute_output_shape(self, input_shape): # def compute_mask(self, input, input_mask=None): # def __init__(self, indices, **kwargs): # def call(self, x, mask=None): # def compute_output_shape(self, input_shape): # def compute_mask(self, input, input_mask=None): # def get_config(self): # def __init__(self, pos=-1, **kwargs): # def call(self, x, mask=None): # def compute_output_shape(self, input_shape): # def compute_mask(self, input, input_mask=None): # def get_config(self): # def __init__(self, add_epsilon=False, **kwargs): # def call(self, x, mask=None): # def compute_output_shape(self, input_shape): # def compute_mask(self, input, input_mask=None): # def get_config(self): # B = self.batch_size # # Path: mimic3models/keras_utils.py # class ExtendMask(Layer): # """ Inputs: [X, M] # Output: X # Output_mask: M # """ # # def __init__(self, add_epsilon=False, **kwargs): # self.supports_masking = True # self.add_epsilon = add_epsilon # super(ExtendMask, self).__init__(**kwargs) # # def call(self, x, mask=None): # return x[0] # # def compute_output_shape(self, input_shape): # return input_shape[0] # # def compute_mask(self, input, input_mask=None): # if self.add_epsilon: # return input[1] + K.epsilon() # return input[1] # # def get_config(self): # return {'add_epsilon': self.add_epsilon} . Output only the next line.
channel_names = sorted(list(channel_names))
Using the snippet: <|code_start|> inputs = [X] mX = Masking()(X) if deep_supervision: M = Input(shape=(None,), name='M') inputs.append(M) # Configurations is_bidirectional = True if deep_supervision: is_bidirectional = False # Preprocess each channel cX = [] for ch in channels: cX.append(Slice(ch)(mX)) pX = [] # LSTM processed version of cX for x in cX: p = x for i in range(depth): num_units = dim if is_bidirectional: num_units = num_units // 2 lstm = LSTM(units=num_units, activation='tanh', return_sequences=True, dropout=dropout, recurrent_dropout=rec_dropout) <|code_end|> , determine the next line of code. You have imports: from keras.models import Model from keras.layers import Input, Dense, LSTM, Masking, Dropout from keras.layers.wrappers import Bidirectional, TimeDistributed from mimic3models.keras_utils import Slice, LastTimestep from keras.layers.merge import Concatenate from mimic3models.keras_utils import ExtendMask and context (class names, function names, or code) available: # Path: mimic3models/keras_utils.py # class DecompensationMetrics(keras.callbacks.Callback): # class InHospitalMortalityMetrics(keras.callbacks.Callback): # class PhenotypingMetrics(keras.callbacks.Callback): # class LengthOfStayMetrics(keras.callbacks.Callback): # class MultitaskMetrics(keras.callbacks.Callback): # class CollectAttetion(Layer): # class Slice(Layer): # class GetTimestep(Layer): # class ExtendMask(Layer): # def __init__(self, train_data_gen, val_data_gen, deep_supervision, # batch_size=32, early_stopping=True, verbose=2): # def calc_metrics(self, data_gen, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def __init__(self, train_data, val_data, target_repl, batch_size=32, early_stopping=True, verbose=2): # def calc_metrics(self, data, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def __init__(self, train_data_gen, val_data_gen, batch_size=32, # early_stopping=True, verbose=2): # def calc_metrics(self, data_gen, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def __init__(self, train_data_gen, val_data_gen, partition, batch_size=32, # early_stopping=True, verbose=2): # def calc_metrics(self, data_gen, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def __init__(self, train_data_gen, val_data_gen, partition, # batch_size=32, early_stopping=True, verbose=2): # def calc_metrics(self, data_gen, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def softmax(x, axis, mask=None): # def _collect_attention(x, a, mask): # def __init__(self, **kwargs): # def call(self, inputs, mask=None): # def compute_output_shape(self, input_shape): # def compute_mask(self, input, input_mask=None): # def __init__(self, indices, **kwargs): # def call(self, x, mask=None): # def compute_output_shape(self, input_shape): # def compute_mask(self, input, input_mask=None): # def get_config(self): # def __init__(self, pos=-1, **kwargs): # def call(self, x, mask=None): # def compute_output_shape(self, input_shape): # def compute_mask(self, input, input_mask=None): # def get_config(self): # def __init__(self, add_epsilon=False, **kwargs): # def call(self, x, mask=None): # def compute_output_shape(self, input_shape): # def compute_mask(self, input, input_mask=None): # def get_config(self): # B = self.batch_size # # Path: mimic3models/keras_utils.py # class ExtendMask(Layer): # """ Inputs: [X, M] # Output: X # Output_mask: M # """ # # def __init__(self, add_epsilon=False, **kwargs): # self.supports_masking = True # self.add_epsilon = add_epsilon # super(ExtendMask, self).__init__(**kwargs) # # def call(self, x, mask=None): # return x[0] # # def compute_output_shape(self, input_shape): # return input_shape[0] # # def compute_mask(self, input, input_mask=None): # if self.add_epsilon: # return input[1] + K.epsilon() # return input[1] # # def get_config(self): # return {'add_epsilon': self.add_epsilon} . Output only the next line.
if is_bidirectional:
Using the snippet: <|code_start|> # Main part of the network for i in range(depth-1): num_units = int(size_coef*dim) if is_bidirectional: num_units = num_units // 2 lstm = LSTM(units=num_units, activation='tanh', return_sequences=True, dropout=dropout, recurrent_dropout=rec_dropout) if is_bidirectional: Z = Bidirectional(lstm)(Z) else: Z = lstm(Z) # Output module of the network return_sequences = (target_repl or deep_supervision) L = LSTM(units=int(size_coef*dim), activation='tanh', return_sequences=return_sequences, dropout=dropout, recurrent_dropout=rec_dropout)(Z) if dropout > 0: L = Dropout(dropout)(L) if target_repl: <|code_end|> , determine the next line of code. You have imports: from keras.models import Model from keras.layers import Input, Dense, LSTM, Masking, Dropout from keras.layers.wrappers import Bidirectional, TimeDistributed from mimic3models.keras_utils import Slice, LastTimestep from keras.layers.merge import Concatenate from mimic3models.keras_utils import ExtendMask and context (class names, function names, or code) available: # Path: mimic3models/keras_utils.py # class DecompensationMetrics(keras.callbacks.Callback): # class InHospitalMortalityMetrics(keras.callbacks.Callback): # class PhenotypingMetrics(keras.callbacks.Callback): # class LengthOfStayMetrics(keras.callbacks.Callback): # class MultitaskMetrics(keras.callbacks.Callback): # class CollectAttetion(Layer): # class Slice(Layer): # class GetTimestep(Layer): # class ExtendMask(Layer): # def __init__(self, train_data_gen, val_data_gen, deep_supervision, # batch_size=32, early_stopping=True, verbose=2): # def calc_metrics(self, data_gen, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def __init__(self, train_data, val_data, target_repl, batch_size=32, early_stopping=True, verbose=2): # def calc_metrics(self, data, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def __init__(self, train_data_gen, val_data_gen, batch_size=32, # early_stopping=True, verbose=2): # def calc_metrics(self, data_gen, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def __init__(self, train_data_gen, val_data_gen, partition, batch_size=32, # early_stopping=True, verbose=2): # def calc_metrics(self, data_gen, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def __init__(self, train_data_gen, val_data_gen, partition, # batch_size=32, early_stopping=True, verbose=2): # def calc_metrics(self, data_gen, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def softmax(x, axis, mask=None): # def _collect_attention(x, a, mask): # def __init__(self, **kwargs): # def call(self, inputs, mask=None): # def compute_output_shape(self, input_shape): # def compute_mask(self, input, input_mask=None): # def __init__(self, indices, **kwargs): # def call(self, x, mask=None): # def compute_output_shape(self, input_shape): # def compute_mask(self, input, input_mask=None): # def get_config(self): # def __init__(self, pos=-1, **kwargs): # def call(self, x, mask=None): # def compute_output_shape(self, input_shape): # def compute_mask(self, input, input_mask=None): # def get_config(self): # def __init__(self, add_epsilon=False, **kwargs): # def call(self, x, mask=None): # def compute_output_shape(self, input_shape): # def compute_mask(self, input, input_mask=None): # def get_config(self): # B = self.batch_size # # Path: mimic3models/keras_utils.py # class ExtendMask(Layer): # """ Inputs: [X, M] # Output: X # Output_mask: M # """ # # def __init__(self, add_epsilon=False, **kwargs): # self.supports_masking = True # self.add_epsilon = add_epsilon # super(ExtendMask, self).__init__(**kwargs) # # def call(self, x, mask=None): # return x[0] # # def compute_output_shape(self, input_shape): # return input_shape[0] # # def compute_mask(self, input, input_mask=None): # if self.add_epsilon: # return input[1] + K.epsilon() # return input[1] # # def get_config(self): # return {'add_epsilon': self.add_epsilon} . Output only the next line.
y = TimeDistributed(Dense(num_classes, activation=final_activation),
Continue the code snippet: <|code_start|>from __future__ import absolute_import from __future__ import print_function def load_data(reader, discretizer, normalizer, small_part=False, return_names=False): N = reader.get_number_of_examples() if small_part: N = 1000 ret = common_utils.read_chunk(reader, N) data = ret["X"] ts = ret["t"] labels = ret["y"] names = ret["name"] data = [discretizer.transform(X, end=t)[0] for (X, t) in zip(data, ts)] if normalizer is not None: data = [normalizer.transform(X) for X in data] whole_data = (np.array(data), labels) if not return_names: return whole_data return {"data": whole_data, "names": names} def save_results(names, pred, y_true, path): common_utils.create_directory(os.path.dirname(path)) with open(path, 'w') as f: f.write("stay,prediction,y_true\n") for (name, x, y) in zip(names, pred, y_true): <|code_end|> . Use current file imports: from mimic3models import common_utils import numpy as np import os and context (classes, functions, or code) from other files: # Path: mimic3models/common_utils.py # def convert_to_dict(data, header, channel_info): # def extract_features_from_rawdata(chunk, header, period, features): # def read_chunk(reader, chunk_size): # def sort_and_shuffle(data, batch_size): # def add_common_arguments(parser): # def __init__(self, dataset_dir, listfile=None, small_part=False): # def _read_timeseries(self, ts_filename): # def create_directory(directory): # def pad_zeros(arr, min_length=None): # class DeepSupervisionDataLoader: . Output only the next line.
f.write("{},{:.6f},{}\n".format(name, x, y))
Next line prediction: <|code_start|> command += ' --ihm_C {}'.format(ihm_C) if decomp_C: command += ' --decomp_C {}'.format(decomp_C) if los_C: command += ' --los_C {}'.format(los_C) if pheno_C: command += ' --pheno_C {}'.format(pheno_C) if dropout > 0.0: command += ' --dropout {}'.format(dropout) if partition: command += ' --partition {}'.format(partition) if deep_supervision: command += ' --deep_supervision' if (target_repl_coef is not None) and target_repl_coef > 0.0: command += ' --target_repl_coef {}'.format(target_repl_coef) return {"command": command, "train_max": np.max(train_metrics), "train_max_pos": np.argmax(train_metrics), "val_max": np.max(val_metrics), "val_max_pos": np.argmax(val_metrics), "last_train": last_train, "last_val": last_val, <|code_end|> . Use current file imports: (import argparse import json import numpy as np from mimic3models import parse_utils) and context including class names, function names, or small code snippets from other files: # Path: mimic3models/parse_utils.py # def parse_task(log): # def get_loss(log, loss_name): # def parse_metrics(log, metric): # def parse_network(log): # def parse_load_state(log): # def parse_prefix(log): # def parse_dim(log): # def parse_size_coef(log): # def parse_depth(log): # def parse_ihm_C(log): # def parse_decomp_C(log): # def parse_los_C(log): # def parse_pheno_C(log): # def parse_dropout(log): # def parse_timestep(log): # def parse_partition(log): # def parse_deep_supervision(log): # def parse_target_repl_coef(log): # def parse_epoch(state): # def parse_batch_size(log): # def parse_state(log, epoch): # def parse_last_state(log): . Output only the next line.
"n_epochs": n_epochs,
Given the code snippet: <|code_start|>from __future__ import absolute_import from __future__ import print_function class Network(Model): def __init__(self, dim, batch_norm, dropout, rec_dropout, partition, ihm_pos, target_repl=False, depth=1, input_dim=76, **kwargs): print("==> not used params in network class:", kwargs.keys()) self.dim = dim self.batch_norm = batch_norm <|code_end|> , generate the next line using the imports in this file: from keras.models import Model from keras.layers import Input, Dense, LSTM, Masking, Dropout from keras.layers.wrappers import TimeDistributed from mimic3models.keras_utils import ExtendMask, GetTimestep, LastTimestep from keras.layers.merge import Multiply and context (functions, classes, or occasionally code) from other files: # Path: mimic3models/keras_utils.py # class DecompensationMetrics(keras.callbacks.Callback): # class InHospitalMortalityMetrics(keras.callbacks.Callback): # class PhenotypingMetrics(keras.callbacks.Callback): # class LengthOfStayMetrics(keras.callbacks.Callback): # class MultitaskMetrics(keras.callbacks.Callback): # class CollectAttetion(Layer): # class Slice(Layer): # class GetTimestep(Layer): # class ExtendMask(Layer): # def __init__(self, train_data_gen, val_data_gen, deep_supervision, # batch_size=32, early_stopping=True, verbose=2): # def calc_metrics(self, data_gen, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def __init__(self, train_data, val_data, target_repl, batch_size=32, early_stopping=True, verbose=2): # def calc_metrics(self, data, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def __init__(self, train_data_gen, val_data_gen, batch_size=32, # early_stopping=True, verbose=2): # def calc_metrics(self, data_gen, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def __init__(self, train_data_gen, val_data_gen, partition, batch_size=32, # early_stopping=True, verbose=2): # def calc_metrics(self, data_gen, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def __init__(self, train_data_gen, val_data_gen, partition, # batch_size=32, early_stopping=True, verbose=2): # def calc_metrics(self, data_gen, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def softmax(x, axis, mask=None): # def _collect_attention(x, a, mask): # def __init__(self, **kwargs): # def call(self, inputs, mask=None): # def compute_output_shape(self, input_shape): # def compute_mask(self, input, input_mask=None): # def __init__(self, indices, **kwargs): # def call(self, x, mask=None): # def compute_output_shape(self, input_shape): # def compute_mask(self, input, input_mask=None): # def get_config(self): # def __init__(self, pos=-1, **kwargs): # def call(self, x, mask=None): # def compute_output_shape(self, input_shape): # def compute_mask(self, input, input_mask=None): # def get_config(self): # def __init__(self, add_epsilon=False, **kwargs): # def call(self, x, mask=None): # def compute_output_shape(self, input_shape): # def compute_mask(self, input, input_mask=None): # def get_config(self): # B = self.batch_size . Output only the next line.
self.dropout = dropout
Given the following code snippet before the placeholder: <|code_start|> ihm_y = GetTimestep(ihm_pos)(ihm_seq) ihm_y = Multiply(name='ihm_single')([ihm_y, ihm_M]) outputs += [ihm_y, ihm_seq] else: ihm_seq = TimeDistributed(Dense(1, activation='sigmoid'))(L) ihm_y = GetTimestep(ihm_pos)(ihm_seq) ihm_y = Multiply(name='ihm')([ihm_y, ihm_M]) outputs += [ihm_y] # decomp output decomp_y = TimeDistributed(Dense(1, activation='sigmoid'))(L) decomp_y = ExtendMask(name='decomp', add_epsilon=True)([decomp_y, decomp_M]) outputs += [decomp_y] # los output if partition == 'none': los_y = TimeDistributed(Dense(1, activation='relu'))(L) else: los_y = TimeDistributed(Dense(10, activation='softmax'))(L) los_y = ExtendMask(name='los', add_epsilon=True)([los_y, los_M]) outputs += [los_y] # pheno output if target_repl: pheno_seq = TimeDistributed(Dense(25, activation='sigmoid'), name='pheno_seq')(L) pheno_y = LastTimestep(name='pheno_single')(pheno_seq) outputs += [pheno_y, pheno_seq] else: pheno_seq = TimeDistributed(Dense(25, activation='sigmoid'))(L) pheno_y = LastTimestep(name='pheno')(pheno_seq) <|code_end|> , predict the next line using imports from the current file: from keras.models import Model from keras.layers import Input, Dense, LSTM, Masking, Dropout from keras.layers.wrappers import TimeDistributed from mimic3models.keras_utils import ExtendMask, GetTimestep, LastTimestep from keras.layers.merge import Multiply and context including class names, function names, and sometimes code from other files: # Path: mimic3models/keras_utils.py # class DecompensationMetrics(keras.callbacks.Callback): # class InHospitalMortalityMetrics(keras.callbacks.Callback): # class PhenotypingMetrics(keras.callbacks.Callback): # class LengthOfStayMetrics(keras.callbacks.Callback): # class MultitaskMetrics(keras.callbacks.Callback): # class CollectAttetion(Layer): # class Slice(Layer): # class GetTimestep(Layer): # class ExtendMask(Layer): # def __init__(self, train_data_gen, val_data_gen, deep_supervision, # batch_size=32, early_stopping=True, verbose=2): # def calc_metrics(self, data_gen, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def __init__(self, train_data, val_data, target_repl, batch_size=32, early_stopping=True, verbose=2): # def calc_metrics(self, data, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def __init__(self, train_data_gen, val_data_gen, batch_size=32, # early_stopping=True, verbose=2): # def calc_metrics(self, data_gen, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def __init__(self, train_data_gen, val_data_gen, partition, batch_size=32, # early_stopping=True, verbose=2): # def calc_metrics(self, data_gen, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def __init__(self, train_data_gen, val_data_gen, partition, # batch_size=32, early_stopping=True, verbose=2): # def calc_metrics(self, data_gen, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def softmax(x, axis, mask=None): # def _collect_attention(x, a, mask): # def __init__(self, **kwargs): # def call(self, inputs, mask=None): # def compute_output_shape(self, input_shape): # def compute_mask(self, input, input_mask=None): # def __init__(self, indices, **kwargs): # def call(self, x, mask=None): # def compute_output_shape(self, input_shape): # def compute_mask(self, input, input_mask=None): # def get_config(self): # def __init__(self, pos=-1, **kwargs): # def call(self, x, mask=None): # def compute_output_shape(self, input_shape): # def compute_mask(self, input, input_mask=None): # def get_config(self): # def __init__(self, add_epsilon=False, **kwargs): # def call(self, x, mask=None): # def compute_output_shape(self, input_shape): # def compute_mask(self, input, input_mask=None): # def get_config(self): # B = self.batch_size . Output only the next line.
outputs += [pheno_y]
Here is a snippet: <|code_start|> # decomp output decomp_y = TimeDistributed(Dense(1, activation='sigmoid'))(L) decomp_y = ExtendMask(name='decomp', add_epsilon=True)([decomp_y, decomp_M]) outputs += [decomp_y] # los output if partition == 'none': los_y = TimeDistributed(Dense(1, activation='relu'))(L) else: los_y = TimeDistributed(Dense(10, activation='softmax'))(L) los_y = ExtendMask(name='los', add_epsilon=True)([los_y, los_M]) outputs += [los_y] # pheno output if target_repl: pheno_seq = TimeDistributed(Dense(25, activation='sigmoid'), name='pheno_seq')(L) pheno_y = LastTimestep(name='pheno_single')(pheno_seq) outputs += [pheno_y, pheno_seq] else: pheno_seq = TimeDistributed(Dense(25, activation='sigmoid'))(L) pheno_y = LastTimestep(name='pheno')(pheno_seq) outputs += [pheno_y] super(Network, self).__init__(inputs=inputs, outputs=outputs) def say_name(self): return "{}.n{}{}{}{}.dep{}".format('k_lstm', self.dim, ".bn" if self.batch_norm else "", <|code_end|> . Write the next line using the current file imports: from keras.models import Model from keras.layers import Input, Dense, LSTM, Masking, Dropout from keras.layers.wrappers import TimeDistributed from mimic3models.keras_utils import ExtendMask, GetTimestep, LastTimestep from keras.layers.merge import Multiply and context from other files: # Path: mimic3models/keras_utils.py # class DecompensationMetrics(keras.callbacks.Callback): # class InHospitalMortalityMetrics(keras.callbacks.Callback): # class PhenotypingMetrics(keras.callbacks.Callback): # class LengthOfStayMetrics(keras.callbacks.Callback): # class MultitaskMetrics(keras.callbacks.Callback): # class CollectAttetion(Layer): # class Slice(Layer): # class GetTimestep(Layer): # class ExtendMask(Layer): # def __init__(self, train_data_gen, val_data_gen, deep_supervision, # batch_size=32, early_stopping=True, verbose=2): # def calc_metrics(self, data_gen, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def __init__(self, train_data, val_data, target_repl, batch_size=32, early_stopping=True, verbose=2): # def calc_metrics(self, data, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def __init__(self, train_data_gen, val_data_gen, batch_size=32, # early_stopping=True, verbose=2): # def calc_metrics(self, data_gen, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def __init__(self, train_data_gen, val_data_gen, partition, batch_size=32, # early_stopping=True, verbose=2): # def calc_metrics(self, data_gen, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def __init__(self, train_data_gen, val_data_gen, partition, # batch_size=32, early_stopping=True, verbose=2): # def calc_metrics(self, data_gen, history, dataset, logs): # def on_epoch_end(self, epoch, logs={}): # def softmax(x, axis, mask=None): # def _collect_attention(x, a, mask): # def __init__(self, **kwargs): # def call(self, inputs, mask=None): # def compute_output_shape(self, input_shape): # def compute_mask(self, input, input_mask=None): # def __init__(self, indices, **kwargs): # def call(self, x, mask=None): # def compute_output_shape(self, input_shape): # def compute_mask(self, input, input_mask=None): # def get_config(self): # def __init__(self, pos=-1, **kwargs): # def call(self, x, mask=None): # def compute_output_shape(self, input_shape): # def compute_mask(self, input, input_mask=None): # def get_config(self): # def __init__(self, add_epsilon=False, **kwargs): # def call(self, x, mask=None): # def compute_output_shape(self, input_shape): # def compute_mask(self, input, input_mask=None): # def get_config(self): # B = self.batch_size , which may include functions, classes, or code. Output only the next line.
".d{}".format(self.dropout) if self.dropout > 0 else "",
Given the code snippet: <|code_start|> logger = logging.getLogger('timeline_logger') DEFAULT_TEMPLATE = settings.TIMELINE_DEFAULT_TEMPLATE @python_2_unicode_compatible class TimelineLog(models.Model): <|code_end|> , generate the next line using the imports in this file: import logging from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.contrib.postgres.fields import JSONField from django.db import models from django.template.loader import get_template, render_to_string from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext, ugettext_lazy as _ from .conf import settings and context (functions, classes, or occasionally code) from other files: # Path: timeline_logger/conf.py # class TimelineLoggerConf(AppConf): # class Meta: # DEFAULT_TEMPLATE = 'timeline_logger/default.txt' # PAGINATE_BY = 25 # USER_EMAIL_FIELD = 'email' # DIGEST_EMAIL_RECIPIENTS = None # DIGEST_EMAIL_SUBJECT = _('Events timeline') # DIGEST_FROM_EMAIL = None # def configure_digest_email_recipients(self, value): # def configure_digest_from_email(self, value): . Output only the next line.
content_type = models.ForeignKey(
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- class TimelineLogTestCase(TestCase): def setUp(self): self.article = ArticleFactory.create() self.user = User.objects.create(username='john_doe', email='john.doe@maykinmedia.nl') self.timeline_log = TimelineLog.objects.create( content_object=self.article, user=self.user, ) self.request = RequestFactory().get('/my_object/') <|code_end|> , predict the next line using imports from the current file: from unittest import skipIf from django.conf import settings from django.contrib.auth.models import User from django.template.defaultfilters import date from django.template.exceptions import TemplateDoesNotExist from django.test import RequestFactory, TestCase from timeline_logger.models import TimelineLog from .factories import ArticleFactory and context including class names, function names, and sometimes code from other files: # Path: timeline_logger/models.py # class TimelineLog(models.Model): # content_type = models.ForeignKey( # ContentType, # verbose_name=_('content type'), # on_delete=models.SET_NULL, # blank=True, null=True, # ) # object_id = models.TextField( # verbose_name=_('object id'), # blank=True, null=True # ) # content_object = GenericForeignKey('content_type', 'object_id') # timestamp = models.DateTimeField(verbose_name=_('timestamp'), auto_now_add=True) # extra_data = JSONField( # verbose_name=_('extra data'), # null=True, blank=True, # ) # user = models.ForeignKey( # settings.AUTH_USER_MODEL, # verbose_name=_('user'), # on_delete=models.SET_NULL, # blank=True, null=True, # ) # template = models.CharField(max_length=200, default=DEFAULT_TEMPLATE) # # class Meta: # verbose_name = _('timeline log entry') # verbose_name_plural = _('timeline log entries') # # def __str__(self): # if self.object_id: # return "{ct} - {pk}".format( # ct=self.content_type.name, # pk=self.object_id # ) # # return ugettext('TimelineLog Object') # # @classmethod # def log_from_request(cls, request, content_object, template=None, **extra_data): # """ # Given an ``HTTPRequest`` object and a generic content, it creates a # ``TimelineLog`` object to store the data of that request. # # :param request: A Django ``HTTPRequest`` object. # :param content_object: A Django model instance. Any object can be # related. # :param template: String representing the template to be used to render # the message. Defaults to 'default.txt'. # :param extra_data: A dictionary (translatable into JSON) determining # specifications of the action performed. # :return: A newly created ``TimelineLog`` instance. # """ # try: # user = request.user # except AttributeError: # user = None # # if template is not None: # # Ensure that the expected template actually exists. # get_template(template) # # timeline_log = cls.objects.create( # content_object=content_object, # extra_data=extra_data or None, # template=template or DEFAULT_TEMPLATE, # user=user, # ) # logger.debug('Logged event in %s %s', content_object._meta.object_name, content_object.pk) # return timeline_log # # def get_message(self, template=None, **extra_context): # """ # Gets the 'log' message, describing the event performed. # # :param template: String representing the template to be used to render # the message. Defaults to ``self.template``. # :return: The log message string. # """ # context = {'log': self} # context.update(**extra_context) # return render_to_string(template or self.template, context) # # Path: tests/factories.py # class ArticleFactory(factory.django.DjangoModelFactory): # # class Meta: # model = 'tests.Article' # # title = factory.Faker('sentence') # date = factory.Faker('date') . Output only the next line.
def test_log_from_request_no_user(self):
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- class TimelineLogTestCase(TestCase): def setUp(self): self.article = ArticleFactory.create() self.user = User.objects.create(username='john_doe', email='john.doe@maykinmedia.nl') self.timeline_log = TimelineLog.objects.create( content_object=self.article, <|code_end|> . Write the next line using the current file imports: from unittest import skipIf from django.conf import settings from django.contrib.auth.models import User from django.template.defaultfilters import date from django.template.exceptions import TemplateDoesNotExist from django.test import RequestFactory, TestCase from timeline_logger.models import TimelineLog from .factories import ArticleFactory and context from other files: # Path: timeline_logger/models.py # class TimelineLog(models.Model): # content_type = models.ForeignKey( # ContentType, # verbose_name=_('content type'), # on_delete=models.SET_NULL, # blank=True, null=True, # ) # object_id = models.TextField( # verbose_name=_('object id'), # blank=True, null=True # ) # content_object = GenericForeignKey('content_type', 'object_id') # timestamp = models.DateTimeField(verbose_name=_('timestamp'), auto_now_add=True) # extra_data = JSONField( # verbose_name=_('extra data'), # null=True, blank=True, # ) # user = models.ForeignKey( # settings.AUTH_USER_MODEL, # verbose_name=_('user'), # on_delete=models.SET_NULL, # blank=True, null=True, # ) # template = models.CharField(max_length=200, default=DEFAULT_TEMPLATE) # # class Meta: # verbose_name = _('timeline log entry') # verbose_name_plural = _('timeline log entries') # # def __str__(self): # if self.object_id: # return "{ct} - {pk}".format( # ct=self.content_type.name, # pk=self.object_id # ) # # return ugettext('TimelineLog Object') # # @classmethod # def log_from_request(cls, request, content_object, template=None, **extra_data): # """ # Given an ``HTTPRequest`` object and a generic content, it creates a # ``TimelineLog`` object to store the data of that request. # # :param request: A Django ``HTTPRequest`` object. # :param content_object: A Django model instance. Any object can be # related. # :param template: String representing the template to be used to render # the message. Defaults to 'default.txt'. # :param extra_data: A dictionary (translatable into JSON) determining # specifications of the action performed. # :return: A newly created ``TimelineLog`` instance. # """ # try: # user = request.user # except AttributeError: # user = None # # if template is not None: # # Ensure that the expected template actually exists. # get_template(template) # # timeline_log = cls.objects.create( # content_object=content_object, # extra_data=extra_data or None, # template=template or DEFAULT_TEMPLATE, # user=user, # ) # logger.debug('Logged event in %s %s', content_object._meta.object_name, content_object.pk) # return timeline_log # # def get_message(self, template=None, **extra_context): # """ # Gets the 'log' message, describing the event performed. # # :param template: String representing the template to be used to render # the message. Defaults to ``self.template``. # :return: The log message string. # """ # context = {'log': self} # context.update(**extra_context) # return render_to_string(template or self.template, context) # # Path: tests/factories.py # class ArticleFactory(factory.django.DjangoModelFactory): # # class Meta: # model = 'tests.Article' # # title = factory.Faker('sentence') # date = factory.Faker('date') , which may include functions, classes, or code. Output only the next line.
user=self.user,
Here is a snippet: <|code_start|> app_name = 'timeline' urlpatterns = [ url(r'^$', TimelineLogListView.as_view(), name='timeline'), <|code_end|> . Write the next line using the current file imports: from django.conf.urls import url from .views import TimelineLogListView and context from other files: # Path: timeline_logger/views.py # class TimelineLogListView(ListView): # queryset = TimelineLog.objects.order_by('-timestamp') # paginate_by = settings.TIMELINE_PAGINATE_BY , which may include functions, classes, or code. Output only the next line.
]
Based on the snippet: <|code_start|> admin.site.unregister(TimelineLog) @admin.register(TimelineLog) class TimelineLogAdmin(ExportMixin, TimelineLogAdmin): <|code_end|> , predict the immediate next line with the help of imports: from django.contrib import admin from import_export.admin import ExportMixin from import_export.formats import base_formats from import_export_xml.formats import XML from timeline_logger.models import TimelineLog from timeline_logger.admin import TimelineLogAdmin from timeline_logger.resources import TimelineLogResource and context (classes, functions, sometimes code) from other files: # Path: timeline_logger/models.py # class TimelineLog(models.Model): # content_type = models.ForeignKey( # ContentType, # verbose_name=_('content type'), # on_delete=models.SET_NULL, # blank=True, null=True, # ) # object_id = models.TextField( # verbose_name=_('object id'), # blank=True, null=True # ) # content_object = GenericForeignKey('content_type', 'object_id') # timestamp = models.DateTimeField(verbose_name=_('timestamp'), auto_now_add=True) # extra_data = JSONField( # verbose_name=_('extra data'), # null=True, blank=True, # ) # user = models.ForeignKey( # settings.AUTH_USER_MODEL, # verbose_name=_('user'), # on_delete=models.SET_NULL, # blank=True, null=True, # ) # template = models.CharField(max_length=200, default=DEFAULT_TEMPLATE) # # class Meta: # verbose_name = _('timeline log entry') # verbose_name_plural = _('timeline log entries') # # def __str__(self): # if self.object_id: # return "{ct} - {pk}".format( # ct=self.content_type.name, # pk=self.object_id # ) # # return ugettext('TimelineLog Object') # # @classmethod # def log_from_request(cls, request, content_object, template=None, **extra_data): # """ # Given an ``HTTPRequest`` object and a generic content, it creates a # ``TimelineLog`` object to store the data of that request. # # :param request: A Django ``HTTPRequest`` object. # :param content_object: A Django model instance. Any object can be # related. # :param template: String representing the template to be used to render # the message. Defaults to 'default.txt'. # :param extra_data: A dictionary (translatable into JSON) determining # specifications of the action performed. # :return: A newly created ``TimelineLog`` instance. # """ # try: # user = request.user # except AttributeError: # user = None # # if template is not None: # # Ensure that the expected template actually exists. # get_template(template) # # timeline_log = cls.objects.create( # content_object=content_object, # extra_data=extra_data or None, # template=template or DEFAULT_TEMPLATE, # user=user, # ) # logger.debug('Logged event in %s %s', content_object._meta.object_name, content_object.pk) # return timeline_log # # def get_message(self, template=None, **extra_context): # """ # Gets the 'log' message, describing the event performed. # # :param template: String representing the template to be used to render # the message. Defaults to ``self.template``. # :return: The log message string. # """ # context = {'log': self} # context.update(**extra_context) # return render_to_string(template or self.template, context) # # Path: timeline_logger/admin.py # class TimelineLogAdmin(admin.ModelAdmin): # list_display = ['__str__', 'timestamp', 'template'] # list_filter = ['timestamp', 'content_type'] # list_select_related = ['content_type'] # # Path: timeline_logger/resources.py # class TimelineLogResource(ModelResource): # extra_data = Field( # attribute='extra_data', # column_name='extra_data', # widget=JSONWidget(), # default=None # ) # # class Meta: # model = TimelineLog . Output only the next line.
formats = (
Continue the code snippet: <|code_start|> admin.site.unregister(TimelineLog) @admin.register(TimelineLog) class TimelineLogAdmin(ExportMixin, TimelineLogAdmin): formats = ( XML, base_formats.CSV, <|code_end|> . Use current file imports: from django.contrib import admin from import_export.admin import ExportMixin from import_export.formats import base_formats from import_export_xml.formats import XML from timeline_logger.models import TimelineLog from timeline_logger.admin import TimelineLogAdmin from timeline_logger.resources import TimelineLogResource and context (classes, functions, or code) from other files: # Path: timeline_logger/models.py # class TimelineLog(models.Model): # content_type = models.ForeignKey( # ContentType, # verbose_name=_('content type'), # on_delete=models.SET_NULL, # blank=True, null=True, # ) # object_id = models.TextField( # verbose_name=_('object id'), # blank=True, null=True # ) # content_object = GenericForeignKey('content_type', 'object_id') # timestamp = models.DateTimeField(verbose_name=_('timestamp'), auto_now_add=True) # extra_data = JSONField( # verbose_name=_('extra data'), # null=True, blank=True, # ) # user = models.ForeignKey( # settings.AUTH_USER_MODEL, # verbose_name=_('user'), # on_delete=models.SET_NULL, # blank=True, null=True, # ) # template = models.CharField(max_length=200, default=DEFAULT_TEMPLATE) # # class Meta: # verbose_name = _('timeline log entry') # verbose_name_plural = _('timeline log entries') # # def __str__(self): # if self.object_id: # return "{ct} - {pk}".format( # ct=self.content_type.name, # pk=self.object_id # ) # # return ugettext('TimelineLog Object') # # @classmethod # def log_from_request(cls, request, content_object, template=None, **extra_data): # """ # Given an ``HTTPRequest`` object and a generic content, it creates a # ``TimelineLog`` object to store the data of that request. # # :param request: A Django ``HTTPRequest`` object. # :param content_object: A Django model instance. Any object can be # related. # :param template: String representing the template to be used to render # the message. Defaults to 'default.txt'. # :param extra_data: A dictionary (translatable into JSON) determining # specifications of the action performed. # :return: A newly created ``TimelineLog`` instance. # """ # try: # user = request.user # except AttributeError: # user = None # # if template is not None: # # Ensure that the expected template actually exists. # get_template(template) # # timeline_log = cls.objects.create( # content_object=content_object, # extra_data=extra_data or None, # template=template or DEFAULT_TEMPLATE, # user=user, # ) # logger.debug('Logged event in %s %s', content_object._meta.object_name, content_object.pk) # return timeline_log # # def get_message(self, template=None, **extra_context): # """ # Gets the 'log' message, describing the event performed. # # :param template: String representing the template to be used to render # the message. Defaults to ``self.template``. # :return: The log message string. # """ # context = {'log': self} # context.update(**extra_context) # return render_to_string(template or self.template, context) # # Path: timeline_logger/admin.py # class TimelineLogAdmin(admin.ModelAdmin): # list_display = ['__str__', 'timestamp', 'template'] # list_filter = ['timestamp', 'content_type'] # list_select_related = ['content_type'] # # Path: timeline_logger/resources.py # class TimelineLogResource(ModelResource): # extra_data = Field( # attribute='extra_data', # column_name='extra_data', # widget=JSONWidget(), # default=None # ) # # class Meta: # model = TimelineLog . Output only the next line.
base_formats.XLS,
Using the snippet: <|code_start|> admin.site.unregister(TimelineLog) @admin.register(TimelineLog) class TimelineLogAdmin(ExportMixin, TimelineLogAdmin): formats = ( <|code_end|> , determine the next line of code. You have imports: from django.contrib import admin from import_export.admin import ExportMixin from import_export.formats import base_formats from import_export_xml.formats import XML from timeline_logger.models import TimelineLog from timeline_logger.admin import TimelineLogAdmin from timeline_logger.resources import TimelineLogResource and context (class names, function names, or code) available: # Path: timeline_logger/models.py # class TimelineLog(models.Model): # content_type = models.ForeignKey( # ContentType, # verbose_name=_('content type'), # on_delete=models.SET_NULL, # blank=True, null=True, # ) # object_id = models.TextField( # verbose_name=_('object id'), # blank=True, null=True # ) # content_object = GenericForeignKey('content_type', 'object_id') # timestamp = models.DateTimeField(verbose_name=_('timestamp'), auto_now_add=True) # extra_data = JSONField( # verbose_name=_('extra data'), # null=True, blank=True, # ) # user = models.ForeignKey( # settings.AUTH_USER_MODEL, # verbose_name=_('user'), # on_delete=models.SET_NULL, # blank=True, null=True, # ) # template = models.CharField(max_length=200, default=DEFAULT_TEMPLATE) # # class Meta: # verbose_name = _('timeline log entry') # verbose_name_plural = _('timeline log entries') # # def __str__(self): # if self.object_id: # return "{ct} - {pk}".format( # ct=self.content_type.name, # pk=self.object_id # ) # # return ugettext('TimelineLog Object') # # @classmethod # def log_from_request(cls, request, content_object, template=None, **extra_data): # """ # Given an ``HTTPRequest`` object and a generic content, it creates a # ``TimelineLog`` object to store the data of that request. # # :param request: A Django ``HTTPRequest`` object. # :param content_object: A Django model instance. Any object can be # related. # :param template: String representing the template to be used to render # the message. Defaults to 'default.txt'. # :param extra_data: A dictionary (translatable into JSON) determining # specifications of the action performed. # :return: A newly created ``TimelineLog`` instance. # """ # try: # user = request.user # except AttributeError: # user = None # # if template is not None: # # Ensure that the expected template actually exists. # get_template(template) # # timeline_log = cls.objects.create( # content_object=content_object, # extra_data=extra_data or None, # template=template or DEFAULT_TEMPLATE, # user=user, # ) # logger.debug('Logged event in %s %s', content_object._meta.object_name, content_object.pk) # return timeline_log # # def get_message(self, template=None, **extra_context): # """ # Gets the 'log' message, describing the event performed. # # :param template: String representing the template to be used to render # the message. Defaults to ``self.template``. # :return: The log message string. # """ # context = {'log': self} # context.update(**extra_context) # return render_to_string(template or self.template, context) # # Path: timeline_logger/admin.py # class TimelineLogAdmin(admin.ModelAdmin): # list_display = ['__str__', 'timestamp', 'template'] # list_filter = ['timestamp', 'content_type'] # list_select_related = ['content_type'] # # Path: timeline_logger/resources.py # class TimelineLogResource(ModelResource): # extra_data = Field( # attribute='extra_data', # column_name='extra_data', # widget=JSONWidget(), # default=None # ) # # class Meta: # model = TimelineLog . Output only the next line.
XML,
Here is a snippet: <|code_start|> class JSONWidget(Widget): def render(self, value, obj=None): return value <|code_end|> . Write the next line using the current file imports: from import_export.resources import ModelResource from import_export.fields import Field from import_export.widgets import Widget from .models import TimelineLog and context from other files: # Path: timeline_logger/models.py # class TimelineLog(models.Model): # content_type = models.ForeignKey( # ContentType, # verbose_name=_('content type'), # on_delete=models.SET_NULL, # blank=True, null=True, # ) # object_id = models.TextField( # verbose_name=_('object id'), # blank=True, null=True # ) # content_object = GenericForeignKey('content_type', 'object_id') # timestamp = models.DateTimeField(verbose_name=_('timestamp'), auto_now_add=True) # extra_data = JSONField( # verbose_name=_('extra data'), # null=True, blank=True, # ) # user = models.ForeignKey( # settings.AUTH_USER_MODEL, # verbose_name=_('user'), # on_delete=models.SET_NULL, # blank=True, null=True, # ) # template = models.CharField(max_length=200, default=DEFAULT_TEMPLATE) # # class Meta: # verbose_name = _('timeline log entry') # verbose_name_plural = _('timeline log entries') # # def __str__(self): # if self.object_id: # return "{ct} - {pk}".format( # ct=self.content_type.name, # pk=self.object_id # ) # # return ugettext('TimelineLog Object') # # @classmethod # def log_from_request(cls, request, content_object, template=None, **extra_data): # """ # Given an ``HTTPRequest`` object and a generic content, it creates a # ``TimelineLog`` object to store the data of that request. # # :param request: A Django ``HTTPRequest`` object. # :param content_object: A Django model instance. Any object can be # related. # :param template: String representing the template to be used to render # the message. Defaults to 'default.txt'. # :param extra_data: A dictionary (translatable into JSON) determining # specifications of the action performed. # :return: A newly created ``TimelineLog`` instance. # """ # try: # user = request.user # except AttributeError: # user = None # # if template is not None: # # Ensure that the expected template actually exists. # get_template(template) # # timeline_log = cls.objects.create( # content_object=content_object, # extra_data=extra_data or None, # template=template or DEFAULT_TEMPLATE, # user=user, # ) # logger.debug('Logged event in %s %s', content_object._meta.object_name, content_object.pk) # return timeline_log # # def get_message(self, template=None, **extra_context): # """ # Gets the 'log' message, describing the event performed. # # :param template: String representing the template to be used to render # the message. Defaults to ``self.template``. # :return: The log message string. # """ # context = {'log': self} # context.update(**extra_context) # return render_to_string(template or self.template, context) , which may include functions, classes, or code. Output only the next line.
class TimelineLogResource(ModelResource):
Given the following code snippet before the placeholder: <|code_start|> logger = logging.getLogger('timeline_logger') class Command(BaseCommand): help = 'Sends mail notifications for last events to (admin) users.' template_name = 'timeline_logger/notifications.html' def add_arguments(self, parser): parser.add_argument( '--days', type=int, help='An integer number with the number of days to look at from today to the past.' ) recipients_group = parser.add_mutually_exclusive_group() recipients_group.add_argument('--all', action='store_true', help=_('Send e-mail to all users')) recipients_group.add_argument('--staff', action='store_true', help=_('Send e-mail to staff users')) <|code_end|> , predict the next line using imports from the current file: import logging from datetime import timedelta from django.conf import settings from django.contrib.auth import get_user_model from django.core.mail import send_mail from django.core.management.base import BaseCommand, CommandError from django.template.loader import render_to_string from django.utils import timezone from django.utils.html import strip_tags from django.utils.translation import ugettext_lazy as _ from timeline_logger.compat import html from timeline_logger.models import TimelineLog and context including class names, function names, and sometimes code from other files: # Path: timeline_logger/compat.py # # Path: timeline_logger/models.py # class TimelineLog(models.Model): # content_type = models.ForeignKey( # ContentType, # verbose_name=_('content type'), # on_delete=models.SET_NULL, # blank=True, null=True, # ) # object_id = models.TextField( # verbose_name=_('object id'), # blank=True, null=True # ) # content_object = GenericForeignKey('content_type', 'object_id') # timestamp = models.DateTimeField(verbose_name=_('timestamp'), auto_now_add=True) # extra_data = JSONField( # verbose_name=_('extra data'), # null=True, blank=True, # ) # user = models.ForeignKey( # settings.AUTH_USER_MODEL, # verbose_name=_('user'), # on_delete=models.SET_NULL, # blank=True, null=True, # ) # template = models.CharField(max_length=200, default=DEFAULT_TEMPLATE) # # class Meta: # verbose_name = _('timeline log entry') # verbose_name_plural = _('timeline log entries') # # def __str__(self): # if self.object_id: # return "{ct} - {pk}".format( # ct=self.content_type.name, # pk=self.object_id # ) # # return ugettext('TimelineLog Object') # # @classmethod # def log_from_request(cls, request, content_object, template=None, **extra_data): # """ # Given an ``HTTPRequest`` object and a generic content, it creates a # ``TimelineLog`` object to store the data of that request. # # :param request: A Django ``HTTPRequest`` object. # :param content_object: A Django model instance. Any object can be # related. # :param template: String representing the template to be used to render # the message. Defaults to 'default.txt'. # :param extra_data: A dictionary (translatable into JSON) determining # specifications of the action performed. # :return: A newly created ``TimelineLog`` instance. # """ # try: # user = request.user # except AttributeError: # user = None # # if template is not None: # # Ensure that the expected template actually exists. # get_template(template) # # timeline_log = cls.objects.create( # content_object=content_object, # extra_data=extra_data or None, # template=template or DEFAULT_TEMPLATE, # user=user, # ) # logger.debug('Logged event in %s %s', content_object._meta.object_name, content_object.pk) # return timeline_log # # def get_message(self, template=None, **extra_context): # """ # Gets the 'log' message, describing the event performed. # # :param template: String representing the template to be used to render # the message. Defaults to ``self.template``. # :return: The log message string. # """ # context = {'log': self} # context.update(**extra_context) # return render_to_string(template or self.template, context) . Output only the next line.
recipients_group.add_argument(
Predict the next line after this snippet: <|code_start|> logger = logging.getLogger('timeline_logger') class Command(BaseCommand): help = 'Sends mail notifications for last events to (admin) users.' template_name = 'timeline_logger/notifications.html' def add_arguments(self, parser): parser.add_argument( '--days', type=int, help='An integer number with the number of days to look at from today to the past.' <|code_end|> using the current file's imports: import logging from datetime import timedelta from django.conf import settings from django.contrib.auth import get_user_model from django.core.mail import send_mail from django.core.management.base import BaseCommand, CommandError from django.template.loader import render_to_string from django.utils import timezone from django.utils.html import strip_tags from django.utils.translation import ugettext_lazy as _ from timeline_logger.compat import html from timeline_logger.models import TimelineLog and any relevant context from other files: # Path: timeline_logger/compat.py # # Path: timeline_logger/models.py # class TimelineLog(models.Model): # content_type = models.ForeignKey( # ContentType, # verbose_name=_('content type'), # on_delete=models.SET_NULL, # blank=True, null=True, # ) # object_id = models.TextField( # verbose_name=_('object id'), # blank=True, null=True # ) # content_object = GenericForeignKey('content_type', 'object_id') # timestamp = models.DateTimeField(verbose_name=_('timestamp'), auto_now_add=True) # extra_data = JSONField( # verbose_name=_('extra data'), # null=True, blank=True, # ) # user = models.ForeignKey( # settings.AUTH_USER_MODEL, # verbose_name=_('user'), # on_delete=models.SET_NULL, # blank=True, null=True, # ) # template = models.CharField(max_length=200, default=DEFAULT_TEMPLATE) # # class Meta: # verbose_name = _('timeline log entry') # verbose_name_plural = _('timeline log entries') # # def __str__(self): # if self.object_id: # return "{ct} - {pk}".format( # ct=self.content_type.name, # pk=self.object_id # ) # # return ugettext('TimelineLog Object') # # @classmethod # def log_from_request(cls, request, content_object, template=None, **extra_data): # """ # Given an ``HTTPRequest`` object and a generic content, it creates a # ``TimelineLog`` object to store the data of that request. # # :param request: A Django ``HTTPRequest`` object. # :param content_object: A Django model instance. Any object can be # related. # :param template: String representing the template to be used to render # the message. Defaults to 'default.txt'. # :param extra_data: A dictionary (translatable into JSON) determining # specifications of the action performed. # :return: A newly created ``TimelineLog`` instance. # """ # try: # user = request.user # except AttributeError: # user = None # # if template is not None: # # Ensure that the expected template actually exists. # get_template(template) # # timeline_log = cls.objects.create( # content_object=content_object, # extra_data=extra_data or None, # template=template or DEFAULT_TEMPLATE, # user=user, # ) # logger.debug('Logged event in %s %s', content_object._meta.object_name, content_object.pk) # return timeline_log # # def get_message(self, template=None, **extra_context): # """ # Gets the 'log' message, describing the event performed. # # :param template: String representing the template to be used to render # the message. Defaults to ``self.template``. # :return: The log message string. # """ # context = {'log': self} # context.update(**extra_context) # return render_to_string(template or self.template, context) . Output only the next line.
)
Given the code snippet: <|code_start|> @pytest.mark.skipif( settings.DATABASES['default']['ENGINE'] != 'django.db.backends.postgresql', reason='Requires PostgreSQL' ) @pytest.mark.django_db def test_render_message(): log = TimelineLogFactory.create(extra_data={'foo': 'bar'}) with patch.object(log, 'get_message') as mock_get_message: <|code_end|> , generate the next line using the imports in this file: import pytest from django.conf import settings from django.template.loader import render_to_string from .compat import patch from .factories import TimelineLogFactory and context (functions, classes, or occasionally code) from other files: # Path: tests/compat.py # # Path: tests/factories.py # class TimelineLogFactory(factory.django.DjangoModelFactory): # # class Meta: # model = 'timeline_logger.TimelineLog' # # content_object = factory.SubFactory(ArticleFactory) . Output only the next line.
render_to_string('test_render_message', {'log': log})
Here is a snippet: <|code_start|> class ReportMailingTestCase(TestCase): def setUp(self): self.article = ArticleFactory.create() self.user = UserFactory.create(email='jose@maykinmedia.nl') self.staff_user = UserFactory.create(is_staff=True) self.admin_user = UserFactory.create(is_staff=True, is_superuser=True) self.log_1 = TimelineLog.objects.create( content_object=self.article, user=self.user, <|code_end|> . Write the next line using the current file imports: from datetime import timedelta from django.conf import settings from django.core import mail from django.core.management import CommandError, call_command from django.template.defaultfilters import date from django.test import TestCase, override_settings from django.utils import timezone from timeline_logger.models import TimelineLog from .factories import ArticleFactory, UserFactory and context from other files: # Path: timeline_logger/models.py # class TimelineLog(models.Model): # content_type = models.ForeignKey( # ContentType, # verbose_name=_('content type'), # on_delete=models.SET_NULL, # blank=True, null=True, # ) # object_id = models.TextField( # verbose_name=_('object id'), # blank=True, null=True # ) # content_object = GenericForeignKey('content_type', 'object_id') # timestamp = models.DateTimeField(verbose_name=_('timestamp'), auto_now_add=True) # extra_data = JSONField( # verbose_name=_('extra data'), # null=True, blank=True, # ) # user = models.ForeignKey( # settings.AUTH_USER_MODEL, # verbose_name=_('user'), # on_delete=models.SET_NULL, # blank=True, null=True, # ) # template = models.CharField(max_length=200, default=DEFAULT_TEMPLATE) # # class Meta: # verbose_name = _('timeline log entry') # verbose_name_plural = _('timeline log entries') # # def __str__(self): # if self.object_id: # return "{ct} - {pk}".format( # ct=self.content_type.name, # pk=self.object_id # ) # # return ugettext('TimelineLog Object') # # @classmethod # def log_from_request(cls, request, content_object, template=None, **extra_data): # """ # Given an ``HTTPRequest`` object and a generic content, it creates a # ``TimelineLog`` object to store the data of that request. # # :param request: A Django ``HTTPRequest`` object. # :param content_object: A Django model instance. Any object can be # related. # :param template: String representing the template to be used to render # the message. Defaults to 'default.txt'. # :param extra_data: A dictionary (translatable into JSON) determining # specifications of the action performed. # :return: A newly created ``TimelineLog`` instance. # """ # try: # user = request.user # except AttributeError: # user = None # # if template is not None: # # Ensure that the expected template actually exists. # get_template(template) # # timeline_log = cls.objects.create( # content_object=content_object, # extra_data=extra_data or None, # template=template or DEFAULT_TEMPLATE, # user=user, # ) # logger.debug('Logged event in %s %s', content_object._meta.object_name, content_object.pk) # return timeline_log # # def get_message(self, template=None, **extra_context): # """ # Gets the 'log' message, describing the event performed. # # :param template: String representing the template to be used to render # the message. Defaults to ``self.template``. # :return: The log message string. # """ # context = {'log': self} # context.update(**extra_context) # return render_to_string(template or self.template, context) # # Path: tests/factories.py # class ArticleFactory(factory.django.DjangoModelFactory): # # class Meta: # model = 'tests.Article' # # title = factory.Faker('sentence') # date = factory.Faker('date') # # class UserFactory(factory.DjangoModelFactory): # class Meta: # model = 'auth.User' # # first_name = 'Test' # last_name = 'User' # username = factory.Sequence(lambda n: 'user_{0}'.format(n)) # email = factory.Sequence(lambda n: 'user_{0}@maykinmedia.nl'.format(n)) # password = factory.PostGenerationMethodCall('set_password', 'testing') , which may include functions, classes, or code. Output only the next line.
)
Given the following code snippet before the placeholder: <|code_start|> class ReportMailingTestCase(TestCase): def setUp(self): self.article = ArticleFactory.create() self.user = UserFactory.create(email='jose@maykinmedia.nl') self.staff_user = UserFactory.create(is_staff=True) self.admin_user = UserFactory.create(is_staff=True, is_superuser=True) self.log_1 = TimelineLog.objects.create( content_object=self.article, user=self.user, ) self.log_2 = TimelineLog.objects.create( <|code_end|> , predict the next line using imports from the current file: from datetime import timedelta from django.conf import settings from django.core import mail from django.core.management import CommandError, call_command from django.template.defaultfilters import date from django.test import TestCase, override_settings from django.utils import timezone from timeline_logger.models import TimelineLog from .factories import ArticleFactory, UserFactory and context including class names, function names, and sometimes code from other files: # Path: timeline_logger/models.py # class TimelineLog(models.Model): # content_type = models.ForeignKey( # ContentType, # verbose_name=_('content type'), # on_delete=models.SET_NULL, # blank=True, null=True, # ) # object_id = models.TextField( # verbose_name=_('object id'), # blank=True, null=True # ) # content_object = GenericForeignKey('content_type', 'object_id') # timestamp = models.DateTimeField(verbose_name=_('timestamp'), auto_now_add=True) # extra_data = JSONField( # verbose_name=_('extra data'), # null=True, blank=True, # ) # user = models.ForeignKey( # settings.AUTH_USER_MODEL, # verbose_name=_('user'), # on_delete=models.SET_NULL, # blank=True, null=True, # ) # template = models.CharField(max_length=200, default=DEFAULT_TEMPLATE) # # class Meta: # verbose_name = _('timeline log entry') # verbose_name_plural = _('timeline log entries') # # def __str__(self): # if self.object_id: # return "{ct} - {pk}".format( # ct=self.content_type.name, # pk=self.object_id # ) # # return ugettext('TimelineLog Object') # # @classmethod # def log_from_request(cls, request, content_object, template=None, **extra_data): # """ # Given an ``HTTPRequest`` object and a generic content, it creates a # ``TimelineLog`` object to store the data of that request. # # :param request: A Django ``HTTPRequest`` object. # :param content_object: A Django model instance. Any object can be # related. # :param template: String representing the template to be used to render # the message. Defaults to 'default.txt'. # :param extra_data: A dictionary (translatable into JSON) determining # specifications of the action performed. # :return: A newly created ``TimelineLog`` instance. # """ # try: # user = request.user # except AttributeError: # user = None # # if template is not None: # # Ensure that the expected template actually exists. # get_template(template) # # timeline_log = cls.objects.create( # content_object=content_object, # extra_data=extra_data or None, # template=template or DEFAULT_TEMPLATE, # user=user, # ) # logger.debug('Logged event in %s %s', content_object._meta.object_name, content_object.pk) # return timeline_log # # def get_message(self, template=None, **extra_context): # """ # Gets the 'log' message, describing the event performed. # # :param template: String representing the template to be used to render # the message. Defaults to ``self.template``. # :return: The log message string. # """ # context = {'log': self} # context.update(**extra_context) # return render_to_string(template or self.template, context) # # Path: tests/factories.py # class ArticleFactory(factory.django.DjangoModelFactory): # # class Meta: # model = 'tests.Article' # # title = factory.Faker('sentence') # date = factory.Faker('date') # # class UserFactory(factory.DjangoModelFactory): # class Meta: # model = 'auth.User' # # first_name = 'Test' # last_name = 'User' # username = factory.Sequence(lambda n: 'user_{0}'.format(n)) # email = factory.Sequence(lambda n: 'user_{0}@maykinmedia.nl'.format(n)) # password = factory.PostGenerationMethodCall('set_password', 'testing') . Output only the next line.
content_object=self.article,
Based on the snippet: <|code_start|> class ReportMailingTestCase(TestCase): def setUp(self): self.article = ArticleFactory.create() self.user = UserFactory.create(email='jose@maykinmedia.nl') self.staff_user = UserFactory.create(is_staff=True) self.admin_user = UserFactory.create(is_staff=True, is_superuser=True) self.log_1 = TimelineLog.objects.create( <|code_end|> , predict the immediate next line with the help of imports: from datetime import timedelta from django.conf import settings from django.core import mail from django.core.management import CommandError, call_command from django.template.defaultfilters import date from django.test import TestCase, override_settings from django.utils import timezone from timeline_logger.models import TimelineLog from .factories import ArticleFactory, UserFactory and context (classes, functions, sometimes code) from other files: # Path: timeline_logger/models.py # class TimelineLog(models.Model): # content_type = models.ForeignKey( # ContentType, # verbose_name=_('content type'), # on_delete=models.SET_NULL, # blank=True, null=True, # ) # object_id = models.TextField( # verbose_name=_('object id'), # blank=True, null=True # ) # content_object = GenericForeignKey('content_type', 'object_id') # timestamp = models.DateTimeField(verbose_name=_('timestamp'), auto_now_add=True) # extra_data = JSONField( # verbose_name=_('extra data'), # null=True, blank=True, # ) # user = models.ForeignKey( # settings.AUTH_USER_MODEL, # verbose_name=_('user'), # on_delete=models.SET_NULL, # blank=True, null=True, # ) # template = models.CharField(max_length=200, default=DEFAULT_TEMPLATE) # # class Meta: # verbose_name = _('timeline log entry') # verbose_name_plural = _('timeline log entries') # # def __str__(self): # if self.object_id: # return "{ct} - {pk}".format( # ct=self.content_type.name, # pk=self.object_id # ) # # return ugettext('TimelineLog Object') # # @classmethod # def log_from_request(cls, request, content_object, template=None, **extra_data): # """ # Given an ``HTTPRequest`` object and a generic content, it creates a # ``TimelineLog`` object to store the data of that request. # # :param request: A Django ``HTTPRequest`` object. # :param content_object: A Django model instance. Any object can be # related. # :param template: String representing the template to be used to render # the message. Defaults to 'default.txt'. # :param extra_data: A dictionary (translatable into JSON) determining # specifications of the action performed. # :return: A newly created ``TimelineLog`` instance. # """ # try: # user = request.user # except AttributeError: # user = None # # if template is not None: # # Ensure that the expected template actually exists. # get_template(template) # # timeline_log = cls.objects.create( # content_object=content_object, # extra_data=extra_data or None, # template=template or DEFAULT_TEMPLATE, # user=user, # ) # logger.debug('Logged event in %s %s', content_object._meta.object_name, content_object.pk) # return timeline_log # # def get_message(self, template=None, **extra_context): # """ # Gets the 'log' message, describing the event performed. # # :param template: String representing the template to be used to render # the message. Defaults to ``self.template``. # :return: The log message string. # """ # context = {'log': self} # context.update(**extra_context) # return render_to_string(template or self.template, context) # # Path: tests/factories.py # class ArticleFactory(factory.django.DjangoModelFactory): # # class Meta: # model = 'tests.Article' # # title = factory.Faker('sentence') # date = factory.Faker('date') # # class UserFactory(factory.DjangoModelFactory): # class Meta: # model = 'auth.User' # # first_name = 'Test' # last_name = 'User' # username = factory.Sequence(lambda n: 'user_{0}'.format(n)) # email = factory.Sequence(lambda n: 'user_{0}@maykinmedia.nl'.format(n)) # password = factory.PostGenerationMethodCall('set_password', 'testing') . Output only the next line.
content_object=self.article,
Using the snippet: <|code_start|> logger = logging.getLogger(__name__) CRS_BOUNDS = { # http://spatialreference.org/ref/epsg/wgs-84/ "epsg:4326": (-180.0, -90.0, 180.0, 90.0), # unknown source "epsg:3857": (-180.0, -85.0511, 180.0, 85.0511), # http://spatialreference.org/ref/epsg/3035/ "epsg:3035": (-10.6700, 34.5000, 31.5500, 71.0500), } def reproject_geometry( geometry, src_crs=None, <|code_end|> , determine the next line of code. You have imports: from fiona.transform import transform_geom from rasterio.crs import CRS from shapely.errors import TopologicalError from shapely.geometry import ( box, GeometryCollection, shape, mapping, MultiPoint, MultiLineString, MultiPolygon, Polygon, LinearRing, LineString, base, ) from shapely.validation import explain_validity from mapchete.errors import GeometryTypeError from mapchete.validate import validate_crs import logging import pyproj and context (class names, function names, or code) available: # Path: mapchete/errors.py # class GeometryTypeError(TypeError): # """Raised when geometry type does not fit.""" # # Path: mapchete/validate.py # def validate_crs(crs): # """ # Return crs as rasterio.crs.CRS. # # Parameters # ---------- # crs : rasterio.crs.CRS, str, int or dict # # Returns # ------- # rasterio.crs.CRS # # Raises # ------ # TypeError if type is invalid. # """ # if isinstance(crs, CRS): # return crs # elif isinstance(crs, str): # try: # return CRS().from_epsg(int(crs)) # except Exception: # return CRS().from_string(crs) # elif isinstance(crs, int): # return CRS().from_epsg(crs) # elif isinstance(crs, dict): # return CRS().from_dict(crs) # else: # raise TypeError("invalid CRS given") . Output only the next line.
dst_crs=None,
Here is a snippet: <|code_start|> logger = logging.getLogger(__name__) CRS_BOUNDS = { # http://spatialreference.org/ref/epsg/wgs-84/ "epsg:4326": (-180.0, -90.0, 180.0, 90.0), # unknown source "epsg:3857": (-180.0, -85.0511, 180.0, 85.0511), # http://spatialreference.org/ref/epsg/3035/ "epsg:3035": (-10.6700, 34.5000, 31.5500, 71.0500), } def reproject_geometry( geometry, src_crs=None, dst_crs=None, clip_to_crs_bounds=True, error_on_clip=False, segmentize_on_clip=False, segmentize=False, <|code_end|> . Write the next line using the current file imports: from fiona.transform import transform_geom from rasterio.crs import CRS from shapely.errors import TopologicalError from shapely.geometry import ( box, GeometryCollection, shape, mapping, MultiPoint, MultiLineString, MultiPolygon, Polygon, LinearRing, LineString, base, ) from shapely.validation import explain_validity from mapchete.errors import GeometryTypeError from mapchete.validate import validate_crs import logging import pyproj and context from other files: # Path: mapchete/errors.py # class GeometryTypeError(TypeError): # """Raised when geometry type does not fit.""" # # Path: mapchete/validate.py # def validate_crs(crs): # """ # Return crs as rasterio.crs.CRS. # # Parameters # ---------- # crs : rasterio.crs.CRS, str, int or dict # # Returns # ------- # rasterio.crs.CRS # # Raises # ------ # TypeError if type is invalid. # """ # if isinstance(crs, CRS): # return crs # elif isinstance(crs, str): # try: # return CRS().from_epsg(int(crs)) # except Exception: # return CRS().from_string(crs) # elif isinstance(crs, int): # return CRS().from_epsg(crs) # elif isinstance(crs, dict): # return CRS().from_dict(crs) # else: # raise TypeError("invalid CRS given") , which may include functions, classes, or code. Output only the next line.
segmentize_fraction=100,
Given the following code snippet before the placeholder: <|code_start|> def test_timer(): timer1 = Timer(elapsed=1000) timer2 = Timer(elapsed=2000) timer3 = Timer(elapsed=1000) assert timer1 < timer2 assert timer1 <= timer2 assert timer2 > timer3 assert timer2 >= timer3 assert timer1 == timer3 assert timer1 != timer2 <|code_end|> , predict the next line using imports from the current file: from mapchete import Timer and context including class names, function names, and sometimes code from other files: # Path: mapchete/_timer.py # class Timer: # """ # Context manager to facilitate timing code. # # Examples # -------- # >>> with Timer() as t: # ... # some longer running code # >>> print(t) # prints elapsed time # # based on http://preshing.com/20110924/timing-your-code-using-pythons-with-statement/ # """ # # def __init__(self, elapsed=0.0, str_round=3): # self._elapsed = elapsed # self._str_round = str_round # self.start = None # self.end = None # # def __enter__(self): # self.start = time.time() # return self # # def __exit__(self, *args): # self.end = time.time() # self._elapsed = self.end - self.start # # def __lt__(self, other): # return self._elapsed < other._elapsed # # def __le__(self, other): # return self._elapsed <= other._elapsed # # def __eq__(self, other): # return self._elapsed == other._elapsed # # def __ne__(self, other): # return self._elapsed != other._elapsed # # def __ge__(self, other): # return self._elapsed >= other._elapsed # # def __gt__(self, other): # return self._elapsed > other._elapsed # # def __add__(self, other): # return Timer(elapsed=self._elapsed + other._elapsed) # # def __sub__(self, other): # return Timer(elapsed=self._elapsed - other._elapsed) # # def __repr__(self): # return "Timer(start=%s, end=%s, elapsed=%s)" % ( # self.start, # self.end, # self.__str__(), # ) # # def __str__(self): # minutes, seconds = divmod(self.elapsed, 60) # hours, minutes = divmod(minutes, 60) # if hours: # return "%sh %sm %ss" % (int(hours), int(minutes), int(seconds)) # elif minutes: # return "%sm %ss" % (int(minutes), int(seconds)) # else: # return "%ss" % round(seconds, self._str_round) # # @property # def elapsed(self): # return ( # time.time() - self.start if self.start and not self.end else self._elapsed # ) . Output only the next line.
assert timer1 + timer3 == timer2
Next line prediction: <|code_start|> items = list(range(10)) with Executor(concurrency="threads") as executor: result = executor.map(_dummy_process, items) assert [i + 1 for i in items] == result def test_dask_executor_as_completed(): items = 100 with Executor(concurrency="dask", max_workers=2) as executor: # abort for future in executor.as_completed( _dummy_process, range(items), fkwargs=dict(sleep=2) ): assert future.result() executor.cancel() break assert not executor.running_futures def test_dask_executor_as_completed_skip(): items = 100 skip_info = "foo" with Executor(concurrency="dask", max_workers=2) as executor: count = 0 for future in executor.as_completed( _dummy_process, [(i, True, skip_info) for i in range(items)], item_skip_bool=True, fkwargs=dict(sleep=2), <|code_end|> . Use current file imports: (import pytest import time from mapchete import Executor, SkippedFuture from mapchete._executor import FakeFuture) and context including class names, function names, or small code snippets from other files: # Path: mapchete/_executor.py # class Executor: # """ # Executor factory for dask and concurrent.futures executor # # Will move into the mapchete core package. # """ # # def __new__(cls, *args, concurrency=None, **kwargs): # if concurrency == "dask": # try: # return DaskExecutor(*args, **kwargs) # except ImportError as exc: # pragma: no cover # raise ImportError( # "this feature requires the mapchete[dask] extra" # ) from exc # # elif concurrency is None or kwargs.get("max_workers") == 1: # return SequentialExecutor(*args, **kwargs) # # elif concurrency in ["processes", "threads"]: # return ConcurrentFuturesExecutor(*args, concurrency=concurrency, **kwargs) # # else: # pragma: no cover # raise ValueError( # f"concurrency must be one of None, 'processes', 'threads' or 'dask', not {concurrency}" # ) # # class SkippedFuture: # """Wrapper class to mimick future interface for empty tasks.""" # # def __init__(self, result=None, skip_info=None, **kwargs): # self._result = result # self.skip_info = skip_info # # def result(self): # """Only return initial result value.""" # return self._result # # def exception(self): # pragma: no cover # """Nothing to raise here.""" # return # # def cancelled(self): # pragma: no cover # """Nothing to cancel here.""" # return False # # def __repr__(self): # pragma: no cover # """Return string representation.""" # return f"<SkippedFuture: type: {type(self._result)}, exception: {type(self._exception)})" # # Path: mapchete/_executor.py # class FakeFuture: # """Wrapper class to mimick future interface.""" # # def __init__(self, func, fargs=None, fkwargs=None): # """Set attributes.""" # fargs = fargs or [] # fkwargs = fkwargs or {} # try: # self._result, self._exception = func(*fargs, **fkwargs), None # except Exception as e: # pragma: no cover # self._result, self._exception = None, e # # def result(self): # """Return task result.""" # if self._exception: # logger.exception(self._exception) # raise self._exception # return self._result # # def exception(self): # """Raise task exception if any.""" # return self._exception # # def cancelled(self): # pragma: no cover # """Sequential futures cannot be cancelled.""" # return False # # def __repr__(self): # pragma: no cover # """Return string representation.""" # return f"<FakeFuture: type: {type(self._result)}, exception: {type(self._exception)})" . Output only the next line.
):
Based on the snippet: <|code_start|> ): assert future.result() executor.cancel() break assert not executor.running_futures def test_dask_executor_as_completed_skip(): items = 100 skip_info = "foo" with Executor(concurrency="dask", max_workers=2) as executor: count = 0 for future in executor.as_completed( _dummy_process, [(i, True, skip_info) for i in range(items)], item_skip_bool=True, fkwargs=dict(sleep=2), ): count += 1 assert isinstance(future, SkippedFuture) assert future.skip_info == skip_info assert items == count def test_dask_executor_as_completed_max_tasks(): items = 100 with Executor(concurrency="dask") as executor: # abort for future in executor.as_completed( <|code_end|> , predict the immediate next line with the help of imports: import pytest import time from mapchete import Executor, SkippedFuture from mapchete._executor import FakeFuture and context (classes, functions, sometimes code) from other files: # Path: mapchete/_executor.py # class Executor: # """ # Executor factory for dask and concurrent.futures executor # # Will move into the mapchete core package. # """ # # def __new__(cls, *args, concurrency=None, **kwargs): # if concurrency == "dask": # try: # return DaskExecutor(*args, **kwargs) # except ImportError as exc: # pragma: no cover # raise ImportError( # "this feature requires the mapchete[dask] extra" # ) from exc # # elif concurrency is None or kwargs.get("max_workers") == 1: # return SequentialExecutor(*args, **kwargs) # # elif concurrency in ["processes", "threads"]: # return ConcurrentFuturesExecutor(*args, concurrency=concurrency, **kwargs) # # else: # pragma: no cover # raise ValueError( # f"concurrency must be one of None, 'processes', 'threads' or 'dask', not {concurrency}" # ) # # class SkippedFuture: # """Wrapper class to mimick future interface for empty tasks.""" # # def __init__(self, result=None, skip_info=None, **kwargs): # self._result = result # self.skip_info = skip_info # # def result(self): # """Only return initial result value.""" # return self._result # # def exception(self): # pragma: no cover # """Nothing to raise here.""" # return # # def cancelled(self): # pragma: no cover # """Nothing to cancel here.""" # return False # # def __repr__(self): # pragma: no cover # """Return string representation.""" # return f"<SkippedFuture: type: {type(self._result)}, exception: {type(self._exception)})" # # Path: mapchete/_executor.py # class FakeFuture: # """Wrapper class to mimick future interface.""" # # def __init__(self, func, fargs=None, fkwargs=None): # """Set attributes.""" # fargs = fargs or [] # fkwargs = fkwargs or {} # try: # self._result, self._exception = func(*fargs, **fkwargs), None # except Exception as e: # pragma: no cover # self._result, self._exception = None, e # # def result(self): # """Return task result.""" # if self._exception: # logger.exception(self._exception) # raise self._exception # return self._result # # def exception(self): # """Raise task exception if any.""" # return self._exception # # def cancelled(self): # pragma: no cover # """Sequential futures cannot be cancelled.""" # return False # # def __repr__(self): # pragma: no cover # """Return string representation.""" # return f"<FakeFuture: type: {type(self._result)}, exception: {type(self._exception)})" . Output only the next line.
_dummy_process, range(items), max_submitted_tasks=1
Given the code snippet: <|code_start|> count += 1 assert isinstance(future, SkippedFuture) assert future.skip_info == skip_info assert items == count def test_dask_executor_as_completed_max_tasks(): items = 100 with Executor(concurrency="dask") as executor: # abort for future in executor.as_completed( _dummy_process, range(items), max_submitted_tasks=1 ): assert future.result() assert not executor.running_futures def test_dask_executor_as_completed_unlimited_max_tasks(): items = 100 with Executor(concurrency="dask") as executor: # abort for future in executor.as_completed( _dummy_process, range(items), max_submitted_tasks=None ): assert future.result() assert not executor.running_futures <|code_end|> , generate the next line using the imports in this file: import pytest import time from mapchete import Executor, SkippedFuture from mapchete._executor import FakeFuture and context (functions, classes, or occasionally code) from other files: # Path: mapchete/_executor.py # class Executor: # """ # Executor factory for dask and concurrent.futures executor # # Will move into the mapchete core package. # """ # # def __new__(cls, *args, concurrency=None, **kwargs): # if concurrency == "dask": # try: # return DaskExecutor(*args, **kwargs) # except ImportError as exc: # pragma: no cover # raise ImportError( # "this feature requires the mapchete[dask] extra" # ) from exc # # elif concurrency is None or kwargs.get("max_workers") == 1: # return SequentialExecutor(*args, **kwargs) # # elif concurrency in ["processes", "threads"]: # return ConcurrentFuturesExecutor(*args, concurrency=concurrency, **kwargs) # # else: # pragma: no cover # raise ValueError( # f"concurrency must be one of None, 'processes', 'threads' or 'dask', not {concurrency}" # ) # # class SkippedFuture: # """Wrapper class to mimick future interface for empty tasks.""" # # def __init__(self, result=None, skip_info=None, **kwargs): # self._result = result # self.skip_info = skip_info # # def result(self): # """Only return initial result value.""" # return self._result # # def exception(self): # pragma: no cover # """Nothing to raise here.""" # return # # def cancelled(self): # pragma: no cover # """Nothing to cancel here.""" # return False # # def __repr__(self): # pragma: no cover # """Return string representation.""" # return f"<SkippedFuture: type: {type(self._result)}, exception: {type(self._exception)})" # # Path: mapchete/_executor.py # class FakeFuture: # """Wrapper class to mimick future interface.""" # # def __init__(self, func, fargs=None, fkwargs=None): # """Set attributes.""" # fargs = fargs or [] # fkwargs = fkwargs or {} # try: # self._result, self._exception = func(*fargs, **fkwargs), None # except Exception as e: # pragma: no cover # self._result, self._exception = None, e # # def result(self): # """Return task result.""" # if self._exception: # logger.exception(self._exception) # raise self._exception # return self._result # # def exception(self): # """Raise task exception if any.""" # return self._exception # # def cancelled(self): # pragma: no cover # """Sequential futures cannot be cancelled.""" # return False # # def __repr__(self): # pragma: no cover # """Return string representation.""" # return f"<FakeFuture: type: {type(self._result)}, exception: {type(self._exception)})" . Output only the next line.
def test_concurrent_futures_dask_executor_map():
Based on the snippet: <|code_start|>KNOWN_MATRIX_PROPERTIES = { "geodetic": { "name": "WorldCRS84Quad", "url": "http://schemas.opengis.net/tms/1.0/json/examples/WorldCRS84Quad.json", "title": "CRS84 for the World", "crs": "http://www.opengis.net/def/crs/OGC/1.3/CRS84", "supportedCRS": "http://www.opengis.net/def/crs/OGC/1.3/CRS84", "wellKnownScaleSet": "http://www.opengis.net/def/wkss/OGC/1.0/GoogleCRS84Quad", }, "mercator": { "name": "WebMercatorQuad", "url": "http://schemas.opengis.net/tms/1.0/json/examples/WebMercatorQuad.json", "title": "Google Maps Compatible for the World", "crs": "http://www.opengis.net/def/crs/EPSG/0/3857", "supportedCRS": "http://www.opengis.net/def/crs/EPSG/0/3857", "wellKnownScaleSet": "http://www.opengis.net/def/wkss/OGC/1.0/GoogleMapsCompatible", }, } def tile_directory_stac_item( item_id=None, tile_pyramid=None, max_zoom=None, item_path=None, asset_basepath=None, relative_paths=False, min_zoom=0, item_metadata=None, bounds=None, <|code_end|> , predict the immediate next line with the help of imports: from collections import OrderedDict from shapely.geometry import box, mapping from mapchete.io.vector import reproject_geometry from pystac.version import get_stac_version import datetime import os import pystac and context (classes, functions, sometimes code) from other files: # Path: mapchete/io/vector.py # def read_vector_window(inp, tile, validity_check=True, clip_to_crs_bounds=False): # def _read_vector_window(inp, tile, validity_check=True, clip_to_crs_bounds=False): # def write_vector_window( # in_data=None, # out_driver="GeoJSON", # out_schema=None, # out_tile=None, # out_path=None, # bucket_resource=None, # allow_multipart_geometries=True, # ): # def __init__(self, tile=None, features=None, schema=None, driver=None): # def __enter__(self): # def __exit__(self, *args): # def _get_reprojected_features( # inp=None, # dst_bounds=None, # dst_crs=None, # validity_check=False, # clip_to_crs_bounds=False, # ): # def bounds_intersect(bounds1, bounds2): # def __init__(self): # def insert(self, id, bounds): # def intersection(self, bounds): # def __init__(self, features, index="rtree", allow_non_geo_objects=False, crs=None): # def __repr__(self): # pragma: no cover # def __len__(self): # def __str__(self): # pragma: no cover # def __getitem__(self, key): # def __iter__(self): # def items(self): # def keys(self): # def values(self): # def filter(self, bounds=None, bbox=None): # def _update_bounds(self, bounds): # def _get_feature_id(self, feature): # def _get_feature_bounds(self, feature, allow_non_geo_objects=False): # def convert_vector(inp, out, overwrite=False, exists_ok=True, **kwargs): # def read_vector(inp, index="rtree"): # class VectorWindowMemoryFile: # class FakeIndex: # class IndexedFeatures: . Output only the next line.
bounds_crs=None,
Given the following code snippet before the placeholder: <|code_start|> out_path = mp.config.output_reader.get_path( mp.config.process_pyramid.tile(*tile) ) with rasterio.open(out_path) as src: assert not src.read(masked=True).mask.all() out_path = mp.config.output_reader.path total_tifs = [ f"{directory[0]}/{file}" for directory in fs_from_path(out_path).walk(out_path) for file in directory[2] if file.endswith(".tif") ] assert len(total_tifs) == 1 def test_preprocessing_tasks_dependencies_single_tile_dask(preprocess_cache_memory): with preprocess_cache_memory.mp(batch_preprocess=False) as mp: for i in ["clip", "inp"]: input_data = mp.config.input_at_zoom(key=i, zoom=5) for task in input_data.preprocessing_tasks.values(): assert isinstance(task, Task) assert task.has_geometry() tile = (5, 31, 63) list(mp.compute(concurrency="dask", tile=tile)) out_path = mp.config.output_reader.get_path( mp.config.process_pyramid.tile(*tile) <|code_end|> , predict the next line using imports from the current file: import mapchete import pytest import rasterio from mapchete.io import fs_from_path from mapchete._tasks import Task and context including class names, function names, and sometimes code from other files: # Path: mapchete/io/_path.py # def fs_from_path(path, timeout=5, session=None, username=None, password=None, **kwargs): # """Guess fsspec FileSystem from path and initialize using the desired options.""" # if path.startswith("s3://"): # return fsspec.filesystem( # "s3", # requester_pays=os.environ.get("AWS_REQUEST_PAYER") == "requester", # config_kwargs=dict(connect_timeout=timeout, read_timeout=timeout), # session=session, # client_kwargs=kwargs, # ) # elif path.startswith(("http://", "https://")): # if username: # pragma: no cover # from aiohttp import BasicAuth # # auth = BasicAuth(username, password) # else: # auth = None # return fsspec.filesystem("https", auth=auth, asynchronous=False, **kwargs) # else: # return fsspec.filesystem("file", asynchronous=False, **kwargs) # # Path: mapchete/_tasks.py # class Task: # """Generic processing task. # # Can optionally have spatial properties attached which helps building up dependencies # between tasks. # """ # # def __init__( # self, # id=None, # func=None, # fargs=None, # fkwargs=None, # geometry=None, # bounds=None, # dependencies=None, # ): # self.id = id or uuid4().hex # self.func = func # self.fargs = fargs or () # self.fkwargs = fkwargs or {} # self.dependencies = dependencies or {} # if geometry and bounds: # raise ValueError("only provide one of either 'geometry' or 'bounds'") # elif geometry: # self.geometry = to_shape(geometry) # self.bounds = self.geometry.bounds # elif bounds: # self.bounds = validate_bounds(bounds) # self.geometry = box(*self.bounds) # else: # self.bounds, self.geometry = None, None # # def __repr__(self): # pragma: no cover # return f"Task(id={self.id}, bounds={self.bounds})" # # def to_dict(self): # return { # "id": self.id, # "bounds": self.bounds, # "geometry": mapping(self.geometry) if self.geometry else None, # "properties": {}, # } # # def add_dependencies(self, dependencies): # dependencies = dependencies or {} # if not isinstance(dependencies, dict): # raise TypeError( # f"dependencies must be a dictionary, not {type(dependencies)}" # ) # self.dependencies.update(dependencies) # # def execute(self, dependencies=None): # return self.func(*self.fargs, **self.fkwargs) # # def has_geometry(self): # return self.geometry is not None # # @property # def __geo_interface__(self): # if self.has_geometry(): # return mapping(self.geometry) # else: # raise NoTaskGeometry(f"{self} has no geo information assigned") . Output only the next line.
)
Based on the snippet: <|code_start|> assert inp1.get_preprocessing_task_result("test_task") == "foofoobar" assert mp.config.preprocessing_task_finished( f"{inp1.input_key}:test_other_task" ) assert inp1.get_preprocessing_task_result("test_other_task") == "barfoobar" assert mp.config.preprocessing_task_finished(f"{inp2.input_key}:test_task") assert inp2.get_preprocessing_task_result("test_task") == "foofoobar" def test_preprocess_cache_raster_vector(preprocess_cache_raster_vector): # tile containing only features: 5 29 62 mp = preprocess_cache_raster_vector.process_mp((5, 29, 62)) with mp.open("clip") as clip: assert clip.path.endswith("cache/aoi_br.fgb") assert clip.read() with mp.open("inp") as raster: assert raster.path.endswith("cache/cleantopo_br.tif") assert raster.read().mask.all() # tile containing features and raster: 5 30 62 mp = preprocess_cache_raster_vector.process_mp((5, 30, 62)) with mp.open("clip") as clip: assert clip.path.endswith("cache/aoi_br.fgb") assert clip.read() with mp.open("inp") as raster: assert raster.path.endswith("cache/cleantopo_br.tif") assert not raster.read().mask.all() def test_preprocess_cache_raster_vector_tasks(preprocess_cache_raster_vector): <|code_end|> , predict the immediate next line with the help of imports: import mapchete import pytest import rasterio from mapchete.io import fs_from_path from mapchete._tasks import Task and context (classes, functions, sometimes code) from other files: # Path: mapchete/io/_path.py # def fs_from_path(path, timeout=5, session=None, username=None, password=None, **kwargs): # """Guess fsspec FileSystem from path and initialize using the desired options.""" # if path.startswith("s3://"): # return fsspec.filesystem( # "s3", # requester_pays=os.environ.get("AWS_REQUEST_PAYER") == "requester", # config_kwargs=dict(connect_timeout=timeout, read_timeout=timeout), # session=session, # client_kwargs=kwargs, # ) # elif path.startswith(("http://", "https://")): # if username: # pragma: no cover # from aiohttp import BasicAuth # # auth = BasicAuth(username, password) # else: # auth = None # return fsspec.filesystem("https", auth=auth, asynchronous=False, **kwargs) # else: # return fsspec.filesystem("file", asynchronous=False, **kwargs) # # Path: mapchete/_tasks.py # class Task: # """Generic processing task. # # Can optionally have spatial properties attached which helps building up dependencies # between tasks. # """ # # def __init__( # self, # id=None, # func=None, # fargs=None, # fkwargs=None, # geometry=None, # bounds=None, # dependencies=None, # ): # self.id = id or uuid4().hex # self.func = func # self.fargs = fargs or () # self.fkwargs = fkwargs or {} # self.dependencies = dependencies or {} # if geometry and bounds: # raise ValueError("only provide one of either 'geometry' or 'bounds'") # elif geometry: # self.geometry = to_shape(geometry) # self.bounds = self.geometry.bounds # elif bounds: # self.bounds = validate_bounds(bounds) # self.geometry = box(*self.bounds) # else: # self.bounds, self.geometry = None, None # # def __repr__(self): # pragma: no cover # return f"Task(id={self.id}, bounds={self.bounds})" # # def to_dict(self): # return { # "id": self.id, # "bounds": self.bounds, # "geometry": mapping(self.geometry) if self.geometry else None, # "properties": {}, # } # # def add_dependencies(self, dependencies): # dependencies = dependencies or {} # if not isinstance(dependencies, dict): # raise TypeError( # f"dependencies must be a dictionary, not {type(dependencies)}" # ) # self.dependencies.update(dependencies) # # def execute(self, dependencies=None): # return self.func(*self.fargs, **self.fkwargs) # # def has_geometry(self): # return self.geometry is not None # # @property # def __geo_interface__(self): # if self.has_geometry(): # return mapping(self.geometry) # else: # raise NoTaskGeometry(f"{self} has no geo information assigned") . Output only the next line.
with preprocess_cache_raster_vector.mp() as mp:
Using the snippet: <|code_start|> def _validate_json(self, json_object): contents = pkg_resources.resource_string(__name__, 'sperimentschema.json') schema = json.loads(contents) jsonschema.validate(json_object, schema) def to_JSON(self): SampleFrom._compile_time_generators = copy.deepcopy(SampleFrom._id_generators) return json.dumps(self, indent = 4, cls = ExperimentEncoder) def to_file(self, filename, varname): '''validates the structure of the experiment and writes it as a JSON object in a JavaScript file.''' json_experiment = self.to_JSON() self._validate_json(json_experiment) to_write = 'var ' + varname + ' = ' + json_experiment with open(filename, 'w') as f: f.write(to_write) def install(self, experiment_name): '''validates the structure of the experiment, writes it as a JSON object in a JavaScript file, and gives PsiTurk access to Speriment and the JSON object.''' filename = experiment_name + '.js' varname = experiment_name self.to_file('./static/js/' + filename, varname) make_exp(filename) make_task(varname) def get_samplers(obj): <|code_end|> , determine the next line of code. You have imports: from component import Component from sample_from import SampleFrom from speriment.compiler import ExperimentEncoder from speriment.utils import make_exp, make_task, IDGenerator import pkg_resources, json, jsonschema, copy and context (class names, function names, or code) available: # Path: speriment/compiler.py # class ExperimentEncoder(json.JSONEncoder): # '''This class enables nested Python objects to be correctly serialized to JSON. # It also requires that non-schema validation pass before the JSON is # generated.''' # def default(self, obj): # obj._validate() # new_obj = copy.deepcopy(obj) # try: # return new_obj.comp().__dict__ # except: # # Let the base class default method raise the TypeError # return json.JSONEncoder.default(self, new_obj.__dict__) # # Path: speriment/utils.py # def make_exp(filename): # '''Add script tags to PsiTurk's exp.html file so it can use speriment.js and # the JSON object, and add css link so it can use speriment.css.''' # exp_file = './templates/exp.html' # #TODO will change to static/lib/node_modules/speriment/speriment.js and maybe min # speriment_tag = '''\n\t\t<script src="/static/lib/node_modules/speriment/javascript/speriment.js" type="text/javascript">''' # json_tag = '''\n\t\t<script src="/static/js/{0}" type="text/javascript">'''.format(filename) # script_divider = '</script>' # css_tag = '''\n\t<link rel=stylesheet href="/static/lib/node_modules/speriment/css/speriment.css"''' # css_divider = 'type="text/css">' # new_contents = None # with open(exp_file, 'r') as exp: # exp_contents = exp.read() # script_tags = exp_contents.split(script_divider) # # These scripts must go after PsiTurk and its dependencies but before # # task.js and the rest of the page # if script_tags[-4] == speriment_tag: # script_tags[-3] = json_tag # else: # script_tags = script_tags[:-2] + [speriment_tag] + [json_tag] + script_tags[-2:] # with_scripts = script_divider.join(script_tags) # contents = with_scripts.split(css_divider) # if contents[-2] != css_tag: # contents = contents[:-1] + [css_tag] + [contents[-1]] # new_contents = css_divider.join(contents) # with open(exp_file, 'w') as expw: # expw.write(new_contents) # # def make_task(varname): # '''Replace PsiTurk's example task.js with the standard Speriment task.js, # with the JSON object variable name inserted.''' # with open('./static/js/task.js', 'w') as task: # task.write('''$(document).ready(function(){ # var mySperiment = ''' + varname + '''; # var psiturk = PsiTurk(uniqueId, adServerLoc); # psiturk.finishInstructions(); # var speriment = new Experiment(mySperiment, condition, counterbalance, psiturk); # speriment.start(); # });''') # # class IDGenerator: # '''Creates an object to generate unique IDs for experimental components. You # should create exactly one per experiment so that all IDs in that experiment # will be distinct. # # Usage: # with make_experiment(IDGenerator()): # <experiment code> # ''' # # def __init__(self, seed = -1): # '''seed: optional, an integer to start making IDs at.''' # self.current_id = seed # # def _current(self): # return self.current_id # # def _next_id(self): # '''Takes no arguments and returns a string, which is a new unique ID.''' # self.current_id += 1 # return str(self.current_id) . Output only the next line.
attrs = obj.__dict__
Continue the code snippet: <|code_start|> if any_replacement and not all_replacement: raise ValueError('''Some SampleFrom objects for bank {} are with replacement and some are without replacement. They must all sample the same way.'''.format(bank_name)) if any(type(val) == dict for val in bank): if not all(type(val) == dict for val in bank): raise ValueError('''Values in {} must all be either strings or dictionaries'''.format(bank_name)) fields = bank[0].keys() if not all(val.keys() == fields for val in bank): raise ValueError('''All values in {} must have the same fields'''.format(bank_name)) if not all(hasattr(sampler, field) for sampler in samplers): raise ValueError('''All SampleFrom objects sampling from {} must specify a field.'''.format(bank_name)) if not all(sampler.field in fields for sampler in samplers): for sampler in samplers: if sampler.field not in fields: raise ValueError('''Attempt to sample {} field from {}, which is not among its fields'''.format(sampler.field, bank_name)) def _validate_json(self, json_object): contents = pkg_resources.resource_string(__name__, 'sperimentschema.json') schema = json.loads(contents) jsonschema.validate(json_object, schema) def to_JSON(self): SampleFrom._compile_time_generators = copy.deepcopy(SampleFrom._id_generators) return json.dumps(self, indent = 4, cls = ExperimentEncoder) def to_file(self, filename, varname): '''validates the structure of the experiment and writes it as a JSON object in a JavaScript file.''' json_experiment = self.to_JSON() <|code_end|> . Use current file imports: from component import Component from sample_from import SampleFrom from speriment.compiler import ExperimentEncoder from speriment.utils import make_exp, make_task, IDGenerator import pkg_resources, json, jsonschema, copy and context (classes, functions, or code) from other files: # Path: speriment/compiler.py # class ExperimentEncoder(json.JSONEncoder): # '''This class enables nested Python objects to be correctly serialized to JSON. # It also requires that non-schema validation pass before the JSON is # generated.''' # def default(self, obj): # obj._validate() # new_obj = copy.deepcopy(obj) # try: # return new_obj.comp().__dict__ # except: # # Let the base class default method raise the TypeError # return json.JSONEncoder.default(self, new_obj.__dict__) # # Path: speriment/utils.py # def make_exp(filename): # '''Add script tags to PsiTurk's exp.html file so it can use speriment.js and # the JSON object, and add css link so it can use speriment.css.''' # exp_file = './templates/exp.html' # #TODO will change to static/lib/node_modules/speriment/speriment.js and maybe min # speriment_tag = '''\n\t\t<script src="/static/lib/node_modules/speriment/javascript/speriment.js" type="text/javascript">''' # json_tag = '''\n\t\t<script src="/static/js/{0}" type="text/javascript">'''.format(filename) # script_divider = '</script>' # css_tag = '''\n\t<link rel=stylesheet href="/static/lib/node_modules/speriment/css/speriment.css"''' # css_divider = 'type="text/css">' # new_contents = None # with open(exp_file, 'r') as exp: # exp_contents = exp.read() # script_tags = exp_contents.split(script_divider) # # These scripts must go after PsiTurk and its dependencies but before # # task.js and the rest of the page # if script_tags[-4] == speriment_tag: # script_tags[-3] = json_tag # else: # script_tags = script_tags[:-2] + [speriment_tag] + [json_tag] + script_tags[-2:] # with_scripts = script_divider.join(script_tags) # contents = with_scripts.split(css_divider) # if contents[-2] != css_tag: # contents = contents[:-1] + [css_tag] + [contents[-1]] # new_contents = css_divider.join(contents) # with open(exp_file, 'w') as expw: # expw.write(new_contents) # # def make_task(varname): # '''Replace PsiTurk's example task.js with the standard Speriment task.js, # with the JSON object variable name inserted.''' # with open('./static/js/task.js', 'w') as task: # task.write('''$(document).ready(function(){ # var mySperiment = ''' + varname + '''; # var psiturk = PsiTurk(uniqueId, adServerLoc); # psiturk.finishInstructions(); # var speriment = new Experiment(mySperiment, condition, counterbalance, psiturk); # speriment.start(); # });''') # # class IDGenerator: # '''Creates an object to generate unique IDs for experimental components. You # should create exactly one per experiment so that all IDs in that experiment # will be distinct. # # Usage: # with make_experiment(IDGenerator()): # <experiment code> # ''' # # def __init__(self, seed = -1): # '''seed: optional, an integer to start making IDs at.''' # self.current_id = seed # # def _current(self): # return self.current_id # # def _next_id(self): # '''Takes no arguments and returns a string, which is a new unique ID.''' # self.current_id += 1 # return str(self.current_id) . Output only the next line.
self._validate_json(json_experiment)
Continue the code snippet: <|code_start|> raise ValueError('''All values in {} must have the same fields'''.format(bank_name)) if not all(hasattr(sampler, field) for sampler in samplers): raise ValueError('''All SampleFrom objects sampling from {} must specify a field.'''.format(bank_name)) if not all(sampler.field in fields for sampler in samplers): for sampler in samplers: if sampler.field not in fields: raise ValueError('''Attempt to sample {} field from {}, which is not among its fields'''.format(sampler.field, bank_name)) def _validate_json(self, json_object): contents = pkg_resources.resource_string(__name__, 'sperimentschema.json') schema = json.loads(contents) jsonschema.validate(json_object, schema) def to_JSON(self): SampleFrom._compile_time_generators = copy.deepcopy(SampleFrom._id_generators) return json.dumps(self, indent = 4, cls = ExperimentEncoder) def to_file(self, filename, varname): '''validates the structure of the experiment and writes it as a JSON object in a JavaScript file.''' json_experiment = self.to_JSON() self._validate_json(json_experiment) to_write = 'var ' + varname + ' = ' + json_experiment with open(filename, 'w') as f: f.write(to_write) def install(self, experiment_name): '''validates the structure of the experiment, writes it as a JSON object in a JavaScript file, and gives PsiTurk access to Speriment and the JSON object.''' <|code_end|> . Use current file imports: from component import Component from sample_from import SampleFrom from speriment.compiler import ExperimentEncoder from speriment.utils import make_exp, make_task, IDGenerator import pkg_resources, json, jsonschema, copy and context (classes, functions, or code) from other files: # Path: speriment/compiler.py # class ExperimentEncoder(json.JSONEncoder): # '''This class enables nested Python objects to be correctly serialized to JSON. # It also requires that non-schema validation pass before the JSON is # generated.''' # def default(self, obj): # obj._validate() # new_obj = copy.deepcopy(obj) # try: # return new_obj.comp().__dict__ # except: # # Let the base class default method raise the TypeError # return json.JSONEncoder.default(self, new_obj.__dict__) # # Path: speriment/utils.py # def make_exp(filename): # '''Add script tags to PsiTurk's exp.html file so it can use speriment.js and # the JSON object, and add css link so it can use speriment.css.''' # exp_file = './templates/exp.html' # #TODO will change to static/lib/node_modules/speriment/speriment.js and maybe min # speriment_tag = '''\n\t\t<script src="/static/lib/node_modules/speriment/javascript/speriment.js" type="text/javascript">''' # json_tag = '''\n\t\t<script src="/static/js/{0}" type="text/javascript">'''.format(filename) # script_divider = '</script>' # css_tag = '''\n\t<link rel=stylesheet href="/static/lib/node_modules/speriment/css/speriment.css"''' # css_divider = 'type="text/css">' # new_contents = None # with open(exp_file, 'r') as exp: # exp_contents = exp.read() # script_tags = exp_contents.split(script_divider) # # These scripts must go after PsiTurk and its dependencies but before # # task.js and the rest of the page # if script_tags[-4] == speriment_tag: # script_tags[-3] = json_tag # else: # script_tags = script_tags[:-2] + [speriment_tag] + [json_tag] + script_tags[-2:] # with_scripts = script_divider.join(script_tags) # contents = with_scripts.split(css_divider) # if contents[-2] != css_tag: # contents = contents[:-1] + [css_tag] + [contents[-1]] # new_contents = css_divider.join(contents) # with open(exp_file, 'w') as expw: # expw.write(new_contents) # # def make_task(varname): # '''Replace PsiTurk's example task.js with the standard Speriment task.js, # with the JSON object variable name inserted.''' # with open('./static/js/task.js', 'w') as task: # task.write('''$(document).ready(function(){ # var mySperiment = ''' + varname + '''; # var psiturk = PsiTurk(uniqueId, adServerLoc); # psiturk.finishInstructions(); # var speriment = new Experiment(mySperiment, condition, counterbalance, psiturk); # speriment.start(); # });''') # # class IDGenerator: # '''Creates an object to generate unique IDs for experimental components. You # should create exactly one per experiment so that all IDs in that experiment # will be distinct. # # Usage: # with make_experiment(IDGenerator()): # <experiment code> # ''' # # def __init__(self, seed = -1): # '''seed: optional, an integer to start making IDs at.''' # self.current_id = seed # # def _current(self): # return self.current_id # # def _next_id(self): # '''Takes no arguments and returns a string, which is a new unique ID.''' # self.current_id += 1 # return str(self.current_id) . Output only the next line.
filename = experiment_name + '.js'
Here is a snippet: <|code_start|> class SampleFrom: '''Stands in place of a value of a Page or Option and tells the program to randomly choose a value to go there on a per-participant basis. Once sampled, the choice will remain in place for all iterations of the block. Sampling happens after pages are chosen from groups.''' _id_generators = {} # {bankname: IDGenerator} _variable_maps = {} # {bankname: {variablename: index}} _compile_time_generators = {} # {bankname: IDGenerator} def __init__(self, bank, variable = None, not_variable = None, field = None, <|code_end|> . Write the next line using the current file imports: from speriment.utils import IDGenerator, at_most_one import copy and context from other files: # Path: speriment/utils.py # class IDGenerator: # '''Creates an object to generate unique IDs for experimental components. You # should create exactly one per experiment so that all IDs in that experiment # will be distinct. # # Usage: # with make_experiment(IDGenerator()): # <experiment code> # ''' # # def __init__(self, seed = -1): # '''seed: optional, an integer to start making IDs at.''' # self.current_id = seed # # def _current(self): # return self.current_id # # def _next_id(self): # '''Takes no arguments and returns a string, which is a new unique ID.''' # self.current_id += 1 # return str(self.current_id) # # def at_most_one(obj, attributes): # found = [attribute for attribute in attributes if hasattr(obj, attribute)] # if len(found) > 1: # raise ValueError, '''{} must have at most one of the following attributes: # # {} # # but it has: # # {}.'''.format(obj, attributes, found) , which may include functions, classes, or code. Output only the next line.
with_replacement = False):
Predict the next line after this snippet: <|code_start|> group] except AttributeError: raise ValueError, '''In block {0}, can't pseudorandomize pages without conditions.'''.format(self.id_str) cond_counter = Counter(conditions) cond_counts = cond_counter.values() num_cond_counts = len(set(cond_counts)) if num_cond_counts != 1: raise ValueError, '''Can't pseudorandomize pages if not all conditions are represented the same number of times in the block.''' #TODO elif hasattr('pages') def _validate_latin_square(self): pass def comp(self): if hasattr(self, 'treatments'): self.compile_treatments() if hasattr(self, 'latin_square'): self.latinSquare = self.latin_square del self.latin_square super(Block, self).comp() return self def compile_treatments(self): '''Treatments are lists of lists of blocks to run conditionally. Remove this variable and add RunIf objects to those blocks.''' for i, treatment in enumerate(self.treatments): for block in treatment: <|code_end|> using the current file's imports: from component import Component from run_if import RunIf from collections import Counter from speriment.utils import exactly_one and any relevant context from other files: # Path: speriment/utils.py # def exactly_one(obj, attributes): # found = [attribute for attribute in attributes if hasattr(obj, attribute)] # if len(found) != 1: # raise ValueError, '''{} must have exactly one of the following attributes: # # {} # # but it has: # # {}.'''.format(obj, attributes, found) . Output only the next line.
block.run_if = RunIf(permutation = i)
Predict the next line after this snippet: <|code_start|> that Pages can display multiple times if they are in Blocks with a criterion.''' if item != None: self.item = item if page != None: self.page = page if option != None: self.option = option elif regex != None: self.regex = regex if permutation != None: self.permutation = permutation def _validate(self): exactly_one(self, ['item', 'page', 'permutation']) if hasattr(self, 'item'): item_contents = self.item.contents if hasattr(self.item, 'contents') else self.item.pages if not (type(item_contents) != list or len(item_contents) == 1): raise ValueError, '''Cannot set RunIf by Item if Item has more than one Page.''' def comp(self): if hasattr(self, 'page'): self.pageID = self.page.id_str if self.page.id_str else self.page.id del self.page if hasattr(self, 'option'): self.optionID = self.option.id_str if self.option.id_str else self.option.id del self.option if hasattr(self, 'item'): page = self.item.pages[0] self.pageID = page.id_str if page.id_str else page.id <|code_end|> using the current file's imports: from speriment.utils import exactly_one and any relevant context from other files: # Path: speriment/utils.py # def exactly_one(obj, attributes): # found = [attribute for attribute in attributes if hasattr(obj, attribute)] # if len(found) != 1: # raise ValueError, '''{} must have exactly one of the following attributes: # # {} # # but it has: # # {}.'''.format(obj, attributes, found) . Output only the next line.
del self.item
Based on the snippet: <|code_start|> raise ValueError, '''A text box option should have a regular expression rather than a boolean as its "correct" attribute.''' if hasattr(self, 'correct'): if self.correct in [True, False]: raise ValueError, '''A text box option should have a regular expression rather than a boolean as its "correct" attribute.''' else: if hasattr(self, 'correct'): if self.correct not in [True, False]: raise ValueError, '''A non-text option should have a boolean as its "correct" attribute.''' def _validate_multiple_choice(self): if hasattr(self, 'options'): if hasattr(self, 'freetext') and self.freetext == False: if hasattr(self, 'correct') and self.correct not in [True, False]: raise ValueError, '''A question with multiple choice options should have a boolean rather than a regular expression as its "correct" attribute.''' option_correct = [getattr(option, 'correct') for option in self.options] option_string = [correct for correct in option_correct if type(correct) == str] if len(option_string) > 0: raise ValueError, '''A multiple choice option should have a boolean rather than a regular expression as its "correct" attribute.''' def _validate_keyboard(self): if hasattr(self, 'keyboard'): if type(self.keyboard) == list: if len(self.keyboard) != len(self.options): raise ValueError, '''List of keybindings must have as many entries as there are options in the page.''' <|code_end|> , predict the immediate next line with the help of imports: from component import Component from option import Option from speriment.utils import check_list and context (classes, functions, sometimes code) from other files: # Path: speriment/utils.py # def check_list(obj, attribute): # if hasattr(obj, attribute) and type(getattr(obj, attribute)) != list: # raise ValueError, '''{} in {} must be a list.'''.format(attribute, obj) . Output only the next line.
elif self.keyboard:
Next line prediction: <|code_start|>BACKENDS = settings.AUTHENTICATION_BACKENDS STRATEGY = getattr(settings, setting_name('STRATEGY'), 'social.strategies.django_strategy.DjangoStrategy') STORAGE = getattr(settings, setting_name('STORAGE'), 'social.apps.django_app.default.models.DjangoStorage') Strategy = module_member(STRATEGY) Storage = module_member(STORAGE) def load_strategy(*args, **kwargs): return get_strategy(BACKENDS, STRATEGY, STORAGE, *args, **kwargs) def strategy(redirect_uri=None): def decorator(func): @wraps(func) def wrapper(request, backend, *args, **kwargs): uri = redirect_uri if uri and not uri.startswith('/'): uri = reverse(redirect_uri, args=(backend,)) request.strategy = load_strategy(request=request, backend=backend, redirect_uri=uri, *args, **kwargs) return func(request, backend, *args, **kwargs) return wrapper return decorator def setting(name, default=None): try: return getattr(settings, setting_name(name)) <|code_end|> . Use current file imports: (from functools import wraps from django.conf import settings from django.core.urlresolvers import reverse from social.utils import setting_name, module_member from social.strategies.utils import get_strategy) and context including class names, function names, or small code snippets from other files: # Path: social/utils.py # def setting_name(*names): # names = [val.upper().replace('-', '_') for val in names if val] # return '_'.join((SETTING_PREFIX,) + tuple(names)) # # def module_member(name): # mod, member = name.rsplit('.', 1) # module = import_module(mod) # return getattr(module, member) . Output only the next line.
except AttributeError:
Using the snippet: <|code_start|> BACKENDS = settings.AUTHENTICATION_BACKENDS STRATEGY = getattr(settings, setting_name('STRATEGY'), 'social.strategies.django_strategy.DjangoStrategy') STORAGE = getattr(settings, setting_name('STORAGE'), 'social.apps.django_app.default.models.DjangoStorage') Strategy = module_member(STRATEGY) Storage = module_member(STORAGE) def load_strategy(*args, **kwargs): return get_strategy(BACKENDS, STRATEGY, STORAGE, *args, **kwargs) def strategy(redirect_uri=None): def decorator(func): @wraps(func) def wrapper(request, backend, *args, **kwargs): <|code_end|> , determine the next line of code. You have imports: from functools import wraps from django.conf import settings from django.core.urlresolvers import reverse from social.utils import setting_name, module_member from social.strategies.utils import get_strategy and context (class names, function names, or code) available: # Path: social/utils.py # def setting_name(*names): # names = [val.upper().replace('-', '_') for val in names if val] # return '_'.join((SETTING_PREFIX,) + tuple(names)) # # def module_member(name): # mod, member = name.rsplit('.', 1) # module = import_module(mod) # return getattr(module, member) . Output only the next line.
uri = redirect_uri
Based on the snippet: <|code_start|> tpl = tpl or BaseTemplateStrategy if not isinstance(tpl, BaseTemplateStrategy): tpl = tpl(self) self.tpl = tpl self.request = request self.storage = storage self.backends = backends if backend: self.backend_name = backend.name self.backend = backend(strategy=self, *args, **kwargs) else: self.backend_name = None self.backend = backend def setting(self, name, default=None): names = (setting_name(self.backend_name, name), setting_name(name), name) for name in names: try: return self.get_setting(name) except (AttributeError, KeyError): pass return default def start(self): # Clean any partial pipeline info before starting the process self.clean_partial_pipeline() if self.backend.uses_redirect(): return self.redirect(self.backend.auth_url()) <|code_end|> , predict the immediate next line with the help of imports: import time import random import hashlib from social.utils import setting_name from social.store import OpenIdStore and context (classes, functions, sometimes code) from other files: # Path: social/utils.py # def setting_name(*names): # names = [val.upper().replace('-', '_') for val in names if val] # return '_'.join((SETTING_PREFIX,) + tuple(names)) # # Path: social/store.py # class OpenIdStore(BaseOpenIDStore): # """Storage class""" # def __init__(self, strategy): # """Init method""" # super(OpenIdStore, self).__init__() # self.strategy = strategy # self.storage = strategy.storage # self.assoc = self.storage.association # self.nonce = self.storage.nonce # self.max_nonce_age = 6 * 60 * 60 # Six hours # # def storeAssociation(self, server_url, association): # """Store new assocition if doesn't exist""" # self.assoc.store(server_url, association) # # def removeAssociation(self, server_url, handle): # """Remove association""" # associations_ids = list(dict(self.assoc.oids(server_url, # handle)).keys()) # if associations_ids: # self.assoc.remove(associations_ids) # # def getAssociation(self, server_url, handle=None): # """Return stored assocition""" # oid_associations = self.assoc.oids(server_url, handle) # associations = [association # for assoc_id, association in oid_associations # if association.getExpiresIn() > 0] # expired = [assoc_id for assoc_id, association in oid_associations # if association.getExpiresIn() == 0] # # if expired: # clear expired associations # self.assoc.remove(expired) # # if associations: # return most recet association # return associations[0] # # def useNonce(self, server_url, timestamp, salt): # """Generate one use number and return *if* it was created""" # if abs(timestamp - time.time()) > SKEW: # return False # return self.nonce.use(server_url, timestamp, salt) . Output only the next line.
else:
Predict the next line for this snippet: <|code_start|> def session_setdefault(self, name, value): self.session_set(name, value) return self.session_get(name) def to_session(self, next, backend, *args, **kwargs): return { 'next': next, 'backend': backend.name, 'args': args, 'kwargs': kwargs } def from_session(self, session): return session['next'], session['backend'], \ session['args'], session['kwargs'] def clean_partial_pipeline(self): self.session_pop('partial_pipeline') def openid_store(self): return OpenIdStore(self) def get_pipeline(self): return self.setting('PIPELINE', ( 'social.pipeline.social_auth.social_user', 'social.pipeline.user.get_username', 'social.pipeline.user.create_user', 'social.pipeline.social_auth.associate_user', 'social.pipeline.social_auth.load_extra_data', 'social.pipeline.user.user_details' <|code_end|> with the help of current file imports: import time import random import hashlib from social.utils import setting_name from social.store import OpenIdStore and context from other files: # Path: social/utils.py # def setting_name(*names): # names = [val.upper().replace('-', '_') for val in names if val] # return '_'.join((SETTING_PREFIX,) + tuple(names)) # # Path: social/store.py # class OpenIdStore(BaseOpenIDStore): # """Storage class""" # def __init__(self, strategy): # """Init method""" # super(OpenIdStore, self).__init__() # self.strategy = strategy # self.storage = strategy.storage # self.assoc = self.storage.association # self.nonce = self.storage.nonce # self.max_nonce_age = 6 * 60 * 60 # Six hours # # def storeAssociation(self, server_url, association): # """Store new assocition if doesn't exist""" # self.assoc.store(server_url, association) # # def removeAssociation(self, server_url, handle): # """Remove association""" # associations_ids = list(dict(self.assoc.oids(server_url, # handle)).keys()) # if associations_ids: # self.assoc.remove(associations_ids) # # def getAssociation(self, server_url, handle=None): # """Return stored assocition""" # oid_associations = self.assoc.oids(server_url, handle) # associations = [association # for assoc_id, association in oid_associations # if association.getExpiresIn() > 0] # expired = [assoc_id for assoc_id, association in oid_associations # if association.getExpiresIn() == 0] # # if expired: # clear expired associations # self.assoc.remove(expired) # # if associations: # return most recet association # return associations[0] # # def useNonce(self, server_url, timestamp, salt): # """Generate one use number and return *if* it was created""" # if abs(timestamp - time.time()) > SKEW: # return False # return self.nonce.use(server_url, timestamp, salt) , which may contain function names, class names, or code. Output only the next line.
))
Using the snippet: <|code_start|> username = details['username'] else: username = uuid4().hex short_username = username[:max_length - uuid_length] final_username = username[:max_length] if do_clean: final_username = storage.user.clean_username(final_username) if do_slugify: final_username = slugify(final_username) # Generate a unique username for current user using username # as base but adding a unique hash at the end. Original # username is cut to avoid any field max_length. while storage.user.user_exists(final_username): username = short_username + uuid4().hex[:uuid_length] final_username = username[:max_length] if do_clean: final_username = storage.user.clean_username(final_username) if do_slugify: final_username = slugify(final_username) else: final_username = storage.user.get_username(user) return {'username': final_username} def create_user(strategy, details, response, uid, username, user=None, *args, **kwargs): if user or not username: return None <|code_end|> , determine the next line of code. You have imports: from uuid import uuid4 from social.utils import slugify and context (class names, function names, or code) available: # Path: social/utils.py # def slugify(value): # """Converts to lowercase, removes non-word characters (alphanumerics # and underscores) and converts spaces to hyphens. Also strips leading # and trailing whitespace.""" # value = unicodedata.normalize('NFKD', value) \ # .encode('ascii', 'ignore') \ # .decode('ascii') # value = re.sub('[^\w\s-]', '', value).strip().lower() # return re.sub('[-\s]+', '-', value) . Output only the next line.
return {
Continue the code snippet: <|code_start|> def do_auth(strategy, redirect_name='next'): # Save any defined next value into session data = strategy.request_data(merge=False) # Save extra data into session. for field_name in strategy.setting('FIELDS_STORED_IN_SESSION', []): if field_name in data: strategy.session_set(field_name, data[field_name]) if redirect_name in data: # Check and sanitize a user-defined GET/POST next field value redirect_uri = data[redirect_name] if strategy.setting('SANITIZE_REDIRECTS', True): redirect_uri = sanitize_redirect(strategy.request_host(), redirect_uri) strategy.session_set( redirect_name, redirect_uri or strategy.setting('LOGIN_REDIRECT_URL') ) return strategy.start() def do_complete(strategy, login, user=None, redirect_name='next', *args, **kwargs): # pop redirect value before the session is trashed on login() data = strategy.request_data() <|code_end|> . Use current file imports: from social.p3 import quote from social.utils import sanitize_redirect, user_is_authenticated, \ user_is_active and context (classes, functions, or code) from other files: # Path: social/utils.py # def sanitize_redirect(host, redirect_to): # """ # Given the hostname and an untrusted URL to redirect to, # this method tests it to make sure it isn't garbage/harmful # and returns it, else returns None, similar as how's it done # on django.contrib.auth.views. # """ # # Quick sanity check. # if not redirect_to or not isinstance(redirect_to, six.string_types): # return None # # # Heavier security check, don't allow redirection to a different host. # netloc = urlparse(redirect_to)[1] # if netloc and netloc != host: # return None # return redirect_to # # def user_is_authenticated(user): # if user and hasattr(user, 'is_authenticated'): # if isinstance(user.is_authenticated, collections.Callable): # authenticated = user.is_authenticated() # else: # authenticated = user.is_authenticated # elif user: # authenticated = True # else: # authenticated = False # return authenticated # # def user_is_active(user): # if user and hasattr(user, 'is_active'): # if isinstance(user.is_active, collections.Callable): # is_active = user.is_active() # else: # is_active = user.is_active # elif user: # is_active = True # else: # is_active = False # return is_active . Output only the next line.
redirect_value = strategy.session_get(redirect_name, '') or \
Next line prediction: <|code_start|> redirect_uri) strategy.session_set( redirect_name, redirect_uri or strategy.setting('LOGIN_REDIRECT_URL') ) return strategy.start() def do_complete(strategy, login, user=None, redirect_name='next', *args, **kwargs): # pop redirect value before the session is trashed on login() data = strategy.request_data() redirect_value = strategy.session_get(redirect_name, '') or \ data.get(redirect_name, '') is_authenticated = user_is_authenticated(user) user = is_authenticated and user or None default_redirect = strategy.setting('LOGIN_REDIRECT_URL') url = default_redirect login_error_url = strategy.setting('LOGIN_ERROR_URL') or \ strategy.setting('LOGIN_URL') if strategy.session_get('partial_pipeline'): idx, backend, xargs, xkwargs = strategy.from_session( strategy.session_pop('partial_pipeline') ) if backend == strategy.backend_name: kwargs = kwargs.copy() kwargs.setdefault('user', user) kwargs.update(xkwargs) user = strategy.continue_pipeline(pipeline_index=idx, <|code_end|> . Use current file imports: (from social.p3 import quote from social.utils import sanitize_redirect, user_is_authenticated, \ user_is_active) and context including class names, function names, or small code snippets from other files: # Path: social/utils.py # def sanitize_redirect(host, redirect_to): # """ # Given the hostname and an untrusted URL to redirect to, # this method tests it to make sure it isn't garbage/harmful # and returns it, else returns None, similar as how's it done # on django.contrib.auth.views. # """ # # Quick sanity check. # if not redirect_to or not isinstance(redirect_to, six.string_types): # return None # # # Heavier security check, don't allow redirection to a different host. # netloc = urlparse(redirect_to)[1] # if netloc and netloc != host: # return None # return redirect_to # # def user_is_authenticated(user): # if user and hasattr(user, 'is_authenticated'): # if isinstance(user.is_authenticated, collections.Callable): # authenticated = user.is_authenticated() # else: # authenticated = user.is_authenticated # elif user: # authenticated = True # else: # authenticated = False # return authenticated # # def user_is_active(user): # if user and hasattr(user, 'is_active'): # if isinstance(user.is_active, collections.Callable): # is_active = user.is_active() # else: # is_active = user.is_active # elif user: # is_active = True # else: # is_active = False # return is_active . Output only the next line.
*xargs, **xkwargs)
Predict the next line after this snippet: <|code_start|> def do_complete(strategy, login, user=None, redirect_name='next', *args, **kwargs): # pop redirect value before the session is trashed on login() data = strategy.request_data() redirect_value = strategy.session_get(redirect_name, '') or \ data.get(redirect_name, '') is_authenticated = user_is_authenticated(user) user = is_authenticated and user or None default_redirect = strategy.setting('LOGIN_REDIRECT_URL') url = default_redirect login_error_url = strategy.setting('LOGIN_ERROR_URL') or \ strategy.setting('LOGIN_URL') if strategy.session_get('partial_pipeline'): idx, backend, xargs, xkwargs = strategy.from_session( strategy.session_pop('partial_pipeline') ) if backend == strategy.backend_name: kwargs = kwargs.copy() kwargs.setdefault('user', user) kwargs.update(xkwargs) user = strategy.continue_pipeline(pipeline_index=idx, *xargs, **xkwargs) else: strategy.clean_partial_pipeline() user = strategy.complete(user=user, request=strategy.request, *args, **kwargs) else: <|code_end|> using the current file's imports: from social.p3 import quote from social.utils import sanitize_redirect, user_is_authenticated, \ user_is_active and any relevant context from other files: # Path: social/utils.py # def sanitize_redirect(host, redirect_to): # """ # Given the hostname and an untrusted URL to redirect to, # this method tests it to make sure it isn't garbage/harmful # and returns it, else returns None, similar as how's it done # on django.contrib.auth.views. # """ # # Quick sanity check. # if not redirect_to or not isinstance(redirect_to, six.string_types): # return None # # # Heavier security check, don't allow redirection to a different host. # netloc = urlparse(redirect_to)[1] # if netloc and netloc != host: # return None # return redirect_to # # def user_is_authenticated(user): # if user and hasattr(user, 'is_authenticated'): # if isinstance(user.is_authenticated, collections.Callable): # authenticated = user.is_authenticated() # else: # authenticated = user.is_authenticated # elif user: # authenticated = True # else: # authenticated = False # return authenticated # # def user_is_active(user): # if user and hasattr(user, 'is_active'): # if isinstance(user.is_active, collections.Callable): # is_active = user.is_active() # else: # is_active = user.is_active # elif user: # is_active = True # else: # is_active = False # return is_active . Output only the next line.
user = strategy.complete(user=user, request=strategy.request,
Given the code snippet: <|code_start|>""" Base backends classes. This module defines base classes needed to define custom OpenID or OAuth1/2 auth services from third parties. This customs must subclass an Auth and a Backend class, check current implementation for examples. Also the modules *must* define a BACKENDS dictionary with the backend name (which is used for URLs matching) and Auth class, otherwise it won't be enabled. """ class BaseAuth(object): """A django.contrib.auth backend that authenticates the user based on a authentication provider response""" name = '' # provider name, it's stored in database supports_inactive_user = False # Django auth ID_KEY = None def __init__(self, strategy=None, redirect_uri=None, *args, **kwargs): self.strategy = strategy self.redirect_uri = redirect_uri self.data = {} if strategy: self.data = self.strategy.request_data() <|code_end|> , generate the next line using the imports in this file: from requests import request from social.utils import module_member, parse_qs and context (functions, classes, or occasionally code) from other files: # Path: social/utils.py # def module_member(name): # mod, member = name.rsplit('.', 1) # module = import_module(mod) # return getattr(module, member) # # def parse_qs(value): # """Like urlparse.parse_qs but transform list values to single items""" # return drop_lists(battery_parse_qs(value)) . Output only the next line.
self.redirect_uri = self.strategy.build_absolute_uri(
Using the snippet: <|code_start|> def request_token_extra_arguments(self): """Return extra arguments needed on request-token process""" return self.setting('REQUEST_TOKEN_EXTRA_ARGUMENTS', {}) def auth_extra_arguments(self): """Return extra arguments needed on auth process. The defaults can be overriden by GET parameters.""" extra_arguments = self.setting('AUTH_EXTRA_ARGUMENTS', {}) extra_arguments.update((key, self.data[key]) for key in extra_arguments if key in self.data) return extra_arguments def uses_redirect(self): """Return True if this provider uses redirect url method, otherwise return false.""" return True def request(self, url, method='GET', *args, **kwargs): kwargs.setdefault('timeout', self.setting('REQUESTS_TIMEOUT') or self.setting('URLOPEN_TIMEOUT')) response = request(method, url, *args, **kwargs) response.raise_for_status() return response def get_json(self, url, *args, **kwargs): return self.request(url, *args, **kwargs).json() def get_querystring(self, url, *args, **kwargs): return parse_qs(self.request(url, *args, **kwargs).text) <|code_end|> , determine the next line of code. You have imports: from requests import request from social.utils import module_member, parse_qs and context (class names, function names, or code) available: # Path: social/utils.py # def module_member(name): # mod, member = name.rsplit('.', 1) # module = import_module(mod) # return getattr(module, member) # # def parse_qs(value): # """Like urlparse.parse_qs but transform list values to single items""" # return drop_lists(battery_parse_qs(value)) . Output only the next line.
def get_key_and_secret(self):
Based on the snippet: <|code_start|> DEFAULT_REDIRECT = setting('LOGIN_REDIRECT_URL') LOGIN_ERROR_URL = setting('LOGIN_ERROR_URL', setting('LOGIN_URL')) @strategy('social:complete') def auth(request, backend): return do_auth(request.strategy, redirect_name=REDIRECT_FIELD_NAME) @csrf_exempt @strategy('social:complete') def complete(request, backend, *args, **kwargs): """Authentication complete view, override this view if transaction management doesn't suit your needs.""" return do_complete(request.strategy, _do_login, request.user, redirect_name=REDIRECT_FIELD_NAME, *args, **kwargs) @login_required @strategy() @require_POST @csrf_protect <|code_end|> , predict the immediate next line with the help of imports: from django.contrib.auth import login, REDIRECT_FIELD_NAME, BACKEND_SESSION_KEY from django.contrib.auth.decorators import login_required from django.views.decorators.csrf import csrf_exempt, csrf_protect from django.views.decorators.http import require_POST from social.actions import do_auth, do_complete, do_disconnect from social.apps.django_app.utils import strategy, setting, BackendWrapper and context (classes, functions, sometimes code) from other files: # Path: social/actions.py # def do_auth(strategy, redirect_name='next'): # # Save any defined next value into session # data = strategy.request_data(merge=False) # # Save extra data into session. # for field_name in strategy.setting('FIELDS_STORED_IN_SESSION', []): # if field_name in data: # strategy.session_set(field_name, data[field_name]) # # if redirect_name in data: # # Check and sanitize a user-defined GET/POST next field value # redirect_uri = data[redirect_name] # if strategy.setting('SANITIZE_REDIRECTS', True): # redirect_uri = sanitize_redirect(strategy.request_host(), # redirect_uri) # strategy.session_set( # redirect_name, # redirect_uri or strategy.setting('LOGIN_REDIRECT_URL') # ) # return strategy.start() # # def do_complete(strategy, login, user=None, redirect_name='next', # *args, **kwargs): # # pop redirect value before the session is trashed on login() # data = strategy.request_data() # redirect_value = strategy.session_get(redirect_name, '') or \ # data.get(redirect_name, '') # # is_authenticated = user_is_authenticated(user) # user = is_authenticated and user or None # default_redirect = strategy.setting('LOGIN_REDIRECT_URL') # url = default_redirect # login_error_url = strategy.setting('LOGIN_ERROR_URL') or \ # strategy.setting('LOGIN_URL') # if strategy.session_get('partial_pipeline'): # idx, backend, xargs, xkwargs = strategy.from_session( # strategy.session_pop('partial_pipeline') # ) # if backend == strategy.backend_name: # kwargs = kwargs.copy() # kwargs.setdefault('user', user) # kwargs.update(xkwargs) # user = strategy.continue_pipeline(pipeline_index=idx, # *xargs, **xkwargs) # else: # strategy.clean_partial_pipeline() # user = strategy.complete(user=user, request=strategy.request, # *args, **kwargs) # else: # user = strategy.complete(user=user, request=strategy.request, # *args, **kwargs) # # if strategy.is_response(user): # return user # # if is_authenticated: # if not user: # url = redirect_value or default_redirect # else: # url = redirect_value or \ # strategy.setting('NEW_ASSOCIATION_REDIRECT_URL') or \ # default_redirect # elif user: # if user_is_active(user): # # catch is_new/social_user in case login() resets the instance # is_new = getattr(user, 'is_new', False) # social_user = user.social_user # login(strategy, user) # # store last login backend name in session # strategy.session_set('social_auth_last_login_backend', # social_user.provider) # # # Remove possible redirect URL from session, if this is a new # # account, send him to the new-users-page if defined. # new_user_redirect = strategy.setting('NEW_USER_REDIRECT_URL') # if new_user_redirect and is_new: # url = new_user_redirect # else: # url = redirect_value or default_redirect # else: # url = strategy.setting('INACTIVE_USER_URL', login_error_url) # else: # url = login_error_url # # if redirect_value and redirect_value != url: # redirect_value = quote(redirect_value) # url += ('?' in url and '&' or '?') + \ # '%s=%s' % (redirect_name, redirect_value) # if url == '/': # url = '/' + user.username # return strategy.redirect(url) # # def do_disconnect(strategy, user, association_id=None, redirect_name='next'): # strategy.disconnect(user=user, association_id=association_id) # data = strategy.request_data() # return strategy.redirect(data.get(redirect_name, '') or # strategy.setting('DISCONNECT_REDIRECT_URL') or # strategy.setting('LOGIN_REDIRECT_URL')) # # Path: social/apps/django_app/utils.py # def strategy(redirect_uri=None): # def decorator(func): # @wraps(func) # def wrapper(request, backend, *args, **kwargs): # uri = redirect_uri # if uri and not uri.startswith('/'): # uri = reverse(redirect_uri, args=(backend,)) # request.strategy = load_strategy(request=request, backend=backend, # redirect_uri=uri, *args, **kwargs) # return func(request, backend, *args, **kwargs) # return wrapper # return decorator # # def setting(name, default=None): # try: # return getattr(settings, setting_name(name)) # except AttributeError: # return getattr(settings, name, default) # # class BackendWrapper(object): # def get_user(self, user_id): # return Strategy(storage=Storage).get_user(user_id) . Output only the next line.
def disconnect(request, backend, association_id=None):
Continue the code snippet: <|code_start|> DEFAULT_REDIRECT = setting('LOGIN_REDIRECT_URL') LOGIN_ERROR_URL = setting('LOGIN_ERROR_URL', setting('LOGIN_URL')) @strategy('social:complete') def auth(request, backend): return do_auth(request.strategy, redirect_name=REDIRECT_FIELD_NAME) @csrf_exempt @strategy('social:complete') def complete(request, backend, *args, **kwargs): """Authentication complete view, override this view if transaction management doesn't suit your needs.""" return do_complete(request.strategy, _do_login, request.user, <|code_end|> . Use current file imports: from django.contrib.auth import login, REDIRECT_FIELD_NAME, BACKEND_SESSION_KEY from django.contrib.auth.decorators import login_required from django.views.decorators.csrf import csrf_exempt, csrf_protect from django.views.decorators.http import require_POST from social.actions import do_auth, do_complete, do_disconnect from social.apps.django_app.utils import strategy, setting, BackendWrapper and context (classes, functions, or code) from other files: # Path: social/actions.py # def do_auth(strategy, redirect_name='next'): # # Save any defined next value into session # data = strategy.request_data(merge=False) # # Save extra data into session. # for field_name in strategy.setting('FIELDS_STORED_IN_SESSION', []): # if field_name in data: # strategy.session_set(field_name, data[field_name]) # # if redirect_name in data: # # Check and sanitize a user-defined GET/POST next field value # redirect_uri = data[redirect_name] # if strategy.setting('SANITIZE_REDIRECTS', True): # redirect_uri = sanitize_redirect(strategy.request_host(), # redirect_uri) # strategy.session_set( # redirect_name, # redirect_uri or strategy.setting('LOGIN_REDIRECT_URL') # ) # return strategy.start() # # def do_complete(strategy, login, user=None, redirect_name='next', # *args, **kwargs): # # pop redirect value before the session is trashed on login() # data = strategy.request_data() # redirect_value = strategy.session_get(redirect_name, '') or \ # data.get(redirect_name, '') # # is_authenticated = user_is_authenticated(user) # user = is_authenticated and user or None # default_redirect = strategy.setting('LOGIN_REDIRECT_URL') # url = default_redirect # login_error_url = strategy.setting('LOGIN_ERROR_URL') or \ # strategy.setting('LOGIN_URL') # if strategy.session_get('partial_pipeline'): # idx, backend, xargs, xkwargs = strategy.from_session( # strategy.session_pop('partial_pipeline') # ) # if backend == strategy.backend_name: # kwargs = kwargs.copy() # kwargs.setdefault('user', user) # kwargs.update(xkwargs) # user = strategy.continue_pipeline(pipeline_index=idx, # *xargs, **xkwargs) # else: # strategy.clean_partial_pipeline() # user = strategy.complete(user=user, request=strategy.request, # *args, **kwargs) # else: # user = strategy.complete(user=user, request=strategy.request, # *args, **kwargs) # # if strategy.is_response(user): # return user # # if is_authenticated: # if not user: # url = redirect_value or default_redirect # else: # url = redirect_value or \ # strategy.setting('NEW_ASSOCIATION_REDIRECT_URL') or \ # default_redirect # elif user: # if user_is_active(user): # # catch is_new/social_user in case login() resets the instance # is_new = getattr(user, 'is_new', False) # social_user = user.social_user # login(strategy, user) # # store last login backend name in session # strategy.session_set('social_auth_last_login_backend', # social_user.provider) # # # Remove possible redirect URL from session, if this is a new # # account, send him to the new-users-page if defined. # new_user_redirect = strategy.setting('NEW_USER_REDIRECT_URL') # if new_user_redirect and is_new: # url = new_user_redirect # else: # url = redirect_value or default_redirect # else: # url = strategy.setting('INACTIVE_USER_URL', login_error_url) # else: # url = login_error_url # # if redirect_value and redirect_value != url: # redirect_value = quote(redirect_value) # url += ('?' in url and '&' or '?') + \ # '%s=%s' % (redirect_name, redirect_value) # if url == '/': # url = '/' + user.username # return strategy.redirect(url) # # def do_disconnect(strategy, user, association_id=None, redirect_name='next'): # strategy.disconnect(user=user, association_id=association_id) # data = strategy.request_data() # return strategy.redirect(data.get(redirect_name, '') or # strategy.setting('DISCONNECT_REDIRECT_URL') or # strategy.setting('LOGIN_REDIRECT_URL')) # # Path: social/apps/django_app/utils.py # def strategy(redirect_uri=None): # def decorator(func): # @wraps(func) # def wrapper(request, backend, *args, **kwargs): # uri = redirect_uri # if uri and not uri.startswith('/'): # uri = reverse(redirect_uri, args=(backend,)) # request.strategy = load_strategy(request=request, backend=backend, # redirect_uri=uri, *args, **kwargs) # return func(request, backend, *args, **kwargs) # return wrapper # return decorator # # def setting(name, default=None): # try: # return getattr(settings, setting_name(name)) # except AttributeError: # return getattr(settings, name, default) # # class BackendWrapper(object): # def get_user(self, user_id): # return Strategy(storage=Storage).get_user(user_id) . Output only the next line.
redirect_name=REDIRECT_FIELD_NAME, *args, **kwargs)
Using the snippet: <|code_start|> DEFAULT_REDIRECT = setting('LOGIN_REDIRECT_URL') LOGIN_ERROR_URL = setting('LOGIN_ERROR_URL', setting('LOGIN_URL')) @strategy('social:complete') def auth(request, backend): return do_auth(request.strategy, redirect_name=REDIRECT_FIELD_NAME) @csrf_exempt @strategy('social:complete') def complete(request, backend, *args, **kwargs): """Authentication complete view, override this view if transaction management doesn't suit your needs.""" return do_complete(request.strategy, _do_login, request.user, redirect_name=REDIRECT_FIELD_NAME, *args, **kwargs) @login_required @strategy() @require_POST @csrf_protect <|code_end|> , determine the next line of code. You have imports: from django.contrib.auth import login, REDIRECT_FIELD_NAME, BACKEND_SESSION_KEY from django.contrib.auth.decorators import login_required from django.views.decorators.csrf import csrf_exempt, csrf_protect from django.views.decorators.http import require_POST from social.actions import do_auth, do_complete, do_disconnect from social.apps.django_app.utils import strategy, setting, BackendWrapper and context (class names, function names, or code) available: # Path: social/actions.py # def do_auth(strategy, redirect_name='next'): # # Save any defined next value into session # data = strategy.request_data(merge=False) # # Save extra data into session. # for field_name in strategy.setting('FIELDS_STORED_IN_SESSION', []): # if field_name in data: # strategy.session_set(field_name, data[field_name]) # # if redirect_name in data: # # Check and sanitize a user-defined GET/POST next field value # redirect_uri = data[redirect_name] # if strategy.setting('SANITIZE_REDIRECTS', True): # redirect_uri = sanitize_redirect(strategy.request_host(), # redirect_uri) # strategy.session_set( # redirect_name, # redirect_uri or strategy.setting('LOGIN_REDIRECT_URL') # ) # return strategy.start() # # def do_complete(strategy, login, user=None, redirect_name='next', # *args, **kwargs): # # pop redirect value before the session is trashed on login() # data = strategy.request_data() # redirect_value = strategy.session_get(redirect_name, '') or \ # data.get(redirect_name, '') # # is_authenticated = user_is_authenticated(user) # user = is_authenticated and user or None # default_redirect = strategy.setting('LOGIN_REDIRECT_URL') # url = default_redirect # login_error_url = strategy.setting('LOGIN_ERROR_URL') or \ # strategy.setting('LOGIN_URL') # if strategy.session_get('partial_pipeline'): # idx, backend, xargs, xkwargs = strategy.from_session( # strategy.session_pop('partial_pipeline') # ) # if backend == strategy.backend_name: # kwargs = kwargs.copy() # kwargs.setdefault('user', user) # kwargs.update(xkwargs) # user = strategy.continue_pipeline(pipeline_index=idx, # *xargs, **xkwargs) # else: # strategy.clean_partial_pipeline() # user = strategy.complete(user=user, request=strategy.request, # *args, **kwargs) # else: # user = strategy.complete(user=user, request=strategy.request, # *args, **kwargs) # # if strategy.is_response(user): # return user # # if is_authenticated: # if not user: # url = redirect_value or default_redirect # else: # url = redirect_value or \ # strategy.setting('NEW_ASSOCIATION_REDIRECT_URL') or \ # default_redirect # elif user: # if user_is_active(user): # # catch is_new/social_user in case login() resets the instance # is_new = getattr(user, 'is_new', False) # social_user = user.social_user # login(strategy, user) # # store last login backend name in session # strategy.session_set('social_auth_last_login_backend', # social_user.provider) # # # Remove possible redirect URL from session, if this is a new # # account, send him to the new-users-page if defined. # new_user_redirect = strategy.setting('NEW_USER_REDIRECT_URL') # if new_user_redirect and is_new: # url = new_user_redirect # else: # url = redirect_value or default_redirect # else: # url = strategy.setting('INACTIVE_USER_URL', login_error_url) # else: # url = login_error_url # # if redirect_value and redirect_value != url: # redirect_value = quote(redirect_value) # url += ('?' in url and '&' or '?') + \ # '%s=%s' % (redirect_name, redirect_value) # if url == '/': # url = '/' + user.username # return strategy.redirect(url) # # def do_disconnect(strategy, user, association_id=None, redirect_name='next'): # strategy.disconnect(user=user, association_id=association_id) # data = strategy.request_data() # return strategy.redirect(data.get(redirect_name, '') or # strategy.setting('DISCONNECT_REDIRECT_URL') or # strategy.setting('LOGIN_REDIRECT_URL')) # # Path: social/apps/django_app/utils.py # def strategy(redirect_uri=None): # def decorator(func): # @wraps(func) # def wrapper(request, backend, *args, **kwargs): # uri = redirect_uri # if uri and not uri.startswith('/'): # uri = reverse(redirect_uri, args=(backend,)) # request.strategy = load_strategy(request=request, backend=backend, # redirect_uri=uri, *args, **kwargs) # return func(request, backend, *args, **kwargs) # return wrapper # return decorator # # def setting(name, default=None): # try: # return getattr(settings, setting_name(name)) # except AttributeError: # return getattr(settings, name, default) # # class BackendWrapper(object): # def get_user(self, user_id): # return Strategy(storage=Storage).get_user(user_id) . Output only the next line.
def disconnect(request, backend, association_id=None):
Using the snippet: <|code_start|> DEFAULT_REDIRECT = setting('LOGIN_REDIRECT_URL') LOGIN_ERROR_URL = setting('LOGIN_ERROR_URL', setting('LOGIN_URL')) @strategy('social:complete') def auth(request, backend): return do_auth(request.strategy, redirect_name=REDIRECT_FIELD_NAME) @csrf_exempt @strategy('social:complete') def complete(request, backend, *args, **kwargs): """Authentication complete view, override this view if transaction management doesn't suit your needs.""" return do_complete(request.strategy, _do_login, request.user, redirect_name=REDIRECT_FIELD_NAME, *args, **kwargs) <|code_end|> , determine the next line of code. You have imports: from django.contrib.auth import login, REDIRECT_FIELD_NAME, BACKEND_SESSION_KEY from django.contrib.auth.decorators import login_required from django.views.decorators.csrf import csrf_exempt, csrf_protect from django.views.decorators.http import require_POST from social.actions import do_auth, do_complete, do_disconnect from social.apps.django_app.utils import strategy, setting, BackendWrapper and context (class names, function names, or code) available: # Path: social/actions.py # def do_auth(strategy, redirect_name='next'): # # Save any defined next value into session # data = strategy.request_data(merge=False) # # Save extra data into session. # for field_name in strategy.setting('FIELDS_STORED_IN_SESSION', []): # if field_name in data: # strategy.session_set(field_name, data[field_name]) # # if redirect_name in data: # # Check and sanitize a user-defined GET/POST next field value # redirect_uri = data[redirect_name] # if strategy.setting('SANITIZE_REDIRECTS', True): # redirect_uri = sanitize_redirect(strategy.request_host(), # redirect_uri) # strategy.session_set( # redirect_name, # redirect_uri or strategy.setting('LOGIN_REDIRECT_URL') # ) # return strategy.start() # # def do_complete(strategy, login, user=None, redirect_name='next', # *args, **kwargs): # # pop redirect value before the session is trashed on login() # data = strategy.request_data() # redirect_value = strategy.session_get(redirect_name, '') or \ # data.get(redirect_name, '') # # is_authenticated = user_is_authenticated(user) # user = is_authenticated and user or None # default_redirect = strategy.setting('LOGIN_REDIRECT_URL') # url = default_redirect # login_error_url = strategy.setting('LOGIN_ERROR_URL') or \ # strategy.setting('LOGIN_URL') # if strategy.session_get('partial_pipeline'): # idx, backend, xargs, xkwargs = strategy.from_session( # strategy.session_pop('partial_pipeline') # ) # if backend == strategy.backend_name: # kwargs = kwargs.copy() # kwargs.setdefault('user', user) # kwargs.update(xkwargs) # user = strategy.continue_pipeline(pipeline_index=idx, # *xargs, **xkwargs) # else: # strategy.clean_partial_pipeline() # user = strategy.complete(user=user, request=strategy.request, # *args, **kwargs) # else: # user = strategy.complete(user=user, request=strategy.request, # *args, **kwargs) # # if strategy.is_response(user): # return user # # if is_authenticated: # if not user: # url = redirect_value or default_redirect # else: # url = redirect_value or \ # strategy.setting('NEW_ASSOCIATION_REDIRECT_URL') or \ # default_redirect # elif user: # if user_is_active(user): # # catch is_new/social_user in case login() resets the instance # is_new = getattr(user, 'is_new', False) # social_user = user.social_user # login(strategy, user) # # store last login backend name in session # strategy.session_set('social_auth_last_login_backend', # social_user.provider) # # # Remove possible redirect URL from session, if this is a new # # account, send him to the new-users-page if defined. # new_user_redirect = strategy.setting('NEW_USER_REDIRECT_URL') # if new_user_redirect and is_new: # url = new_user_redirect # else: # url = redirect_value or default_redirect # else: # url = strategy.setting('INACTIVE_USER_URL', login_error_url) # else: # url = login_error_url # # if redirect_value and redirect_value != url: # redirect_value = quote(redirect_value) # url += ('?' in url and '&' or '?') + \ # '%s=%s' % (redirect_name, redirect_value) # if url == '/': # url = '/' + user.username # return strategy.redirect(url) # # def do_disconnect(strategy, user, association_id=None, redirect_name='next'): # strategy.disconnect(user=user, association_id=association_id) # data = strategy.request_data() # return strategy.redirect(data.get(redirect_name, '') or # strategy.setting('DISCONNECT_REDIRECT_URL') or # strategy.setting('LOGIN_REDIRECT_URL')) # # Path: social/apps/django_app/utils.py # def strategy(redirect_uri=None): # def decorator(func): # @wraps(func) # def wrapper(request, backend, *args, **kwargs): # uri = redirect_uri # if uri and not uri.startswith('/'): # uri = reverse(redirect_uri, args=(backend,)) # request.strategy = load_strategy(request=request, backend=backend, # redirect_uri=uri, *args, **kwargs) # return func(request, backend, *args, **kwargs) # return wrapper # return decorator # # def setting(name, default=None): # try: # return getattr(settings, setting_name(name)) # except AttributeError: # return getattr(settings, name, default) # # class BackendWrapper(object): # def get_user(self, user_id): # return Strategy(storage=Storage).get_user(user_id) . Output only the next line.
@login_required
Based on the snippet: <|code_start|> DEFAULT_REDIRECT = setting('LOGIN_REDIRECT_URL') LOGIN_ERROR_URL = setting('LOGIN_ERROR_URL', setting('LOGIN_URL')) @strategy('social:complete') def auth(request, backend): return do_auth(request.strategy, redirect_name=REDIRECT_FIELD_NAME) @csrf_exempt @strategy('social:complete') def complete(request, backend, *args, **kwargs): """Authentication complete view, override this view if transaction management doesn't suit your needs.""" return do_complete(request.strategy, _do_login, request.user, <|code_end|> , predict the immediate next line with the help of imports: from django.contrib.auth import login, REDIRECT_FIELD_NAME, BACKEND_SESSION_KEY from django.contrib.auth.decorators import login_required from django.views.decorators.csrf import csrf_exempt, csrf_protect from django.views.decorators.http import require_POST from social.actions import do_auth, do_complete, do_disconnect from social.apps.django_app.utils import strategy, setting, BackendWrapper and context (classes, functions, sometimes code) from other files: # Path: social/actions.py # def do_auth(strategy, redirect_name='next'): # # Save any defined next value into session # data = strategy.request_data(merge=False) # # Save extra data into session. # for field_name in strategy.setting('FIELDS_STORED_IN_SESSION', []): # if field_name in data: # strategy.session_set(field_name, data[field_name]) # # if redirect_name in data: # # Check and sanitize a user-defined GET/POST next field value # redirect_uri = data[redirect_name] # if strategy.setting('SANITIZE_REDIRECTS', True): # redirect_uri = sanitize_redirect(strategy.request_host(), # redirect_uri) # strategy.session_set( # redirect_name, # redirect_uri or strategy.setting('LOGIN_REDIRECT_URL') # ) # return strategy.start() # # def do_complete(strategy, login, user=None, redirect_name='next', # *args, **kwargs): # # pop redirect value before the session is trashed on login() # data = strategy.request_data() # redirect_value = strategy.session_get(redirect_name, '') or \ # data.get(redirect_name, '') # # is_authenticated = user_is_authenticated(user) # user = is_authenticated and user or None # default_redirect = strategy.setting('LOGIN_REDIRECT_URL') # url = default_redirect # login_error_url = strategy.setting('LOGIN_ERROR_URL') or \ # strategy.setting('LOGIN_URL') # if strategy.session_get('partial_pipeline'): # idx, backend, xargs, xkwargs = strategy.from_session( # strategy.session_pop('partial_pipeline') # ) # if backend == strategy.backend_name: # kwargs = kwargs.copy() # kwargs.setdefault('user', user) # kwargs.update(xkwargs) # user = strategy.continue_pipeline(pipeline_index=idx, # *xargs, **xkwargs) # else: # strategy.clean_partial_pipeline() # user = strategy.complete(user=user, request=strategy.request, # *args, **kwargs) # else: # user = strategy.complete(user=user, request=strategy.request, # *args, **kwargs) # # if strategy.is_response(user): # return user # # if is_authenticated: # if not user: # url = redirect_value or default_redirect # else: # url = redirect_value or \ # strategy.setting('NEW_ASSOCIATION_REDIRECT_URL') or \ # default_redirect # elif user: # if user_is_active(user): # # catch is_new/social_user in case login() resets the instance # is_new = getattr(user, 'is_new', False) # social_user = user.social_user # login(strategy, user) # # store last login backend name in session # strategy.session_set('social_auth_last_login_backend', # social_user.provider) # # # Remove possible redirect URL from session, if this is a new # # account, send him to the new-users-page if defined. # new_user_redirect = strategy.setting('NEW_USER_REDIRECT_URL') # if new_user_redirect and is_new: # url = new_user_redirect # else: # url = redirect_value or default_redirect # else: # url = strategy.setting('INACTIVE_USER_URL', login_error_url) # else: # url = login_error_url # # if redirect_value and redirect_value != url: # redirect_value = quote(redirect_value) # url += ('?' in url and '&' or '?') + \ # '%s=%s' % (redirect_name, redirect_value) # if url == '/': # url = '/' + user.username # return strategy.redirect(url) # # def do_disconnect(strategy, user, association_id=None, redirect_name='next'): # strategy.disconnect(user=user, association_id=association_id) # data = strategy.request_data() # return strategy.redirect(data.get(redirect_name, '') or # strategy.setting('DISCONNECT_REDIRECT_URL') or # strategy.setting('LOGIN_REDIRECT_URL')) # # Path: social/apps/django_app/utils.py # def strategy(redirect_uri=None): # def decorator(func): # @wraps(func) # def wrapper(request, backend, *args, **kwargs): # uri = redirect_uri # if uri and not uri.startswith('/'): # uri = reverse(redirect_uri, args=(backend,)) # request.strategy = load_strategy(request=request, backend=backend, # redirect_uri=uri, *args, **kwargs) # return func(request, backend, *args, **kwargs) # return wrapper # return decorator # # def setting(name, default=None): # try: # return getattr(settings, setting_name(name)) # except AttributeError: # return getattr(settings, name, default) # # class BackendWrapper(object): # def get_user(self, user_id): # return Strategy(storage=Storage).get_user(user_id) . Output only the next line.
redirect_name=REDIRECT_FIELD_NAME, *args, **kwargs)
Based on the snippet: <|code_start|> DEFAULT_REDIRECT = setting('LOGIN_REDIRECT_URL') LOGIN_ERROR_URL = setting('LOGIN_ERROR_URL', setting('LOGIN_URL')) @strategy('social:complete') def auth(request, backend): return do_auth(request.strategy, redirect_name=REDIRECT_FIELD_NAME) @csrf_exempt @strategy('social:complete') def complete(request, backend, *args, **kwargs): """Authentication complete view, override this view if transaction management doesn't suit your needs.""" return do_complete(request.strategy, _do_login, request.user, redirect_name=REDIRECT_FIELD_NAME, *args, **kwargs) @login_required @strategy() <|code_end|> , predict the immediate next line with the help of imports: from django.contrib.auth import login, REDIRECT_FIELD_NAME, BACKEND_SESSION_KEY from django.contrib.auth.decorators import login_required from django.views.decorators.csrf import csrf_exempt, csrf_protect from django.views.decorators.http import require_POST from social.actions import do_auth, do_complete, do_disconnect from social.apps.django_app.utils import strategy, setting, BackendWrapper and context (classes, functions, sometimes code) from other files: # Path: social/actions.py # def do_auth(strategy, redirect_name='next'): # # Save any defined next value into session # data = strategy.request_data(merge=False) # # Save extra data into session. # for field_name in strategy.setting('FIELDS_STORED_IN_SESSION', []): # if field_name in data: # strategy.session_set(field_name, data[field_name]) # # if redirect_name in data: # # Check and sanitize a user-defined GET/POST next field value # redirect_uri = data[redirect_name] # if strategy.setting('SANITIZE_REDIRECTS', True): # redirect_uri = sanitize_redirect(strategy.request_host(), # redirect_uri) # strategy.session_set( # redirect_name, # redirect_uri or strategy.setting('LOGIN_REDIRECT_URL') # ) # return strategy.start() # # def do_complete(strategy, login, user=None, redirect_name='next', # *args, **kwargs): # # pop redirect value before the session is trashed on login() # data = strategy.request_data() # redirect_value = strategy.session_get(redirect_name, '') or \ # data.get(redirect_name, '') # # is_authenticated = user_is_authenticated(user) # user = is_authenticated and user or None # default_redirect = strategy.setting('LOGIN_REDIRECT_URL') # url = default_redirect # login_error_url = strategy.setting('LOGIN_ERROR_URL') or \ # strategy.setting('LOGIN_URL') # if strategy.session_get('partial_pipeline'): # idx, backend, xargs, xkwargs = strategy.from_session( # strategy.session_pop('partial_pipeline') # ) # if backend == strategy.backend_name: # kwargs = kwargs.copy() # kwargs.setdefault('user', user) # kwargs.update(xkwargs) # user = strategy.continue_pipeline(pipeline_index=idx, # *xargs, **xkwargs) # else: # strategy.clean_partial_pipeline() # user = strategy.complete(user=user, request=strategy.request, # *args, **kwargs) # else: # user = strategy.complete(user=user, request=strategy.request, # *args, **kwargs) # # if strategy.is_response(user): # return user # # if is_authenticated: # if not user: # url = redirect_value or default_redirect # else: # url = redirect_value or \ # strategy.setting('NEW_ASSOCIATION_REDIRECT_URL') or \ # default_redirect # elif user: # if user_is_active(user): # # catch is_new/social_user in case login() resets the instance # is_new = getattr(user, 'is_new', False) # social_user = user.social_user # login(strategy, user) # # store last login backend name in session # strategy.session_set('social_auth_last_login_backend', # social_user.provider) # # # Remove possible redirect URL from session, if this is a new # # account, send him to the new-users-page if defined. # new_user_redirect = strategy.setting('NEW_USER_REDIRECT_URL') # if new_user_redirect and is_new: # url = new_user_redirect # else: # url = redirect_value or default_redirect # else: # url = strategy.setting('INACTIVE_USER_URL', login_error_url) # else: # url = login_error_url # # if redirect_value and redirect_value != url: # redirect_value = quote(redirect_value) # url += ('?' in url and '&' or '?') + \ # '%s=%s' % (redirect_name, redirect_value) # if url == '/': # url = '/' + user.username # return strategy.redirect(url) # # def do_disconnect(strategy, user, association_id=None, redirect_name='next'): # strategy.disconnect(user=user, association_id=association_id) # data = strategy.request_data() # return strategy.redirect(data.get(redirect_name, '') or # strategy.setting('DISCONNECT_REDIRECT_URL') or # strategy.setting('LOGIN_REDIRECT_URL')) # # Path: social/apps/django_app/utils.py # def strategy(redirect_uri=None): # def decorator(func): # @wraps(func) # def wrapper(request, backend, *args, **kwargs): # uri = redirect_uri # if uri and not uri.startswith('/'): # uri = reverse(redirect_uri, args=(backend,)) # request.strategy = load_strategy(request=request, backend=backend, # redirect_uri=uri, *args, **kwargs) # return func(request, backend, *args, **kwargs) # return wrapper # return decorator # # def setting(name, default=None): # try: # return getattr(settings, setting_name(name)) # except AttributeError: # return getattr(settings, name, default) # # class BackendWrapper(object): # def get_user(self, user_id): # return Strategy(storage=Storage).get_user(user_id) . Output only the next line.
@require_POST
Given the code snippet: <|code_start|> social_auth = Blueprint('social', __name__) @social_auth.route('/login/<string:backend>/', methods=['GET', 'POST']) @strategy('social.complete') def auth(backend): return do_auth(g.strategy) @social_auth.route('/complete/<string:backend>/', methods=['GET', 'POST']) @strategy('social.complete') def complete(backend, *args, **kwargs): """Authentication complete view, override this view if transaction management doesn't suit your needs.""" return do_complete(g.strategy, login=lambda strat, user: login_user(user), user=g.user, *args, **kwargs) @social_auth.route('/disconnect/<string:backend>/', methods=['POST']) @social_auth.route('/disconnect/<string:backend>/<string:association_id>/', <|code_end|> , generate the next line using the imports in this file: from flask import g, Blueprint from flask.ext.login import login_user from social.actions import do_auth, do_complete, do_disconnect from social.apps.flask_app.utils import strategy and context (functions, classes, or occasionally code) from other files: # Path: social/actions.py # def do_auth(strategy, redirect_name='next'): # # Save any defined next value into session # data = strategy.request_data(merge=False) # # Save extra data into session. # for field_name in strategy.setting('FIELDS_STORED_IN_SESSION', []): # if field_name in data: # strategy.session_set(field_name, data[field_name]) # # if redirect_name in data: # # Check and sanitize a user-defined GET/POST next field value # redirect_uri = data[redirect_name] # if strategy.setting('SANITIZE_REDIRECTS', True): # redirect_uri = sanitize_redirect(strategy.request_host(), # redirect_uri) # strategy.session_set( # redirect_name, # redirect_uri or strategy.setting('LOGIN_REDIRECT_URL') # ) # return strategy.start() # # def do_complete(strategy, login, user=None, redirect_name='next', # *args, **kwargs): # # pop redirect value before the session is trashed on login() # data = strategy.request_data() # redirect_value = strategy.session_get(redirect_name, '') or \ # data.get(redirect_name, '') # # is_authenticated = user_is_authenticated(user) # user = is_authenticated and user or None # default_redirect = strategy.setting('LOGIN_REDIRECT_URL') # url = default_redirect # login_error_url = strategy.setting('LOGIN_ERROR_URL') or \ # strategy.setting('LOGIN_URL') # if strategy.session_get('partial_pipeline'): # idx, backend, xargs, xkwargs = strategy.from_session( # strategy.session_pop('partial_pipeline') # ) # if backend == strategy.backend_name: # kwargs = kwargs.copy() # kwargs.setdefault('user', user) # kwargs.update(xkwargs) # user = strategy.continue_pipeline(pipeline_index=idx, # *xargs, **xkwargs) # else: # strategy.clean_partial_pipeline() # user = strategy.complete(user=user, request=strategy.request, # *args, **kwargs) # else: # user = strategy.complete(user=user, request=strategy.request, # *args, **kwargs) # # if strategy.is_response(user): # return user # # if is_authenticated: # if not user: # url = redirect_value or default_redirect # else: # url = redirect_value or \ # strategy.setting('NEW_ASSOCIATION_REDIRECT_URL') or \ # default_redirect # elif user: # if user_is_active(user): # # catch is_new/social_user in case login() resets the instance # is_new = getattr(user, 'is_new', False) # social_user = user.social_user # login(strategy, user) # # store last login backend name in session # strategy.session_set('social_auth_last_login_backend', # social_user.provider) # # # Remove possible redirect URL from session, if this is a new # # account, send him to the new-users-page if defined. # new_user_redirect = strategy.setting('NEW_USER_REDIRECT_URL') # if new_user_redirect and is_new: # url = new_user_redirect # else: # url = redirect_value or default_redirect # else: # url = strategy.setting('INACTIVE_USER_URL', login_error_url) # else: # url = login_error_url # # if redirect_value and redirect_value != url: # redirect_value = quote(redirect_value) # url += ('?' in url and '&' or '?') + \ # '%s=%s' % (redirect_name, redirect_value) # if url == '/': # url = '/' + user.username # return strategy.redirect(url) # # def do_disconnect(strategy, user, association_id=None, redirect_name='next'): # strategy.disconnect(user=user, association_id=association_id) # data = strategy.request_data() # return strategy.redirect(data.get(redirect_name, '') or # strategy.setting('DISCONNECT_REDIRECT_URL') or # strategy.setting('LOGIN_REDIRECT_URL')) # # Path: social/apps/flask_app/utils.py # def strategy(redirect_uri=None): # def decorator(func): # @wraps(func) # def wrapper(backend, *args, **kwargs): # uri = redirect_uri # if uri and not uri.startswith('/'): # uri = url_for(uri, backend=backend) # g.strategy = load_strategy(request=request, backend=backend, # redirect_uri=uri, *args, **kwargs) # return func(backend, *args, **kwargs) # return wrapper # return decorator . Output only the next line.
methods=['POST'])