Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Predict the next line after this snippet: <|code_start|> j = len(key[j:j+7])
(dec_data_len,) = unpack("<L", decrypted_data[:4])
return decrypted_data[8:8+dec_data_len]
def get_secret_by_name(secaddr, name, lsakey):
root = get_root(secaddr)
if not root:
return None
enc_secret_key = open_key(root, ["Policy", "Secrets", name, "CurrVal"])
if not enc_secret_key:
return None
enc_secret_value = enc_secret_key.ValueList.List[0]
if not enc_secret_value:
return None
enc_secret = secaddr.read(enc_secret_value.Data.value,
enc_secret_value.DataLength.value)
if not enc_secret:
return None
return decrypt_secret(enc_secret[0xC:], lsakey)
def get_secrets(sysaddr, secaddr):
root = get_root(secaddr)
if not root:
return None
<|code_end|>
using the current file's imports:
from Crypto.Hash import MD5
from Crypto.Cipher import ARC4,DES
from owade.fileAnalyze.creddump.win32.rawreg import *
from owade.fileAnalyze.creddump.addrspace import HiveFileAddressSpace
from owade.fileAnalyze.creddump.win32.hashdump import get_bootkey,str_to_key
and any relevant context from other files:
# Path: owade/fileAnalyze/creddump/addrspace.py
# class HiveFileAddressSpace:
# def __init__(self, fname):
# self.fname = fname
# self.base = FileAddressSpace(fname)
#
# def vtop(self, vaddr):
# return vaddr + BLOCK_SIZE + 4
#
# def read(self, vaddr, length, zero=False):
# first_block = BLOCK_SIZE - vaddr % BLOCK_SIZE
# full_blocks = ((length + (vaddr % BLOCK_SIZE)) / BLOCK_SIZE) - 1
# left_over = (length + vaddr) % BLOCK_SIZE
#
# paddr = self.vtop(vaddr)
# if paddr == None and zero:
# if length < first_block:
# return "\0" * length
# else:
# stuff_read = "\0" * first_block
# elif paddr == None:
# return None
# else:
# if length < first_block:
# stuff_read = self.base.read(paddr, length)
# if not stuff_read and zero:
# return "\0" * length
# else:
# return stuff_read
#
# stuff_read = self.base.read(paddr, first_block)
# if not stuff_read and zero:
# stuff_read = "\0" * first_block
#
# new_vaddr = vaddr + first_block
# for i in range(0,full_blocks):
# paddr = self.vtop(new_vaddr)
# if paddr == None and zero:
# stuff_read = stuff_read + "\0" * BLOCK_SIZE
# elif paddr == None:
# return None
# else:
# new_stuff = self.base.read(paddr, BLOCK_SIZE)
# if not new_stuff and zero:
# new_stuff = "\0" * BLOCK_SIZE
# elif not new_stuff:
# return None
# else:
# stuff_read = stuff_read + new_stuff
# new_vaddr = new_vaddr + BLOCK_SIZE
#
# if left_over > 0:
# paddr = self.vtop(new_vaddr)
# if paddr == None and zero:
# stuff_read = stuff_read + "\0" * left_over
# elif paddr == None:
# return None
# else:
# stuff_read = stuff_read + self.base.read(paddr, left_over)
# return stuff_read
#
# def read_long_phys(self, addr):
# string = self.base.read(addr, 4)
# (longval, ) = struct.unpack('L', string)
# return longval
#
# def is_valid_address(self, vaddr):
# paddr = self.vtop(vaddr)
# if not paddr: return False
# return self.base.is_valid_address(paddr)
#
# Path: owade/fileAnalyze/creddump/win32/hashdump.py
# def get_bootkey(sysaddr):
# cs = find_control_set(sysaddr)
# lsa_base = ["ControlSet%03d" % cs, "Control", "Lsa"]
# lsa_keys = ["JD","Skew1","GBG","Data"]
#
# root = get_root(sysaddr)
# if not root: return None
#
# lsa = open_key(root, lsa_base)
# if not lsa: return None
#
# bootkey = ""
#
# for lk in lsa_keys:
# key = open_key(lsa, [lk])
# class_data = sysaddr.read(key.Class.value, key.ClassLength.value)
# bootkey += class_data.decode('utf-16-le').decode('hex')
#
# bootkey_scrambled = ""
# for i in range(len(bootkey)):
# bootkey_scrambled += bootkey[p[i]]
#
# return bootkey_scrambled
#
# def str_to_key(s):
# key = []
# key.append( ord(s[0])>>1 )
# key.append( ((ord(s[0])&0x01)<<6) | (ord(s[1])>>2) )
# key.append( ((ord(s[1])&0x03)<<5) | (ord(s[2])>>3) )
# key.append( ((ord(s[2])&0x07)<<4) | (ord(s[3])>>4) )
# key.append( ((ord(s[3])&0x0F)<<3) | (ord(s[4])>>5) )
# key.append( ((ord(s[4])&0x1F)<<2) | (ord(s[5])>>6) )
# key.append( ((ord(s[5])&0x3F)<<1) | (ord(s[6])>>7) )
# key.append( ord(s[6])&0x7F )
# for i in range(8):
# key[i] = (key[i]<<1)
# key[i] = odd_parity[key[i]]
# return "".join(chr(k) for k in key)
. Output only the next line. | bootkey = get_bootkey(sysaddr) |
Continue the code snippet: <|code_start|> enc_reg_value = enc_reg_key.ValueList.List[0]
if not enc_reg_value:
return None
obf_lsa_key = secaddr.read(enc_reg_value.Data.value,
enc_reg_value.DataLength.value)
if not obf_lsa_key:
return None
md5 = MD5.new()
md5.update(bootkey)
for i in range(1000):
md5.update(obf_lsa_key[60:76])
rc4key = md5.digest()
rc4 = ARC4.new(rc4key)
lsa_key = rc4.decrypt(obf_lsa_key[12:60])
return lsa_key[0x10:0x20]
def decrypt_secret(secret, key):
"""Python implementation of SystemFunction005.
Decrypts a block of data with DES using given key.
Note that key can be longer than 7 bytes."""
decrypted_data = ''
j = 0 # key index
for i in range(0,len(secret),8):
enc_block = secret[i:i+8]
block_key = key[j:j+7]
<|code_end|>
. Use current file imports:
from Crypto.Hash import MD5
from Crypto.Cipher import ARC4,DES
from owade.fileAnalyze.creddump.win32.rawreg import *
from owade.fileAnalyze.creddump.addrspace import HiveFileAddressSpace
from owade.fileAnalyze.creddump.win32.hashdump import get_bootkey,str_to_key
and context (classes, functions, or code) from other files:
# Path: owade/fileAnalyze/creddump/addrspace.py
# class HiveFileAddressSpace:
# def __init__(self, fname):
# self.fname = fname
# self.base = FileAddressSpace(fname)
#
# def vtop(self, vaddr):
# return vaddr + BLOCK_SIZE + 4
#
# def read(self, vaddr, length, zero=False):
# first_block = BLOCK_SIZE - vaddr % BLOCK_SIZE
# full_blocks = ((length + (vaddr % BLOCK_SIZE)) / BLOCK_SIZE) - 1
# left_over = (length + vaddr) % BLOCK_SIZE
#
# paddr = self.vtop(vaddr)
# if paddr == None and zero:
# if length < first_block:
# return "\0" * length
# else:
# stuff_read = "\0" * first_block
# elif paddr == None:
# return None
# else:
# if length < first_block:
# stuff_read = self.base.read(paddr, length)
# if not stuff_read and zero:
# return "\0" * length
# else:
# return stuff_read
#
# stuff_read = self.base.read(paddr, first_block)
# if not stuff_read and zero:
# stuff_read = "\0" * first_block
#
# new_vaddr = vaddr + first_block
# for i in range(0,full_blocks):
# paddr = self.vtop(new_vaddr)
# if paddr == None and zero:
# stuff_read = stuff_read + "\0" * BLOCK_SIZE
# elif paddr == None:
# return None
# else:
# new_stuff = self.base.read(paddr, BLOCK_SIZE)
# if not new_stuff and zero:
# new_stuff = "\0" * BLOCK_SIZE
# elif not new_stuff:
# return None
# else:
# stuff_read = stuff_read + new_stuff
# new_vaddr = new_vaddr + BLOCK_SIZE
#
# if left_over > 0:
# paddr = self.vtop(new_vaddr)
# if paddr == None and zero:
# stuff_read = stuff_read + "\0" * left_over
# elif paddr == None:
# return None
# else:
# stuff_read = stuff_read + self.base.read(paddr, left_over)
# return stuff_read
#
# def read_long_phys(self, addr):
# string = self.base.read(addr, 4)
# (longval, ) = struct.unpack('L', string)
# return longval
#
# def is_valid_address(self, vaddr):
# paddr = self.vtop(vaddr)
# if not paddr: return False
# return self.base.is_valid_address(paddr)
#
# Path: owade/fileAnalyze/creddump/win32/hashdump.py
# def get_bootkey(sysaddr):
# cs = find_control_set(sysaddr)
# lsa_base = ["ControlSet%03d" % cs, "Control", "Lsa"]
# lsa_keys = ["JD","Skew1","GBG","Data"]
#
# root = get_root(sysaddr)
# if not root: return None
#
# lsa = open_key(root, lsa_base)
# if not lsa: return None
#
# bootkey = ""
#
# for lk in lsa_keys:
# key = open_key(lsa, [lk])
# class_data = sysaddr.read(key.Class.value, key.ClassLength.value)
# bootkey += class_data.decode('utf-16-le').decode('hex')
#
# bootkey_scrambled = ""
# for i in range(len(bootkey)):
# bootkey_scrambled += bootkey[p[i]]
#
# return bootkey_scrambled
#
# def str_to_key(s):
# key = []
# key.append( ord(s[0])>>1 )
# key.append( ((ord(s[0])&0x01)<<6) | (ord(s[1])>>2) )
# key.append( ((ord(s[1])&0x03)<<5) | (ord(s[2])>>3) )
# key.append( ((ord(s[2])&0x07)<<4) | (ord(s[3])>>4) )
# key.append( ((ord(s[3])&0x0F)<<3) | (ord(s[4])>>5) )
# key.append( ((ord(s[4])&0x1F)<<2) | (ord(s[5])>>6) )
# key.append( ((ord(s[5])&0x3F)<<1) | (ord(s[6])>>7) )
# key.append( ord(s[6])&0x7F )
# for i in range(8):
# key[i] = (key[i]<<1)
# key[i] = odd_parity[key[i]]
# return "".join(chr(k) for k in key)
. Output only the next line. | des_key = str_to_key(block_key) |
Next line prediction: <|code_start|>
#############################################################################
## ##
## This file is part of Owade : www.owade.org ##
## Offline Windows Analyzer and Data Extractor ##
## ##
## Authors: ##
## Elie Bursztein <owade@elie.im> ##
## Ivan Fontarensky <ivan.fontarensky@cassidian.com> ##
## Matthieu Martin <matthieu.mar+owade@gmail.com> ##
## Jean-Michel Picod <jean-michel.picod@cassidian.com> ##
## ##
## This program is distributed under GPLv3 licence (see LICENCE.txt) ##
## ##
#############################################################################
__author__="ashe"
__date__ ="$Jul 26, 2011 10:56:51 AM$"
class GetIEHistory:
#indexes is a list of the path :
#%USERPROFILE%Ashee/Local Settings/History/index.dat
#%USERPROFILE%Ashee/Local Settings/History/*/index.dat
def main(self, indexes):
placeValues = {}
formValues = {}
<|code_end|>
. Use current file imports:
(import os
import sys
import tempfile
import re
import subprocess as subp
from owade.constants import MSIECF_DIR
from owade.tools.domainFormater import format)
and context including class names, function names, or small code snippets from other files:
# Path: owade/constants.py
# def checkConstant(dir, isdir=True):
# PROJECT_DIR = "/opt/"
# PROJECT_NAME = "OwadeReborn/"
# TIMELINE_FILE = PROJECT_DIR + PROJECT_NAME + "templates/timeline.html"
# HASHCAT_DIR = PROJECT_DIR + PROJECT_NAME + "owade/fileAnalyze/hashcatLib/hashcat"
# DATABASE_NAME='owade'
# DATABASE_USER='postgres'
# DATABASE_PASSWORD='postgres'
# DATABASE_HOST='localhost'
# DATABASE_PORT='5432'
# EXT_HDRIVE = "/media/hackaton/TOSHIBA EXT/storage"
# IMAGE_DIR = EXT_HDRIVE + "/image"
# IMAGE_FTP = EXT_HDRIVE + "/ftp"
# FILE_DIR = EXT_HDRIVE + "/file"
# DATABASE_DIR = PROJECT_DIR + "OwadeReborn/database/"
# TEMPLATE_DIR = PROJECT_DIR + "OwadeReborn/templates/"
#
# Path: owade/tools/domainFormater.py
# def format(url):
# if not re.match(r'^http', url):
# return None
# if re.match(r'https?://[^/.]*(:[0-9]{1,5})?(/.*)?$', url):
# return None
# match = re.match(r'^https?://([^/]*\.)*([^/.]*\.[^/.]{2}\.[^/.]{2,3})(:[0-9]{1,5})?(/.*)?$', url)
# if match == None:
# match = re.match(r'^https?://([^/]*\.)*([^/.]*\.com\.[^/.]{2,3})(:[0-9]{1,5})?(/.*)?$', url)
# if match == None:
# match = re.match(r'^https?://([^/]*\.)*([^/.]*\.[^/.]{2,4})(:[0-9]{1,5})?(/.*)?$', url)
# if match == None:
# match = re.match(r'^https?://([^/]*\.)*([^/.]*)(:[0-9]{1,5})?(/.*)?$', url)
# if match != None:
# return match.group(1) + match.group(2)
# raise Exception("One case isn't dealed with: %s" % url)
# return match.group(2)
. Output only the next line. | binary = '%s/msiecftools/msiecfexport' % MSIECF_DIR |
Here is a snippet: <|code_start|>
class GetIEHistory:
#indexes is a list of the path :
#%USERPROFILE%Ashee/Local Settings/History/index.dat
#%USERPROFILE%Ashee/Local Settings/History/*/index.dat
def main(self, indexes):
placeValues = {}
formValues = {}
binary = '%s/msiecftools/msiecfexport' % MSIECF_DIR
if not os.path.isfile(binary):
print >>sys.stderr, "Binary %s not found" % binary
return {self.__class__.__name__:{'places':placeValues, 'forms':formValues}}
i = 0
for index in indexes:
temp = tempfile.NamedTemporaryFile()
subp.call([binary, index], universal_newlines=True, stdout=temp)
temp.seek(0)
url = ""
date = ""
for line in temp:
if len(line) != 0 and line[-1] == '\n':
line = line[:-1]
if line == "":
if url != "" and date != "":
i += 1
placeValues['place%d' % i] = {'url':url, 'date':date,
<|code_end|>
. Write the next line using the current file imports:
import os
import sys
import tempfile
import re
import subprocess as subp
from owade.constants import MSIECF_DIR
from owade.tools.domainFormater import format
and context from other files:
# Path: owade/constants.py
# def checkConstant(dir, isdir=True):
# PROJECT_DIR = "/opt/"
# PROJECT_NAME = "OwadeReborn/"
# TIMELINE_FILE = PROJECT_DIR + PROJECT_NAME + "templates/timeline.html"
# HASHCAT_DIR = PROJECT_DIR + PROJECT_NAME + "owade/fileAnalyze/hashcatLib/hashcat"
# DATABASE_NAME='owade'
# DATABASE_USER='postgres'
# DATABASE_PASSWORD='postgres'
# DATABASE_HOST='localhost'
# DATABASE_PORT='5432'
# EXT_HDRIVE = "/media/hackaton/TOSHIBA EXT/storage"
# IMAGE_DIR = EXT_HDRIVE + "/image"
# IMAGE_FTP = EXT_HDRIVE + "/ftp"
# FILE_DIR = EXT_HDRIVE + "/file"
# DATABASE_DIR = PROJECT_DIR + "OwadeReborn/database/"
# TEMPLATE_DIR = PROJECT_DIR + "OwadeReborn/templates/"
#
# Path: owade/tools/domainFormater.py
# def format(url):
# if not re.match(r'^http', url):
# return None
# if re.match(r'https?://[^/.]*(:[0-9]{1,5})?(/.*)?$', url):
# return None
# match = re.match(r'^https?://([^/]*\.)*([^/.]*\.[^/.]{2}\.[^/.]{2,3})(:[0-9]{1,5})?(/.*)?$', url)
# if match == None:
# match = re.match(r'^https?://([^/]*\.)*([^/.]*\.com\.[^/.]{2,3})(:[0-9]{1,5})?(/.*)?$', url)
# if match == None:
# match = re.match(r'^https?://([^/]*\.)*([^/.]*\.[^/.]{2,4})(:[0-9]{1,5})?(/.*)?$', url)
# if match == None:
# match = re.match(r'^https?://([^/]*\.)*([^/.]*)(:[0-9]{1,5})?(/.*)?$', url)
# if match != None:
# return match.group(1) + match.group(2)
# raise Exception("One case isn't dealed with: %s" % url)
# return match.group(2)
, which may include functions, classes, or code. Output only the next line. | 'domain':format(url)} |
Next line prediction: <|code_start|> play['actions'] = [actions.FunctionCall(HARVEST_GATHER_SCREEN,
[NOT_QUEUED, selected_mineral.location.screen.get_flipped().to_array()])]
self._state = EconomyManager._IDLE
elif self._state == EconomyManager._BUILDING_SUPPLY_DEPOT:
if not self._worker_selected:
if obs.observation[PLAYER][IDLE_WORKER_COUNT] > 0:
play['actions'] = [actions.FunctionCall(SELECT_IDLE_WORKER, [NEW_SELECTION])]
self._worker_selected = True
else: # if no idle scv, select one randomly
on_screen_scv = self._shared['screen'].scan_units(obs, self._shared, [TERRAN_SCV], PLAYER_SELF)
if len(on_screen_scv) == 0:
if len(self._shared['economy'].command_centers) > 0:
selected_command_center = random.choice(self._shared['economy'].command_centers)
play['actions'] = [actions.FunctionCall(MOVE_CAMERA,
[selected_command_center.camera.to_array()])]
else:
selected_scv = random.choice(on_screen_scv)
play['actions'] = [actions.FunctionCall(SELECT_POINT,
[NEW_SELECTION, selected_scv.location.screen.get_flipped().to_array()])]
self._worker_selected = True
elif BUILD_SUPPLY_DEPOT in obs.observation["available_actions"]:
building_center = get_random_building_point(obs, self._shared, 11)
if building_center:
play['actions'] = [actions.FunctionCall(BUILD_SUPPLY_DEPOT,
[NOT_QUEUED, building_center.get_flipped().to_array()])]
self._shared['economy'].add_supply_depot(obs, self._shared,
<|code_end|>
. Use current file imports:
(import random
from oscar.agent.custom_agent import CustomAgent
from oscar.constants import *
from oscar.meta_action.build import *
from oscar.util.location import Location)
and context including class names, function names, or small code snippets from other files:
# Path: oscar/agent/custom_agent.py
# class CustomAgent(BaseAgent):
# """A base agent to write custom scripted agents."""
#
# def __init__(self):
# super().__init__()
# self._shared = {}
#
# def add_shared(self, name, shared):
# self._shared[name] = shared
#
# Path: oscar/util/location.py
# class Location:
#
# def __init__(self, minimap_loc=None, screen_loc=None, camera_loc=None):
# self.minimap = minimap_loc
# self.screen = screen_loc
# self.camera = camera_loc
#
# def compute_minimap_loc(self, obs, shared):
# scale_x = shared['camera'].width(obs) / shared['screen'].width(obs)
# scale_y = shared['camera'].height(obs) / shared['screen'].height(obs)
#
# self.minimap = shared['minimap'].bound(obs, Point(
# int(round(self.camera.x - 0.5*shared['camera'].width(obs) + self.screen.x * scale_x)),
# int(round(self.camera.y - 0.5*shared['camera'].height(obs) + self.screen.y * scale_y))))
#
# def squarred_distance(self, other):
# if not self.minimap or not other.minimap:
# raise Exception("Can't compute distance")
# return self.minimap.distance(other.minimap)
#
# def distance(self, other):
# return math.sqrt(self.squarred_distance(other))
#
# def equals(self, other):
# def equals_minimap():
# return (not self.minimap and not other.minimap) \
# or (self.minimap and other.minimap and self.minimap.equals(other.minimap))
#
# def equals_screen():
# return (not self.screen and not other.screen) \
# or (self.screen and other.screen and self.screen.equals(other.screen))
#
# def equals_camera():
# return (not self.camera and not other.camera) \
# or (self.camera and other.camera and self.camera.equals(other.camera))
#
# return equals_minimap() and equals_screen() and equals_camera()
#
# def __str__(self):
# return "Location {\n" \
# + " minimap: " + str(self.minimap) + "\n" \
# + " screen: " + str(self.screen) + "\n" \
# + " camera: " + str(self.camera) + "\n" \
# + "}"
. Output only the next line. | Location(camera_loc=self._shared['camera'].location(obs, self._shared), screen_loc=building_center)) |
Here is a snippet: <|code_start|>parser.add_argument('-tau-m', '--tau-min',
default=1.0,
type=float,
dest="tau_min")
parser.add_argument('-tau-M', '--tau-max',
default=40.0,
type=float,
dest="tau_max")
parser.add_argument('-ds', '--decreasing-steps',
default=10000,
type=float,
dest="decreasing_steps")
parser.add_argument('-c', '--config-file',
default='config/learning_complex.json',
type=str,
dest="config_file")
args = parser.parse_args()
steps_warming_up = 10
if args.load_memory == "random":
steps_warming_up = 50000
if not os.path.isdir(args.out_dir):
os.makedirs(args.out_dir)
CONFIG_FILE = args.config_file
LOG_FILE = args.out_dir + '/duel_dqn_{}.csv'.format(CONFIG_FILE[7:-5])
MEMORY_FILE = 'ML_homework/memory_{}.pickle'.format(CONFIG_FILE[7:-4])
# Get the environment and extract the number of actions.
<|code_end|>
. Write the next line using the current file imports:
import numpy as np
import gym
import os
import pickle
import argparse
import pandas as pd
from keras.models import Sequential
from keras.layers import Dense, Activation, Flatten
from keras.optimizers import Adam
from rl.agents.dqn import DQNAgent
from rl.policy import BoltzmannQPolicy, LinearAnnealedPolicy
from rl.memory import SequentialMemory
from oscar.env.envs.general_learning_env import GeneralLearningEnv
and context from other files:
# Path: oscar/env/envs/general_learning_env.py
# class GeneralLearningEnv(gym.Env):
# def __init__(self, configuration_file=DEFAULT_CONFIGURATION, enable_visualisation=True, game_steps_per_update=8,
# log_file_path=None, publish_stats=True):
# self.env_thread = Pysc2EnvRunner(configuration_file=configuration_file,
# enable_visualisation=enable_visualisation,
# game_steps_per_update=game_steps_per_update)
# self.shared_memory = self.env_thread.shared_memory
# self.log_file = log_file_path
# self.publish_stats = publish_stats
# # get semaphores from shared memory
# self.semaphore_obs_ready = self.shared_memory.semaphore_obs_ready
# self.semaphore_action_set = self.shared_memory.semaphore_action_set
# # set action/observation space from shared memory
# self.action_space = self.shared_memory.action_space
# self.observation_space = self.shared_memory.observation_space
# # start thread
# self.env_thread.start()
#
# def step(self, action):
# info_dict = {}
# # set action into shared memory
# self.shared_memory.shared_action = action
# # let the thread run again
# self.semaphore_action_set.release()
# # increase the number of steps performed by the learning agent
# self.env_thread.learning_agent_step += 1
# # wait a call to the target agent
# self.semaphore_obs_ready.acquire(blocking=True, timeout=None)
# # get the obs of the current state as seen by the agent
# obs = self.shared_memory.shared_obs
# # get the reward of the current run and reset it to 0 for next step
# reward = self.env_thread.reward # / self.env_thread.step_count
# self.env_thread.reward = 0
# # get done state from thread
# done = self.env_thread.was_done
# if done:
# self.env_thread.was_done = False # reset was_done to false for next loop
# if self.publish_stats:
# info_dict["stats"] = self.env_thread.stats
# # log result to disk if asked
# if self.log_file is not None and self.env_thread.stats is not None:
# if os.path.isfile(self.log_file):
# self.env_thread.stats.to_csv(self.log_file, sep=',', mode='a', header=False)
# else:
# self.env_thread.stats.to_csv(self.log_file, sep=',', mode='w', header=True)
# # return current obs
# return obs.copy(), reward, done, info_dict
#
# def reset(self):
# # wait for the env to stop as waiting action
# self.semaphore_obs_ready.acquire(blocking=True, timeout=None)
# return self.shared_memory.shared_obs
#
# def close(self):
# self.env_thread.stop = True
# self.semaphore_action_set.release() # to be sure that the thread go to stop condition
#
# def render(self, mode='human', close=False):
# pass
#
# def seed(self, seed=None):
# pass
#
# def get_action_mask(self):
# # every action is supposed to be playable
# # return np.ones(shape=self.action_space.n)
# # get the actions available according to the learning agent
# return self.shared_memory.available_action_mask
, which may include functions, classes, or code. Output only the next line. | env = GeneralLearningEnv(CONFIG_FILE, False, log_file_path=LOG_FILE, publish_stats=False) |
Predict the next line for this snippet: <|code_start|> context = self._subordinate_context[subordinate]
play = {}
play['actions'] = [actions.FunctionCall(MOVE_CAMERA, [context.camera.to_array()])]
play['locked_choice'] = True
self._is_changing_context = True
return play
def save_context(self, obs):
context = AgentContext()
location = self._shared['camera'].location(obs=obs, shared=self._shared)
context.camera = location
self._subordinate_context[self._playing_subordinate] = context
@abstractmethod
def choose_subordinate(self, obs, locked_choice):
"""
Choose a subordinate among the list of subordinates, and make it play.
:return: A subordinate among the list of subordinates.
"""
def reset(self):
super().reset()
self._subordinate_context = {}
self._is_changing_context = False
self.add_shared('env', Env())
self.add_shared('camera', Camera())
class AgentContext:
def __init__(self):
<|code_end|>
with the help of current file imports:
from abc import ABC, abstractmethod
from oscar.agent.commander.base_commander import BaseCommander
from oscar.util.point import Point
from oscar.meta_action import *
and context from other files:
# Path: oscar/agent/commander/base_commander.py
# class BaseCommander(ABC, CustomAgent):
# """
# A base class for commander agents.
# These are specialized agents that capable of delegating tasks to subordinates
# """
#
# def __init__(self, subordinates: list):
# """
# :param subordinates: a list of agents. These must be initialized already !
# """
# super().__init__()
# self._subordinates = subordinates
# self._locked_choice = False
# self._playing_subordinate = None
#
# def step(self, obs, locked_choice=None):
# """
# Does some work and choose a subordinate that will play
# :param obs: observations from the game
# :return: an action chosen by a subordinate
# """
#
# """if not self._locked_choice:
# self._playing_subordinate = self.choose_subordinate(obs)
# play = self._playing_subordinate.step(obs)
# try:
# self._locked_choice = play["locked_choice"]
# except KeyError:
# self._locked_choice = False
# return play"""
#
# if locked_choice is None:
# locked_choice = self._locked_choice
#
# self._playing_subordinate = self.choose_subordinate(obs, locked_choice)
# play = self._playing_subordinate.step(obs, locked_choice)
# if "locked_choice" in play:
# self._locked_choice = play["locked_choice"]
# else:
# self._locked_choice = False
# return play
#
# def add_subordinate(self, agent):
# """
# Hires a subordinate
# :param agent: to add
# :return:
# """
# self._subordinates.append(agent)
#
# def remove_subordinate(self, agent):
# """
# Fires a subordinate
# :param agent: to remove
# :return:
# """
# self._subordinates.remove(agent)
#
# @abstractmethod
# def choose_subordinate(self, obs, locked_choice):
# """
# Choose a subordinate among the list of subordinates, and make it play.
# :return: A subordinate among the list of subordinates.
# """
#
# def play_locked_choice(self):
# return self._playing_subordinate
#
# def unlock_choice(self):
# if self._locked_choice:
# self._locked_choice = False
# try:
# self._playing_subordinate.unlock_choice()
# # Method does not exist = not a commander
# except AttributeError:
# pass
#
# def setup(self, obs_spec, action_spec):
# super().setup(obs_spec, action_spec)
# for subordinate in self._subordinates:
# subordinate.setup(obs_spec, action_spec)
#
# def reset(self):
# super().reset()
# for subordinate in self._subordinates:
# subordinate.reset()
#
# def __str__(self):
# """
# See print_tree
# :return:
# """
# return self.print_tree(0)
#
# def print_tree(self, depth):
# """
# Recursively builds the hierarchy tree of the agent
# :param depth: current depth in the general tree (used for indentation in the string)
# :return: hierarchy tree (string)
# """
# depth += 1
# ret = "I am a {} and I have {} subordinates :\n".format(type(self).__name__, len(self._subordinates))
# for subordinate in self._subordinates:
# ret += "\t" * depth
# try:
# ret += subordinate.print_tree(depth + 1)
# except AttributeError:
# ret += str(subordinate) + "\n"
# return ret
#
# Path: oscar/util/point.py
# class Point:
#
# def __init__(self, x=None, y=None):
# self.x = x
# self.y = y
#
# def squared_distance(self, other):
# return (self.x-other.x)*(self.x-other.x) + (self.y-other.y)*(self.y-other.y)
#
# def distance(self, other):
# return math.sqrt(self.squared_distance(other))
#
# def get_flipped(self):
# return Point(self.y, self.x)
#
# def to_array(self):
# return [self.x, self.y]
#
# def equals(self, other):
# return self.x == other.x and self.y == other.y
#
# def difference(self, other):
# return Point(self.x - other.x, self.y - other.y)
#
# def addition(self, other):
# return Point(self.x + other.x, self.y + other.y)
#
# def __str__(self):
# return "Point("+str(self.x)+","+str(self.y)+")"
, which may contain function names, class names, or code. Output only the next line. | self.camera = Point() |
Continue the code snippet: <|code_start|>
_PLAYER_RELATIVE = features.SCREEN_FEATURES.player_relative.index
_PLAYER_FRIENDLY = 1
_PLAYER_NEUTRAL = 3 # beacon/minerals
_PLAYER_HOSTILE = 4
_NO_OP = actions.FUNCTIONS.no_op.id
_MOVE_SCREEN = actions.FUNCTIONS.Move_screen.id
_ATTACK_SCREEN = actions.FUNCTIONS.Attack_screen.id
_SELECT_ARMY = actions.FUNCTIONS.select_army.id
_SELECT_POINT = actions.FUNCTIONS.select_point.id
_NOT_QUEUED = [0]
_QUEUED = [1]
_SELECT_ALL = [0]
<|code_end|>
. Use current file imports:
import numpy
from oscar.agent.custom_agent import CustomAgent
from pysc2.lib import actions
from pysc2.lib import features
and context (classes, functions, or code) from other files:
# Path: oscar/agent/custom_agent.py
# class CustomAgent(BaseAgent):
# """A base agent to write custom scripted agents."""
#
# def __init__(self):
# super().__init__()
# self._shared = {}
#
# def add_shared(self, name, shared):
# self._shared[name] = shared
. Output only the next line. | class CollectMyShards(CustomAgent): |
Based on the snippet: <|code_start|>
class Minimap(object):
@staticmethod
def width(obs):
return len(obs.observation[MINIMAP][0])
@staticmethod
def height(obs):
return len(obs.observation[MINIMAP][0][0])
@staticmethod
def random_point(obs):
<|code_end|>
, predict the immediate next line with the help of imports:
import numpy as np
from oscar.util.point import Point
from oscar.constants import MINIMAP
and context (classes, functions, sometimes code) from other files:
# Path: oscar/util/point.py
# class Point:
#
# def __init__(self, x=None, y=None):
# self.x = x
# self.y = y
#
# def squared_distance(self, other):
# return (self.x-other.x)*(self.x-other.x) + (self.y-other.y)*(self.y-other.y)
#
# def distance(self, other):
# return math.sqrt(self.squared_distance(other))
#
# def get_flipped(self):
# return Point(self.y, self.x)
#
# def to_array(self):
# return [self.x, self.y]
#
# def equals(self, other):
# return self.x == other.x and self.y == other.y
#
# def difference(self, other):
# return Point(self.x - other.x, self.y - other.y)
#
# def addition(self, other):
# return Point(self.x + other.x, self.y + other.y)
#
# def __str__(self):
# return "Point("+str(self.x)+","+str(self.y)+")"
#
# Path: oscar/constants.py
# MINIMAP = 'feature_minimap'
. Output only the next line. | loc = Point() |
Predict the next line for this snippet: <|code_start|>
class Minimap(object):
@staticmethod
def width(obs):
<|code_end|>
with the help of current file imports:
import numpy as np
from oscar.util.point import Point
from oscar.constants import MINIMAP
and context from other files:
# Path: oscar/util/point.py
# class Point:
#
# def __init__(self, x=None, y=None):
# self.x = x
# self.y = y
#
# def squared_distance(self, other):
# return (self.x-other.x)*(self.x-other.x) + (self.y-other.y)*(self.y-other.y)
#
# def distance(self, other):
# return math.sqrt(self.squared_distance(other))
#
# def get_flipped(self):
# return Point(self.y, self.x)
#
# def to_array(self):
# return [self.x, self.y]
#
# def equals(self, other):
# return self.x == other.x and self.y == other.y
#
# def difference(self, other):
# return Point(self.x - other.x, self.y - other.y)
#
# def addition(self, other):
# return Point(self.x + other.x, self.y + other.y)
#
# def __str__(self):
# return "Point("+str(self.x)+","+str(self.y)+")"
#
# Path: oscar/constants.py
# MINIMAP = 'feature_minimap'
, which may contain function names, class names, or code. Output only the next line. | return len(obs.observation[MINIMAP][0]) |
Using the snippet: <|code_start|>
"""API Constants"""
_PLAYER_RELATIVE = features.SCREEN_FEATURES.player_relative.index
_PLAYER_FRIENDLY = 1
_PLAYER_NEUTRAL = 3 # beacon/minerals
_PLAYER_HOSTILE = 4
_NO_OP = actions.FUNCTIONS.no_op.id
_MOVE_SCREEN = actions.FUNCTIONS.Move_screen.id
_ATTACK_SCREEN = actions.FUNCTIONS.Attack_screen.id
_SELECT_ARMY = actions.FUNCTIONS.select_army.id
_SELECT_POINT = actions.FUNCTIONS.select_point.id
_SELECT_RECT = actions.FUNCTIONS.select_rect.id
_NOT_QUEUED = [0]
_SELECT_ALL = [0]
_ADD_TO_SELECTION = [1]
_NEW_SELECTION = [0]
OBS_LENGTH = 4
<|code_end|>
, determine the next line of code. You have imports:
from pysc2.env.sc2_env import SC2Env
from pysc2.lib import actions
from pysc2.lib import features
from gym import spaces
from oscar.env.envs.pysc2_env import Pysc2Env
import numpy as np
import copy
and context (class names, function names, or code) available:
# Path: oscar/env/envs/pysc2_env.py
# class Pysc2Env(gym.Env):
# """
# abstract class for building pysc2 env for Gym
# """
# metadata = {'render.modes': ['human']}
#
# # must be defined by sub class !
# pysc2_env = None
#
# last_obs = None
#
# def __init__(self):
# pass
#
# def step(self, action):
# """
# move the environment forward of one step
# :param action: a pysc2 action (a list of one pysc2 function call)
# :return: tuple of pysc2 full observation structure, the reward for the step, if is the last
# step or not and a dict to debug information (empty)
# """
# # Pysc2 can take a list of action :
# # ( https://github.com/deepmind/pysc2/blob/7a04e74effc88d3e2fe0e4562c99a18d06a099b2/pysc2/env/sc2_env.py#L247 )
# self.last_obs = self.pysc2_env.step(action)[0]
# done = self.last_obs.step_type == environment.StepType.LAST
# return self.last_obs, self.last_obs.reward, done, {}
#
# def reset(self):
# self.last_obs = self.pysc2_env.reset()[0]
# return self.last_obs
#
# def render(self, mode='human', close=False):
# pass
#
# def close(self):
# self.pysc2_env.close()
#
# def seed(self, seed=None):
# # any way to set the seed of pysc2 ?
# pass
#
# def get_action_mask(self):
# pass
. Output only the next line. | class Pysc2MineralshardEnv2(Pysc2Env): |
Given snippet: <|code_start|> while len(queue) > 0:
cur = queue.pop()
if _try_explore(cur[0]+1, cur[1], queue, scanned):
sum_x += cur[0]+1
sum_y += cur[1]
nb_scanned += 1
if _try_explore(cur[0], cur[1]+1, queue, scanned):
sum_x += cur[0]
sum_y += cur[1]+1
nb_scanned += 1
if _try_explore(cur[0], cur[1]-1, queue, scanned):
sum_x += cur[0]
sum_y += cur[1]-1
nb_scanned += 1
return round(sum_x/nb_scanned), round(sum_y/nb_scanned)
screen_width = Screen.width(obs)
screen_height = Screen.height(obs)
scanned = np.zeros((screen_width, screen_height))
self._scanned_units = []
for x in range(screen_width):
for y in range(screen_height):
if scanned[x, y] == 0 and obs.observation[SCREEN][SCREEN_UNIT_TYPE][x, y] != 0:
center_x, center_y = _explore_contiguous(x, y,
obs.observation[SCREEN][SCREEN_UNIT_TYPE][x, y],
obs.observation[SCREEN][SCREEN_PLAYER_RELATIVE][x, y],
scanned)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import numpy as np
from oscar.constants import *
from oscar.util.unit import Unit
from oscar.util.location import Location
from oscar.util.point import Point
and context:
# Path: oscar/util/unit.py
# class Unit:
#
# def __init__(self, location, unit_id=None, player_id=None):
# self.location = location
# self.unit_id = unit_id
# self.player_id = player_id
#
# def equals(self, other):
# def is_same_location():
# return (not self.location and not other.location) \
# or (self.location and other.location and self.location.equals(other.location))
# def is_same_unit_id():
# return (self.unit_id is None and other.unit_id is None) \
# or (self.unit_id is not None and other.unit_id is not None and self.unit_id == other.unit_id)
# def is_same_player_id():
# return (self.player_id is None and other.player_id is None) \
# or (self.player_id is not None and other.player_id is not None and self.player_id == other.player_id)
#
# return is_same_location() and is_same_unit_id() and is_same_player_id()
#
# Path: oscar/util/location.py
# class Location:
#
# def __init__(self, minimap_loc=None, screen_loc=None, camera_loc=None):
# self.minimap = minimap_loc
# self.screen = screen_loc
# self.camera = camera_loc
#
# def compute_minimap_loc(self, obs, shared):
# scale_x = shared['camera'].width(obs) / shared['screen'].width(obs)
# scale_y = shared['camera'].height(obs) / shared['screen'].height(obs)
#
# self.minimap = shared['minimap'].bound(obs, Point(
# int(round(self.camera.x - 0.5*shared['camera'].width(obs) + self.screen.x * scale_x)),
# int(round(self.camera.y - 0.5*shared['camera'].height(obs) + self.screen.y * scale_y))))
#
# def squarred_distance(self, other):
# if not self.minimap or not other.minimap:
# raise Exception("Can't compute distance")
# return self.minimap.distance(other.minimap)
#
# def distance(self, other):
# return math.sqrt(self.squarred_distance(other))
#
# def equals(self, other):
# def equals_minimap():
# return (not self.minimap and not other.minimap) \
# or (self.minimap and other.minimap and self.minimap.equals(other.minimap))
#
# def equals_screen():
# return (not self.screen and not other.screen) \
# or (self.screen and other.screen and self.screen.equals(other.screen))
#
# def equals_camera():
# return (not self.camera and not other.camera) \
# or (self.camera and other.camera and self.camera.equals(other.camera))
#
# return equals_minimap() and equals_screen() and equals_camera()
#
# def __str__(self):
# return "Location {\n" \
# + " minimap: " + str(self.minimap) + "\n" \
# + " screen: " + str(self.screen) + "\n" \
# + " camera: " + str(self.camera) + "\n" \
# + "}"
#
# Path: oscar/util/point.py
# class Point:
#
# def __init__(self, x=None, y=None):
# self.x = x
# self.y = y
#
# def squared_distance(self, other):
# return (self.x-other.x)*(self.x-other.x) + (self.y-other.y)*(self.y-other.y)
#
# def distance(self, other):
# return math.sqrt(self.squared_distance(other))
#
# def get_flipped(self):
# return Point(self.y, self.x)
#
# def to_array(self):
# return [self.x, self.y]
#
# def equals(self, other):
# return self.x == other.x and self.y == other.y
#
# def difference(self, other):
# return Point(self.x - other.x, self.y - other.y)
#
# def addition(self, other):
# return Point(self.x + other.x, self.y + other.y)
#
# def __str__(self):
# return "Point("+str(self.x)+","+str(self.y)+")"
which might include code, classes, or functions. Output only the next line. | self._scanned_units.append(Unit(Location(screen_loc=Point(center_x, center_y)), |
Given snippet: <|code_start|> while len(queue) > 0:
cur = queue.pop()
if _try_explore(cur[0]+1, cur[1], queue, scanned):
sum_x += cur[0]+1
sum_y += cur[1]
nb_scanned += 1
if _try_explore(cur[0], cur[1]+1, queue, scanned):
sum_x += cur[0]
sum_y += cur[1]+1
nb_scanned += 1
if _try_explore(cur[0], cur[1]-1, queue, scanned):
sum_x += cur[0]
sum_y += cur[1]-1
nb_scanned += 1
return round(sum_x/nb_scanned), round(sum_y/nb_scanned)
screen_width = Screen.width(obs)
screen_height = Screen.height(obs)
scanned = np.zeros((screen_width, screen_height))
self._scanned_units = []
for x in range(screen_width):
for y in range(screen_height):
if scanned[x, y] == 0 and obs.observation[SCREEN][SCREEN_UNIT_TYPE][x, y] != 0:
center_x, center_y = _explore_contiguous(x, y,
obs.observation[SCREEN][SCREEN_UNIT_TYPE][x, y],
obs.observation[SCREEN][SCREEN_PLAYER_RELATIVE][x, y],
scanned)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import numpy as np
from oscar.constants import *
from oscar.util.unit import Unit
from oscar.util.location import Location
from oscar.util.point import Point
and context:
# Path: oscar/util/unit.py
# class Unit:
#
# def __init__(self, location, unit_id=None, player_id=None):
# self.location = location
# self.unit_id = unit_id
# self.player_id = player_id
#
# def equals(self, other):
# def is_same_location():
# return (not self.location and not other.location) \
# or (self.location and other.location and self.location.equals(other.location))
# def is_same_unit_id():
# return (self.unit_id is None and other.unit_id is None) \
# or (self.unit_id is not None and other.unit_id is not None and self.unit_id == other.unit_id)
# def is_same_player_id():
# return (self.player_id is None and other.player_id is None) \
# or (self.player_id is not None and other.player_id is not None and self.player_id == other.player_id)
#
# return is_same_location() and is_same_unit_id() and is_same_player_id()
#
# Path: oscar/util/location.py
# class Location:
#
# def __init__(self, minimap_loc=None, screen_loc=None, camera_loc=None):
# self.minimap = minimap_loc
# self.screen = screen_loc
# self.camera = camera_loc
#
# def compute_minimap_loc(self, obs, shared):
# scale_x = shared['camera'].width(obs) / shared['screen'].width(obs)
# scale_y = shared['camera'].height(obs) / shared['screen'].height(obs)
#
# self.minimap = shared['minimap'].bound(obs, Point(
# int(round(self.camera.x - 0.5*shared['camera'].width(obs) + self.screen.x * scale_x)),
# int(round(self.camera.y - 0.5*shared['camera'].height(obs) + self.screen.y * scale_y))))
#
# def squarred_distance(self, other):
# if not self.minimap or not other.minimap:
# raise Exception("Can't compute distance")
# return self.minimap.distance(other.minimap)
#
# def distance(self, other):
# return math.sqrt(self.squarred_distance(other))
#
# def equals(self, other):
# def equals_minimap():
# return (not self.minimap and not other.minimap) \
# or (self.minimap and other.minimap and self.minimap.equals(other.minimap))
#
# def equals_screen():
# return (not self.screen and not other.screen) \
# or (self.screen and other.screen and self.screen.equals(other.screen))
#
# def equals_camera():
# return (not self.camera and not other.camera) \
# or (self.camera and other.camera and self.camera.equals(other.camera))
#
# return equals_minimap() and equals_screen() and equals_camera()
#
# def __str__(self):
# return "Location {\n" \
# + " minimap: " + str(self.minimap) + "\n" \
# + " screen: " + str(self.screen) + "\n" \
# + " camera: " + str(self.camera) + "\n" \
# + "}"
#
# Path: oscar/util/point.py
# class Point:
#
# def __init__(self, x=None, y=None):
# self.x = x
# self.y = y
#
# def squared_distance(self, other):
# return (self.x-other.x)*(self.x-other.x) + (self.y-other.y)*(self.y-other.y)
#
# def distance(self, other):
# return math.sqrt(self.squared_distance(other))
#
# def get_flipped(self):
# return Point(self.y, self.x)
#
# def to_array(self):
# return [self.x, self.y]
#
# def equals(self, other):
# return self.x == other.x and self.y == other.y
#
# def difference(self, other):
# return Point(self.x - other.x, self.y - other.y)
#
# def addition(self, other):
# return Point(self.x + other.x, self.y + other.y)
#
# def __str__(self):
# return "Point("+str(self.x)+","+str(self.y)+")"
which might include code, classes, or functions. Output only the next line. | self._scanned_units.append(Unit(Location(screen_loc=Point(center_x, center_y)), |
Predict the next line after this snippet: <|code_start|>
class Screen(object):
def __init__(self):
""" cache data """
self._scanned_units = None
self._scanned_units_timestamp = None
@staticmethod
def width(obs):
return len(obs.observation[SCREEN][0])
@staticmethod
def height(obs):
return len(obs.observation[SCREEN][0][0])
@staticmethod
def random_point(obs, margin=0):
<|code_end|>
using the current file's imports:
import numpy as np
from oscar.constants import *
from oscar.util.unit import Unit
from oscar.util.location import Location
from oscar.util.point import Point
and any relevant context from other files:
# Path: oscar/util/unit.py
# class Unit:
#
# def __init__(self, location, unit_id=None, player_id=None):
# self.location = location
# self.unit_id = unit_id
# self.player_id = player_id
#
# def equals(self, other):
# def is_same_location():
# return (not self.location and not other.location) \
# or (self.location and other.location and self.location.equals(other.location))
# def is_same_unit_id():
# return (self.unit_id is None and other.unit_id is None) \
# or (self.unit_id is not None and other.unit_id is not None and self.unit_id == other.unit_id)
# def is_same_player_id():
# return (self.player_id is None and other.player_id is None) \
# or (self.player_id is not None and other.player_id is not None and self.player_id == other.player_id)
#
# return is_same_location() and is_same_unit_id() and is_same_player_id()
#
# Path: oscar/util/location.py
# class Location:
#
# def __init__(self, minimap_loc=None, screen_loc=None, camera_loc=None):
# self.minimap = minimap_loc
# self.screen = screen_loc
# self.camera = camera_loc
#
# def compute_minimap_loc(self, obs, shared):
# scale_x = shared['camera'].width(obs) / shared['screen'].width(obs)
# scale_y = shared['camera'].height(obs) / shared['screen'].height(obs)
#
# self.minimap = shared['minimap'].bound(obs, Point(
# int(round(self.camera.x - 0.5*shared['camera'].width(obs) + self.screen.x * scale_x)),
# int(round(self.camera.y - 0.5*shared['camera'].height(obs) + self.screen.y * scale_y))))
#
# def squarred_distance(self, other):
# if not self.minimap or not other.minimap:
# raise Exception("Can't compute distance")
# return self.minimap.distance(other.minimap)
#
# def distance(self, other):
# return math.sqrt(self.squarred_distance(other))
#
# def equals(self, other):
# def equals_minimap():
# return (not self.minimap and not other.minimap) \
# or (self.minimap and other.minimap and self.minimap.equals(other.minimap))
#
# def equals_screen():
# return (not self.screen and not other.screen) \
# or (self.screen and other.screen and self.screen.equals(other.screen))
#
# def equals_camera():
# return (not self.camera and not other.camera) \
# or (self.camera and other.camera and self.camera.equals(other.camera))
#
# return equals_minimap() and equals_screen() and equals_camera()
#
# def __str__(self):
# return "Location {\n" \
# + " minimap: " + str(self.minimap) + "\n" \
# + " screen: " + str(self.screen) + "\n" \
# + " camera: " + str(self.camera) + "\n" \
# + "}"
#
# Path: oscar/util/point.py
# class Point:
#
# def __init__(self, x=None, y=None):
# self.x = x
# self.y = y
#
# def squared_distance(self, other):
# return (self.x-other.x)*(self.x-other.x) + (self.y-other.y)*(self.y-other.y)
#
# def distance(self, other):
# return math.sqrt(self.squared_distance(other))
#
# def get_flipped(self):
# return Point(self.y, self.x)
#
# def to_array(self):
# return [self.x, self.y]
#
# def equals(self, other):
# return self.x == other.x and self.y == other.y
#
# def difference(self, other):
# return Point(self.x - other.x, self.y - other.y)
#
# def addition(self, other):
# return Point(self.x + other.x, self.y + other.y)
#
# def __str__(self):
# return "Point("+str(self.x)+","+str(self.y)+")"
. Output only the next line. | loc = Point() |
Given snippet: <|code_start|>
def get_micro_management_location(obs, shared):
_MICRO_DISTANCE = 6
player_relative = obs.observation[MINIMAP][MINI_PLAYER_RELATIVE]
locations = []
for y in range(shared['minimap'].height(obs)):
for x in range(shared['minimap'].width(obs)):
if player_relative[y, x] == PLAYER_SELF:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import random
import numpy as np
from oscar.constants import *
from oscar.util.point import Point
and context:
# Path: oscar/util/point.py
# class Point:
#
# def __init__(self, x=None, y=None):
# self.x = x
# self.y = y
#
# def squared_distance(self, other):
# return (self.x-other.x)*(self.x-other.x) + (self.y-other.y)*(self.y-other.y)
#
# def distance(self, other):
# return math.sqrt(self.squared_distance(other))
#
# def get_flipped(self):
# return Point(self.y, self.x)
#
# def to_array(self):
# return [self.x, self.y]
#
# def equals(self, other):
# return self.x == other.x and self.y == other.y
#
# def difference(self, other):
# return Point(self.x - other.x, self.y - other.y)
#
# def addition(self, other):
# return Point(self.x + other.x, self.y + other.y)
#
# def __str__(self):
# return "Point("+str(self.x)+","+str(self.y)+")"
which might include code, classes, or functions. Output only the next line. | p = Point(x, y) |
Given the following code snippet before the placeholder: <|code_start|>
def build_hierarchy(configuration_filename: str):
"""
Builds a hierarchy of agents from a json file
:param configuration_filename: the path of the configuration file to be loaded
:return: the general agent and a shared memory for training
"""
with open(configuration_filename) as configuration_file:
configuration = json.load(configuration_file)
# Convert structure ids to integers (in place)
configuration["structure"] = {int(k): [int(i) for i in v] for k, v in configuration["structure"].items()}
check_configuration(configuration)
# Create a maintained set of instantiated agents
instantiated = {}
# build shared objects to be associated with agents later
shared = build_shared(configuration)
# Setup a training memory for agent in training mode
<|code_end|>
, predict the next line using imports from the current file:
import json
from oscar.env.shared_objects import SharedObjects
and context including class names, function names, and sometimes code from other files:
# Path: oscar/env/shared_objects.py
# class SharedObjects:
# """
# Container for shared object between the game thread and the learning thread.
# Share observations and actions during training
# """
#
# def __init__(self):
# # Semaphore unlocked when the observation are set
# self.semaphore_obs_ready = threading.Semaphore(value=0)
# # Semaphore unlocked when the action is set
# self.semaphore_action_set = threading.Semaphore(value=0)
# # shared memory containing the action that must be done by the env
# self.shared_action = None
# # shared memory containing the observation get by the env
# self.shared_obs = None
# # number of possible action (set by the env)
# self.action_space = None
# # shape of the observations given by the env
# self.observation_space = None
# # vector masking defining the action that are available or not
# self.available_action_mask = None
. Output only the next line. | training_memory = SharedObjects() |
Predict the next line after this snippet: <|code_start|>
class Location:
def __init__(self, minimap_loc=None, screen_loc=None, camera_loc=None):
self.minimap = minimap_loc
self.screen = screen_loc
self.camera = camera_loc
def compute_minimap_loc(self, obs, shared):
scale_x = shared['camera'].width(obs) / shared['screen'].width(obs)
scale_y = shared['camera'].height(obs) / shared['screen'].height(obs)
<|code_end|>
using the current file's imports:
import math
from oscar.util.point import Point
and any relevant context from other files:
# Path: oscar/util/point.py
# class Point:
#
# def __init__(self, x=None, y=None):
# self.x = x
# self.y = y
#
# def squared_distance(self, other):
# return (self.x-other.x)*(self.x-other.x) + (self.y-other.y)*(self.y-other.y)
#
# def distance(self, other):
# return math.sqrt(self.squared_distance(other))
#
# def get_flipped(self):
# return Point(self.y, self.x)
#
# def to_array(self):
# return [self.x, self.y]
#
# def equals(self, other):
# return self.x == other.x and self.y == other.y
#
# def difference(self, other):
# return Point(self.x - other.x, self.y - other.y)
#
# def addition(self, other):
# return Point(self.x + other.x, self.y + other.y)
#
# def __str__(self):
# return "Point("+str(self.x)+","+str(self.y)+")"
. Output only the next line. | self.minimap = shared['minimap'].bound(obs, Point( |
Given snippet: <|code_start|>
self.R = 0
"""
Last n samples are stored in this buffer and when there are enough of them,
n-step discounted reward R is computed.
Proper variables are retrieved and a tuple (s_0, a_0, R, s_n) is inserted into the brain’s training queue.
"""
if len(self.memory) >= N_STEP_RETURN:
s, a, r, s_ = get_sample(self.memory, N_STEP_RETURN)
brain.train_push(s, a, r, s_)
self.R = self.R - self.memory[0][2]
self.memory.pop(0)
# possible edge case - if an episode ends in <N steps, the computation is incorrect
class Environment(threading.Thread):
"""
The Environment class is an instance of OpenAI Gym environment and contains an instance of Agent.
It is also a thread that continuously runs one episode after another.
"""
stop_signal = False
def __init__(self, global_brain, num_actions, render=False, eps_start=EPS_START, eps_end=EPS_STOP, eps_steps=EPS_STEPS):
threading.Thread.__init__(self)
global brain, NUM_ACTIONS
brain = global_brain
NUM_ACTIONS = num_actions
self.render = render
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import gym
import time
import random
import threading
import numpy as np
import os
import pandas as pd
import warnings
from learning_tools.A3C_learner.constants import *
from oscar.env.envs.general_learning_env import GeneralLearningEnv
and context:
# Path: oscar/env/envs/general_learning_env.py
# class GeneralLearningEnv(gym.Env):
# def __init__(self, configuration_file=DEFAULT_CONFIGURATION, enable_visualisation=True, game_steps_per_update=8,
# log_file_path=None, publish_stats=True):
# self.env_thread = Pysc2EnvRunner(configuration_file=configuration_file,
# enable_visualisation=enable_visualisation,
# game_steps_per_update=game_steps_per_update)
# self.shared_memory = self.env_thread.shared_memory
# self.log_file = log_file_path
# self.publish_stats = publish_stats
# # get semaphores from shared memory
# self.semaphore_obs_ready = self.shared_memory.semaphore_obs_ready
# self.semaphore_action_set = self.shared_memory.semaphore_action_set
# # set action/observation space from shared memory
# self.action_space = self.shared_memory.action_space
# self.observation_space = self.shared_memory.observation_space
# # start thread
# self.env_thread.start()
#
# def step(self, action):
# info_dict = {}
# # set action into shared memory
# self.shared_memory.shared_action = action
# # let the thread run again
# self.semaphore_action_set.release()
# # increase the number of steps performed by the learning agent
# self.env_thread.learning_agent_step += 1
# # wait a call to the target agent
# self.semaphore_obs_ready.acquire(blocking=True, timeout=None)
# # get the obs of the current state as seen by the agent
# obs = self.shared_memory.shared_obs
# # get the reward of the current run and reset it to 0 for next step
# reward = self.env_thread.reward # / self.env_thread.step_count
# self.env_thread.reward = 0
# # get done state from thread
# done = self.env_thread.was_done
# if done:
# self.env_thread.was_done = False # reset was_done to false for next loop
# if self.publish_stats:
# info_dict["stats"] = self.env_thread.stats
# # log result to disk if asked
# if self.log_file is not None and self.env_thread.stats is not None:
# if os.path.isfile(self.log_file):
# self.env_thread.stats.to_csv(self.log_file, sep=',', mode='a', header=False)
# else:
# self.env_thread.stats.to_csv(self.log_file, sep=',', mode='w', header=True)
# # return current obs
# return obs.copy(), reward, done, info_dict
#
# def reset(self):
# # wait for the env to stop as waiting action
# self.semaphore_obs_ready.acquire(blocking=True, timeout=None)
# return self.shared_memory.shared_obs
#
# def close(self):
# self.env_thread.stop = True
# self.semaphore_action_set.release() # to be sure that the thread go to stop condition
#
# def render(self, mode='human', close=False):
# pass
#
# def seed(self, seed=None):
# pass
#
# def get_action_mask(self):
# # every action is supposed to be playable
# # return np.ones(shape=self.action_space.n)
# # get the actions available according to the learning agent
# return self.shared_memory.available_action_mask
which might include code, classes, or functions. Output only the next line. | self.env = GeneralLearningEnv(CONFIGURATION_FILE, ENABLE_PYSC2_GUI) |
Here is a snippet: <|code_start|> pass
def seed(self, seed=None):
pass
def get_action_mask(self):
# every action is supposed to be playable
# return np.ones(shape=self.action_space.n)
# get the actions available according to the learning agent
return self.shared_memory.available_action_mask
class Pysc2EnvRunner(threading.Thread):
def __init__(self, configuration_file, enable_visualisation, game_steps_per_update):
self.done = False
self.was_done = False
self.reward = 0
self.last_army_count = 0
self.last_killed_units = 0
self.last_killed_building = 0
self.step_count = 0
self.last_obs = None
self.stats = None
self.game_steps_per_update = game_steps_per_update
# variable for stats
self.episodes_reward = []
self.start_time = 0
self.learning_agent_step = 0
# setup env
<|code_end|>
. Write the next line using the current file imports:
import gym
import threading
import numpy as np
import pandas as pd
import time
import os
from gym import spaces
from oscar.env.envs.pysc2_general_env import Pysc2GeneralEnv
from oscar.constants import *
and context from other files:
# Path: oscar/env/envs/pysc2_general_env.py
# class Pysc2GeneralEnv(Pysc2Env):
# """
# Gym version of the pysc2 env using the OSCAR general/commander/agent structure
# """
#
# # action_space = spaces.Discrete(1)
# # observation_space = None # set in init
#
# def __init__(self,
# path_to_configuration=DEFAULT_CONFIGURATION,
# enable_visualisation=True,
# game_step_per_update=8):
# self.pysc2_env = SC2Env( # map_name='CollectMineralsAndGas',
# map_name='Simple64',
# players=[Agent(Race.terran),
# Bot(Race.random, Difficulty.very_easy)],
# agent_interface_format=[AgentInterfaceFormat(feature_dimensions=Dimensions(screen=(SCREEN_RESOLUTION,
# SCREEN_RESOLUTION),
# minimap=(MINIMAP_RESOLUTION,
# MINIMAP_RESOLUTION)),
# camera_width_world_units=TILES_VISIBLE_ON_SCREEN_WIDTH)],
# # git version give camera position in observation if asked
# visualize=enable_visualisation,
# step_mul=game_step_per_update,
# game_steps_per_episode=None # use map default
# )
# self.general = General(path_to_configuration)
# action_spec = self.pysc2_env.action_spec()
# observation_spec = self.pysc2_env.observation_spec()
# self.general.setup(observation_spec, action_spec)
# # self.observation_space = self.general.training_memory.observation_space
# super().__init__()
#
# def step(self, action):
# """
# This beautiful environment as a good sens of hierarchy.
# He has a general and his general is better than you, and so the action you give
# is pointless and general will choose what is a good idea (when you only have one
# choice its easier for you, no ?).
# :param action: an int, if you want but None is fine too (dict, tuple and object
# are accepted but not recommended)
# :return: a tuple with the observation, reward, done and an empty dict
# """
# action = self.general.step(self.last_obs)
# obs, reward, done, debug_dict = super().step([action])
# # explore observation to decide if agent can still play
# # first condition is to check if a command center exist
# # second is to check if the agent has unit or minerals to create one
# if obs.observation[PLAYER][FOOD_CAP] < 15 \
# or (obs.observation[PLAYER][FOOD_USED] == 0 and obs.observation[PLAYER][MINERALS] < 50):
# warnings.warn("Environment decided that game is lost")
# done = True
# return obs, reward, done, debug_dict
#
# def reset(self):
# self.general.reset()
# return super().reset()
#
# def render(self, mode='human', close=False):
# super().render(mode, close)
#
# def close(self):
# super().close()
#
# def seed(self, seed=None):
# super().seed(seed)
#
# def get_action_mask(self):
# return None # no action required here
, which may include functions, classes, or code. Output only the next line. | self.env = Pysc2GeneralEnv(configuration_file, enable_visualisation, game_steps_per_update) |
Predict the next line for this snippet: <|code_start|> self._state = ArmySupplier._TRAINING_MARINE
""" Executes states """
if self._state == ArmySupplier._BUILDING_BARRACKS:
if not self._worker_selected:
if obs.observation[PLAYER][IDLE_WORKER_COUNT] > 0:
play['actions'] = [actions.FunctionCall(SELECT_IDLE_WORKER, [NEW_SELECTION])]
self._worker_selected = True
else: # if no idle scv, select one randomly
on_screen_scv = self._shared['screen'].scan_units(obs, self._shared, [TERRAN_SCV], PLAYER_SELF)
if len(on_screen_scv) == 0:
if len(self._shared['economy'].command_centers) > 0:
selected_command_center = random.choice(self._shared['economy'].command_centers)
play['actions'] = [actions.FunctionCall(MOVE_CAMERA,
[selected_command_center.camera.to_array()])]
else:
selected_scv = random.choice(on_screen_scv)
play['actions'] = [actions.FunctionCall(SELECT_POINT,
[NEW_SELECTION,
selected_scv.location.screen.get_flipped().to_array()])]
self._worker_selected = True
elif BUILD_BARRACKS in obs.observation["available_actions"]:
building_center = get_random_building_point(obs, self._shared, 15)
if building_center:
play['actions'] = [actions.FunctionCall(BUILD_BARRACKS,
[NOT_QUEUED, building_center.get_flipped().to_array()])]
self._shared['army'].add_barracks(obs, self._shared,
<|code_end|>
with the help of current file imports:
import random
from oscar.agent.custom_agent import CustomAgent
from oscar.constants import *
from oscar.meta_action.build import *
from oscar.util.location import Location
and context from other files:
# Path: oscar/agent/custom_agent.py
# class CustomAgent(BaseAgent):
# """A base agent to write custom scripted agents."""
#
# def __init__(self):
# super().__init__()
# self._shared = {}
#
# def add_shared(self, name, shared):
# self._shared[name] = shared
#
# Path: oscar/util/location.py
# class Location:
#
# def __init__(self, minimap_loc=None, screen_loc=None, camera_loc=None):
# self.minimap = minimap_loc
# self.screen = screen_loc
# self.camera = camera_loc
#
# def compute_minimap_loc(self, obs, shared):
# scale_x = shared['camera'].width(obs) / shared['screen'].width(obs)
# scale_y = shared['camera'].height(obs) / shared['screen'].height(obs)
#
# self.minimap = shared['minimap'].bound(obs, Point(
# int(round(self.camera.x - 0.5*shared['camera'].width(obs) + self.screen.x * scale_x)),
# int(round(self.camera.y - 0.5*shared['camera'].height(obs) + self.screen.y * scale_y))))
#
# def squarred_distance(self, other):
# if not self.minimap or not other.minimap:
# raise Exception("Can't compute distance")
# return self.minimap.distance(other.minimap)
#
# def distance(self, other):
# return math.sqrt(self.squarred_distance(other))
#
# def equals(self, other):
# def equals_minimap():
# return (not self.minimap and not other.minimap) \
# or (self.minimap and other.minimap and self.minimap.equals(other.minimap))
#
# def equals_screen():
# return (not self.screen and not other.screen) \
# or (self.screen and other.screen and self.screen.equals(other.screen))
#
# def equals_camera():
# return (not self.camera and not other.camera) \
# or (self.camera and other.camera and self.camera.equals(other.camera))
#
# return equals_minimap() and equals_screen() and equals_camera()
#
# def __str__(self):
# return "Location {\n" \
# + " minimap: " + str(self.minimap) + "\n" \
# + " screen: " + str(self.screen) + "\n" \
# + " camera: " + str(self.camera) + "\n" \
# + "}"
, which may contain function names, class names, or code. Output only the next line. | Location( |
Given the code snippet: <|code_start|>
class Camera(object):
def __init__(self):
""" cache data """
self._location = None
self._location_timestamp = None
self._width = None
self._height = None
def location(self, obs, shared):
if not self._location_timestamp or self._location_timestamp != shared['env'].timestamp:
mini_camera = obs.observation[MINIMAP][MINI_CAMERA]
camera_y, camera_x = (mini_camera == 1).nonzero()
<|code_end|>
, generate the next line using the imports in this file:
import numpy as np
from oscar.util.point import Point
from oscar.constants import *
and context (functions, classes, or occasionally code) from other files:
# Path: oscar/util/point.py
# class Point:
#
# def __init__(self, x=None, y=None):
# self.x = x
# self.y = y
#
# def squared_distance(self, other):
# return (self.x-other.x)*(self.x-other.x) + (self.y-other.y)*(self.y-other.y)
#
# def distance(self, other):
# return math.sqrt(self.squared_distance(other))
#
# def get_flipped(self):
# return Point(self.y, self.x)
#
# def to_array(self):
# return [self.x, self.y]
#
# def equals(self, other):
# return self.x == other.x and self.y == other.y
#
# def difference(self, other):
# return Point(self.x - other.x, self.y - other.y)
#
# def addition(self, other):
# return Point(self.x + other.x, self.y + other.y)
#
# def __str__(self):
# return "Point("+str(self.x)+","+str(self.y)+")"
. Output only the next line. | self._location = Point(round(sum(camera_x)/len(camera_x)), round(sum(camera_y)/len(camera_y))) |
Continue the code snippet: <|code_start|>RANDOM_CENTER_MOVE_FACTOR = 2
RANDOM_CENTER_ITERATION_LIMIT = 5
def find_position(obs, unit_type_id, select_method="random_center", player_relative=PLAYER_SELF, exception=NoUnitError):
# unit_type_id is either an iterable, or a single int. In case it is a single int, it is embedded in a list,
# so it will be process as an iterable afterward.
try:
unit_type_id_list = list(unit_type_id)
except TypeError:
unit_type_id_list = [unit_type_id]
unit_type_map = obs.observation[SCREEN][SCREEN_UNIT_TYPE]
player_relative_map = obs.observation[SCREEN][SCREEN_PLAYER_RELATIVE]
correct_unit_type_array = np.isin(unit_type_map, unit_type_id_list)
correct_player_relative_array = (player_relative_map == player_relative)
unit_y, unit_x = (correct_unit_type_array & correct_player_relative_array).nonzero()
if len(unit_x) == 0:
raise exception("Unit of id {0} for the player_relative {1} is not on the screen."
.format(unit_type_id_list, player_relative))
if select_method == "random_center":
return find_random_center(unit_type_map, unit_x, unit_y, unit_type_id_list)
elif select_method == "random":
return random.choice(list(zip(unit_x, unit_y)))
elif select_method == "mean":
return int(unit_x.mean()), int(unit_y.mean())
elif select_method == "all":
return unit_x, unit_y
elif select_method == "screen_scan":
<|code_end|>
. Use current file imports:
import random
import numpy as np
from scipy.signal import convolve2d
from oscar.constants import *
from oscar.meta_action.meta_action_error import *
from oscar.shared.env import Env
from oscar.shared.screen import Screen
and context (classes, functions, or code) from other files:
# Path: oscar/shared/env.py
# class Env:
#
# timestamp = 0
#
# Path: oscar/shared/screen.py
# class Screen(object):
#
# def __init__(self):
# """ cache data """
# self._scanned_units = None
# self._scanned_units_timestamp = None
#
# @staticmethod
# def width(obs):
# return len(obs.observation[SCREEN][0])
#
# @staticmethod
# def height(obs):
# return len(obs.observation[SCREEN][0][0])
#
# @staticmethod
# def random_point(obs, margin=0):
# loc = Point()
# loc.x = np.random.randint(margin, Screen.width(obs)-margin-1)
# loc.y = np.random.randint(margin, Screen.height(obs)-margin-1)
# return loc
#
# def scan_units(self, obs, shared, unit_ids, player_id):
# scan = self.scan(obs, shared)
# return [u for u in scan if u.unit_id in unit_ids and u.player_id == player_id]
#
# def scan(self, obs, shared):
# """ Returns a list of the units on screen """
#
# if not self._scanned_units_timestamp or self._scanned_units_timestamp != shared['env'].timestamp:
# def _explore_contiguous(x, y, unit_id, player_relative, scanned):
# """
# Explores contiguous pixels corresponding to the same unit
# and returns approximate center of the unit.
# """
#
# def _try_explore(x, y, queue, scanned):
# if x < screen_width and y < screen_height \
# and scanned[x, y] == 0 \
# and obs.observation[SCREEN][SCREEN_PLAYER_RELATIVE][x, y] == player_relative \
# and obs.observation[SCREEN][SCREEN_UNIT_TYPE][x, y] == unit_id:
# queue.append((x, y))
# scanned[x, y] = 1
# return True
# else:
# return False
#
# sum_x, sum_y, nb_scanned = x, y, 1
# queue = []
# queue.append((x, y))
#
# while len(queue) > 0:
# cur = queue.pop()
# if _try_explore(cur[0]+1, cur[1], queue, scanned):
# sum_x += cur[0]+1
# sum_y += cur[1]
# nb_scanned += 1
# if _try_explore(cur[0], cur[1]+1, queue, scanned):
# sum_x += cur[0]
# sum_y += cur[1]+1
# nb_scanned += 1
# if _try_explore(cur[0], cur[1]-1, queue, scanned):
# sum_x += cur[0]
# sum_y += cur[1]-1
# nb_scanned += 1
#
# return round(sum_x/nb_scanned), round(sum_y/nb_scanned)
#
# screen_width = Screen.width(obs)
# screen_height = Screen.height(obs)
# scanned = np.zeros((screen_width, screen_height))
# self._scanned_units = []
#
# for x in range(screen_width):
# for y in range(screen_height):
# if scanned[x, y] == 0 and obs.observation[SCREEN][SCREEN_UNIT_TYPE][x, y] != 0:
# center_x, center_y = _explore_contiguous(x, y,
# obs.observation[SCREEN][SCREEN_UNIT_TYPE][x, y],
# obs.observation[SCREEN][SCREEN_PLAYER_RELATIVE][x, y],
# scanned)
#
# self._scanned_units.append(Unit(Location(screen_loc=Point(center_x, center_y)),
# obs.observation[SCREEN][SCREEN_UNIT_TYPE][x, y],
# obs.observation[SCREEN][SCREEN_PLAYER_RELATIVE][x, y]))
#
# self._scanned_units_timestamp = shared['env'].timestamp
#
# return self._scanned_units
. Output only the next line. | shared = {'env': Env} |
Predict the next line after this snippet: <|code_start|>RANDOM_CENTER_ITERATION_LIMIT = 5
def find_position(obs, unit_type_id, select_method="random_center", player_relative=PLAYER_SELF, exception=NoUnitError):
# unit_type_id is either an iterable, or a single int. In case it is a single int, it is embedded in a list,
# so it will be process as an iterable afterward.
try:
unit_type_id_list = list(unit_type_id)
except TypeError:
unit_type_id_list = [unit_type_id]
unit_type_map = obs.observation[SCREEN][SCREEN_UNIT_TYPE]
player_relative_map = obs.observation[SCREEN][SCREEN_PLAYER_RELATIVE]
correct_unit_type_array = np.isin(unit_type_map, unit_type_id_list)
correct_player_relative_array = (player_relative_map == player_relative)
unit_y, unit_x = (correct_unit_type_array & correct_player_relative_array).nonzero()
if len(unit_x) == 0:
raise exception("Unit of id {0} for the player_relative {1} is not on the screen."
.format(unit_type_id_list, player_relative))
if select_method == "random_center":
return find_random_center(unit_type_map, unit_x, unit_y, unit_type_id_list)
elif select_method == "random":
return random.choice(list(zip(unit_x, unit_y)))
elif select_method == "mean":
return int(unit_x.mean()), int(unit_y.mean())
elif select_method == "all":
return unit_x, unit_y
elif select_method == "screen_scan":
shared = {'env': Env}
<|code_end|>
using the current file's imports:
import random
import numpy as np
from scipy.signal import convolve2d
from oscar.constants import *
from oscar.meta_action.meta_action_error import *
from oscar.shared.env import Env
from oscar.shared.screen import Screen
and any relevant context from other files:
# Path: oscar/shared/env.py
# class Env:
#
# timestamp = 0
#
# Path: oscar/shared/screen.py
# class Screen(object):
#
# def __init__(self):
# """ cache data """
# self._scanned_units = None
# self._scanned_units_timestamp = None
#
# @staticmethod
# def width(obs):
# return len(obs.observation[SCREEN][0])
#
# @staticmethod
# def height(obs):
# return len(obs.observation[SCREEN][0][0])
#
# @staticmethod
# def random_point(obs, margin=0):
# loc = Point()
# loc.x = np.random.randint(margin, Screen.width(obs)-margin-1)
# loc.y = np.random.randint(margin, Screen.height(obs)-margin-1)
# return loc
#
# def scan_units(self, obs, shared, unit_ids, player_id):
# scan = self.scan(obs, shared)
# return [u for u in scan if u.unit_id in unit_ids and u.player_id == player_id]
#
# def scan(self, obs, shared):
# """ Returns a list of the units on screen """
#
# if not self._scanned_units_timestamp or self._scanned_units_timestamp != shared['env'].timestamp:
# def _explore_contiguous(x, y, unit_id, player_relative, scanned):
# """
# Explores contiguous pixels corresponding to the same unit
# and returns approximate center of the unit.
# """
#
# def _try_explore(x, y, queue, scanned):
# if x < screen_width and y < screen_height \
# and scanned[x, y] == 0 \
# and obs.observation[SCREEN][SCREEN_PLAYER_RELATIVE][x, y] == player_relative \
# and obs.observation[SCREEN][SCREEN_UNIT_TYPE][x, y] == unit_id:
# queue.append((x, y))
# scanned[x, y] = 1
# return True
# else:
# return False
#
# sum_x, sum_y, nb_scanned = x, y, 1
# queue = []
# queue.append((x, y))
#
# while len(queue) > 0:
# cur = queue.pop()
# if _try_explore(cur[0]+1, cur[1], queue, scanned):
# sum_x += cur[0]+1
# sum_y += cur[1]
# nb_scanned += 1
# if _try_explore(cur[0], cur[1]+1, queue, scanned):
# sum_x += cur[0]
# sum_y += cur[1]+1
# nb_scanned += 1
# if _try_explore(cur[0], cur[1]-1, queue, scanned):
# sum_x += cur[0]
# sum_y += cur[1]-1
# nb_scanned += 1
#
# return round(sum_x/nb_scanned), round(sum_y/nb_scanned)
#
# screen_width = Screen.width(obs)
# screen_height = Screen.height(obs)
# scanned = np.zeros((screen_width, screen_height))
# self._scanned_units = []
#
# for x in range(screen_width):
# for y in range(screen_height):
# if scanned[x, y] == 0 and obs.observation[SCREEN][SCREEN_UNIT_TYPE][x, y] != 0:
# center_x, center_y = _explore_contiguous(x, y,
# obs.observation[SCREEN][SCREEN_UNIT_TYPE][x, y],
# obs.observation[SCREEN][SCREEN_PLAYER_RELATIVE][x, y],
# scanned)
#
# self._scanned_units.append(Unit(Location(screen_loc=Point(center_x, center_y)),
# obs.observation[SCREEN][SCREEN_UNIT_TYPE][x, y],
# obs.observation[SCREEN][SCREEN_PLAYER_RELATIVE][x, y]))
#
# self._scanned_units_timestamp = shared['env'].timestamp
#
# return self._scanned_units
. Output only the next line. | screen = Screen() |
Given the following code snippet before the placeholder: <|code_start|>
"""API Constants"""
_PLAYER_RELATIVE = features.SCREEN_FEATURES.player_relative.index
_PLAYER_FRIENDLY = 1
_PLAYER_NEUTRAL = 3 # beacon/minerals
_PLAYER_HOSTILE = 4
_NO_OP = actions.FUNCTIONS.no_op.id
_MOVE_SCREEN = actions.FUNCTIONS.Move_screen.id
_ATTACK_SCREEN = actions.FUNCTIONS.Attack_screen.id
_SELECT_ARMY = actions.FUNCTIONS.select_army.id
_NOT_QUEUED = [0]
_SELECT_ALL = [0]
<|code_end|>
, predict the next line using imports from the current file:
from pysc2.env.sc2_env import SC2Env
from pysc2.lib import actions
from pysc2.lib import features
from gym import spaces
from oscar.env.envs.pysc2_env import Pysc2Env
import numpy as np
and context including class names, function names, and sometimes code from other files:
# Path: oscar/env/envs/pysc2_env.py
# class Pysc2Env(gym.Env):
# """
# abstract class for building pysc2 env for Gym
# """
# metadata = {'render.modes': ['human']}
#
# # must be defined by sub class !
# pysc2_env = None
#
# last_obs = None
#
# def __init__(self):
# pass
#
# def step(self, action):
# """
# move the environment forward of one step
# :param action: a pysc2 action (a list of one pysc2 function call)
# :return: tuple of pysc2 full observation structure, the reward for the step, if is the last
# step or not and a dict to debug information (empty)
# """
# # Pysc2 can take a list of action :
# # ( https://github.com/deepmind/pysc2/blob/7a04e74effc88d3e2fe0e4562c99a18d06a099b2/pysc2/env/sc2_env.py#L247 )
# self.last_obs = self.pysc2_env.step(action)[0]
# done = self.last_obs.step_type == environment.StepType.LAST
# return self.last_obs, self.last_obs.reward, done, {}
#
# def reset(self):
# self.last_obs = self.pysc2_env.reset()[0]
# return self.last_obs
#
# def render(self, mode='human', close=False):
# pass
#
# def close(self):
# self.pysc2_env.close()
#
# def seed(self, seed=None):
# # any way to set the seed of pysc2 ?
# pass
#
# def get_action_mask(self):
# pass
. Output only the next line. | class Pysc2MineralshardEnv(Pysc2Env): |
Here is a snippet: <|code_start|>
class CollectIdleScvCommander(ContextSaveCommander):
def __init__(self, subordinates: list):
super().__init__(subordinates)
if len(subordinates) != 2:
raise ValueError("CollectIdleScvCommander can only manage two subordinate")
self.idle_manager = None
self.other_subordinate = None
for a in subordinates:
<|code_end|>
. Write the next line using the current file imports:
from oscar.agent.commander.context_save_commender import ContextSaveCommander
from oscar.agent.scripted.idle_scv import IdleSCVManagerBasic
from oscar.constants import *
and context from other files:
# Path: oscar/agent/commander/context_save_commender.py
# class ContextSaveCommander(BaseCommander):
# def __init__(self, subordinates: list):
# super().__init__(subordinates=subordinates)
# self._subordinate_context = {}
# self._is_changing_context = False
# self.add_shared('env', Env())
# self.add_shared('camera', Camera())
#
# def step(self, obs, locked_choice=None):
# self._shared['env'].timestamp += 1
#
# if locked_choice is None:
# locked_choice = self._locked_choice
#
# # if we were changing context do not ask for choosing a subordinate
# if self._is_changing_context:
# self._is_changing_context = False
# playing_subordinate = self._playing_subordinate
# else:
# playing_subordinate = self.choose_subordinate(obs, locked_choice)
#
# # if we are changing active subordinate, save and restore context (require one action)
# if playing_subordinate is not self._playing_subordinate and self._playing_subordinate is not None:
# self.save_context(obs)
# play = self.restore_context(playing_subordinate, obs)
# self._playing_subordinate = playing_subordinate
# else:
# self._playing_subordinate = playing_subordinate
# play = self._playing_subordinate.step(obs, locked_choice)
# if "locked_choice" in play:
# self._locked_choice = play["locked_choice"]
# else:
# self._locked_choice = False
# return play
#
# def restore_context(self, subordinate, obs):
# if subordinate not in self._subordinate_context:
# context = AgentContext()
# location = self._shared['camera'].location(obs=obs, shared=self._shared)
# context.camera = location
# else:
# context = self._subordinate_context[subordinate]
# play = {}
# play['actions'] = [actions.FunctionCall(MOVE_CAMERA, [context.camera.to_array()])]
# play['locked_choice'] = True
# self._is_changing_context = True
# return play
#
# def save_context(self, obs):
# context = AgentContext()
# location = self._shared['camera'].location(obs=obs, shared=self._shared)
# context.camera = location
# self._subordinate_context[self._playing_subordinate] = context
#
# @abstractmethod
# def choose_subordinate(self, obs, locked_choice):
# """
# Choose a subordinate among the list of subordinates, and make it play.
# :return: A subordinate among the list of subordinates.
# """
#
# def reset(self):
# super().reset()
# self._subordinate_context = {}
# self._is_changing_context = False
# self.add_shared('env', Env())
# self.add_shared('camera', Camera())
#
# Path: oscar/agent/scripted/idle_scv.py
# class IdleSCVManagerBasic(CustomAgent):
# def __init__(self):
# super().__init__()
# self.command_center_pos = None
# self.add_shared('env', Env())
# self.add_shared('camera', Camera())
#
# def step(self, obs, locked_choice=None):
# self._shared['env'].timestamp += 1
# if self._shared['env'].timestamp == 1:
# self.command_center_pos = self._shared['camera'].location(obs=obs, shared=self._shared)
# play = {}
# # if a scv is already selected it was most probably selected during last call
# # but in case we just queue the harvest order
# if obs.observation['single_select'][0][0] == TERRAN_SCV:
# try:
# play['actions'] = harvest_mineral(obs, queued=True)
# except NoUnitError:
# # if we get here, chance are that no more command center exist, send scv to attack !
# play['actions'] = attack_minimap(obs, queued=True)
# # select a new idle scv to prevent looping on the same
# try:
# play['actions'] += select_idle_scv(obs)
# except NoValidSCVError:
# pass
# elif SELECT_IDLE_WORKER in obs.observation['available_actions']:
# play['actions'] = select_idle_scv(obs)
# try:
# # if we still have a command center somewhere
# if obs.observation[PLAYER][FOOD_CAP] % 8 != 0:
# play['actions'] += harvest_mineral(obs)
# else:
# play['actions'] += attack_minimap(obs, queued=True)
# except NoUnitError:
# play['actions'] += [actions.FunctionCall(MOVE_CAMERA, [self.command_center_pos.to_array()])]
# play['locked_choice'] = True
# else:
# play['actions'] = [actions.FunctionCall(NO_OP, [])]
#
# return play
#
# def reset(self):
# super().reset()
# self.command_center_pos = None
# self.add_shared('env', Env())
# self.add_shared('camera', Camera())
, which may include functions, classes, or code. Output only the next line. | if type(a) == IdleSCVManagerBasic: |
Given the code snippet: <|code_start|>
DEFAULT_CONFIGURATION = "config/full_hierarchy.json"
# DEFAULT_CONFIGURATION = "config/idleSCVtest.json"
class General(BaseAgent):
"""
The agent at the top of the command chain. It is usually him that will be the interface with PySC2
"""
def __init__(self, configuration_filename=DEFAULT_CONFIGURATION):
"""
Initializes members and call hierarchy factory
:param configuration_filename: The configuration file to pass to the hierarchy factory on launch
"""
super().__init__()
<|code_end|>
, generate the next line using the imports in this file:
from pysc2.lib import actions
from pysc2.agents.base_agent import BaseAgent
from oscar.hiearchy_factory import build_hierarchy
from oscar.constants import NO_OP
import time
and context (functions, classes, or occasionally code) from other files:
# Path: oscar/hiearchy_factory.py
# def build_hierarchy(configuration_filename: str):
# """
# Builds a hierarchy of agents from a json file
# :param configuration_filename: the path of the configuration file to be loaded
# :return: the general agent and a shared memory for training
# """
# with open(configuration_filename) as configuration_file:
# configuration = json.load(configuration_file)
#
# # Convert structure ids to integers (in place)
# configuration["structure"] = {int(k): [int(i) for i in v] for k, v in configuration["structure"].items()}
# check_configuration(configuration)
#
# # Create a maintained set of instantiated agents
# instantiated = {}
#
# # build shared objects to be associated with agents later
# shared = build_shared(configuration)
#
# # Setup a training memory for agent in training mode
# training_memory = SharedObjects()
#
# # Build hierarchy and return general's children
# general_agent = build_agent(configuration, instantiated, shared, 0, training_memory)
#
# # if the training memory is not set with agent value, then nobody use it
# # then delete it
# if training_memory.action_space is None:
# training_memory = None
#
# return general_agent, training_memory
#
# Path: oscar/constants.py
# NO_OP = actions.FUNCTIONS.no_op.id
. Output only the next line. | self._child, self.training_memory = build_hierarchy(configuration_filename) |
Here is a snippet: <|code_start|> child_return = self._child.step(obs)
self._action_list = child_return["actions"]
try:
self._success_callback = child_return["success_callback"]
except KeyError:
self._success_callback = None
try:
self._failure_callback = child_return["failure_callback"]
except KeyError:
self._failure_callback = None
return self._check_and_return_action(obs)
def _check_and_return_action(self, obs):
"""
Check that the first action in self._action_list is among available actions, and return it.
If it is not, return call the callback argument provided by the last agent, empty the action list,
and return NO_OP.
Precondition: self._action_list is not empty.
:param obs: The observation provided by pysc2.
:return: The first action of the action list if it is valid, else NO_OP
"""
current_action = self._action_list.pop(0)
if current_action.function in obs.observation["available_actions"] \
and self._check_argument(current_action):
self._success = True
return current_action
else:
self._action_list = []
self._success = False
<|code_end|>
. Write the next line using the current file imports:
from pysc2.lib import actions
from pysc2.agents.base_agent import BaseAgent
from oscar.hiearchy_factory import build_hierarchy
from oscar.constants import NO_OP
import time
and context from other files:
# Path: oscar/hiearchy_factory.py
# def build_hierarchy(configuration_filename: str):
# """
# Builds a hierarchy of agents from a json file
# :param configuration_filename: the path of the configuration file to be loaded
# :return: the general agent and a shared memory for training
# """
# with open(configuration_filename) as configuration_file:
# configuration = json.load(configuration_file)
#
# # Convert structure ids to integers (in place)
# configuration["structure"] = {int(k): [int(i) for i in v] for k, v in configuration["structure"].items()}
# check_configuration(configuration)
#
# # Create a maintained set of instantiated agents
# instantiated = {}
#
# # build shared objects to be associated with agents later
# shared = build_shared(configuration)
#
# # Setup a training memory for agent in training mode
# training_memory = SharedObjects()
#
# # Build hierarchy and return general's children
# general_agent = build_agent(configuration, instantiated, shared, 0, training_memory)
#
# # if the training memory is not set with agent value, then nobody use it
# # then delete it
# if training_memory.action_space is None:
# training_memory = None
#
# return general_agent, training_memory
#
# Path: oscar/constants.py
# NO_OP = actions.FUNCTIONS.no_op.id
, which may include functions, classes, or code. Output only the next line. | return actions.FunctionCall(NO_OP, []) |
Predict the next line for this snippet: <|code_start|>
def is_enemy_visible(obs):
player_relative = obs.observation[MINIMAP][MINI_PLAYER_RELATIVE]
hostile_y, hostile_x = (player_relative == PLAYER_HOSTILE).nonzero()
return len(hostile_x) > 0
def get_random_enemy_location(obs):
player_relative = obs.observation[MINIMAP][MINI_PLAYER_RELATIVE]
hostile_y, hostile_x = (player_relative == PLAYER_HOSTILE).nonzero()
if len(hostile_x) == 0:
return None
else:
hostile = list(zip(hostile_x, hostile_y))
selected = random.choice(hostile)
<|code_end|>
with the help of current file imports:
import random
from oscar.constants import *
from oscar.util.point import Point
and context from other files:
# Path: oscar/util/point.py
# class Point:
#
# def __init__(self, x=None, y=None):
# self.x = x
# self.y = y
#
# def squared_distance(self, other):
# return (self.x-other.x)*(self.x-other.x) + (self.y-other.y)*(self.y-other.y)
#
# def distance(self, other):
# return math.sqrt(self.squared_distance(other))
#
# def get_flipped(self):
# return Point(self.y, self.x)
#
# def to_array(self):
# return [self.x, self.y]
#
# def equals(self, other):
# return self.x == other.x and self.y == other.y
#
# def difference(self, other):
# return Point(self.x - other.x, self.y - other.y)
#
# def addition(self, other):
# return Point(self.x + other.x, self.y + other.y)
#
# def __str__(self):
# return "Point("+str(self.x)+","+str(self.y)+")"
, which may contain function names, class names, or code. Output only the next line. | return Point(selected[0], selected[1]) |
Predict the next line for this snippet: <|code_start|> return move_camera(self._loc_in_minimap, self.coordinates_helper)[0]
elif state == States.ATTACK__MOVE_UNITS_TO_CLOSEST_ENNEMY:
return actions.FunctionCall(ATTACK_SCREEN, [NOT_QUEUED, self._get_closest_ennemy(obs).to_array()])
elif state == States.ATTACK__CENTER_CAMERA_ON_UNITS:
self._loc_in_minimap = self._get_minimap_loc_centered_on_units(obs)
return move_camera(self._loc_in_minimap, self.coordinates_helper)[0]
def _get_loc_in_minimap(self, obs):
if not self._loc_in_minimap:
self._loc_in_minimap = self.coordinates_helper.get_loc_in_minimap(obs)
return self._loc_in_minimap
def _get_ennemies_locations(self, obs):
if self._ennemies_x is None or self._ennemies_y is None:
player_relative = obs.observation[SCREEN][SCREEN_PLAYER_RELATIVE]
self._ennemies_y, self._ennemies_x = (player_relative == PLAYER_HOSTILE).nonzero()
return self._ennemies_x, self._ennemies_y
def _get_units_locations(self, obs):
if self._units_x is None or not self._units_y is None:
player_relative = obs.observation[SCREEN][SCREEN_PLAYER_RELATIVE]
self._units_y, self._units_x = (player_relative == PLAYER_SELF).nonzero()
return self._units_x, self._units_y
def _get_units_mean_location(self, obs):
if not self._is_units_mean_loc_updated:
units_x, units_y = self._get_units_locations(obs)
if units_x.size > 0:
<|code_end|>
with the help of current file imports:
import numpy as np
import sys
import time
from oscar.constants import *
from oscar.util.location import Location
from oscar.util.coordinates_helper import Coordinates_helper
from oscar.util.exploration_helper import *
from oscar.meta_action import *
and context from other files:
# Path: oscar/util/location.py
# class Location:
#
# def __init__(self, minimap_loc=None, screen_loc=None, camera_loc=None):
# self.minimap = minimap_loc
# self.screen = screen_loc
# self.camera = camera_loc
#
# def compute_minimap_loc(self, obs, shared):
# scale_x = shared['camera'].width(obs) / shared['screen'].width(obs)
# scale_y = shared['camera'].height(obs) / shared['screen'].height(obs)
#
# self.minimap = shared['minimap'].bound(obs, Point(
# int(round(self.camera.x - 0.5*shared['camera'].width(obs) + self.screen.x * scale_x)),
# int(round(self.camera.y - 0.5*shared['camera'].height(obs) + self.screen.y * scale_y))))
#
# def squarred_distance(self, other):
# if not self.minimap or not other.minimap:
# raise Exception("Can't compute distance")
# return self.minimap.distance(other.minimap)
#
# def distance(self, other):
# return math.sqrt(self.squarred_distance(other))
#
# def equals(self, other):
# def equals_minimap():
# return (not self.minimap and not other.minimap) \
# or (self.minimap and other.minimap and self.minimap.equals(other.minimap))
#
# def equals_screen():
# return (not self.screen and not other.screen) \
# or (self.screen and other.screen and self.screen.equals(other.screen))
#
# def equals_camera():
# return (not self.camera and not other.camera) \
# or (self.camera and other.camera and self.camera.equals(other.camera))
#
# return equals_minimap() and equals_screen() and equals_camera()
#
# def __str__(self):
# return "Location {\n" \
# + " minimap: " + str(self.minimap) + "\n" \
# + " screen: " + str(self.screen) + "\n" \
# + " camera: " + str(self.camera) + "\n" \
# + "}"
, which may contain function names, class names, or code. Output only the next line. | newLoc = Location(int(units_x.mean()), int(units_y.mean())) |
Based on the snippet: <|code_start|>
class Plane():
OnPlane = 1
Back = 2
Front = 3
def __init__(self, normal=None, distance=0):
if not normal:
<|code_end|>
, predict the immediate next line with the help of imports:
from vulk.math import vector
and context (classes, functions, sometimes code) from other files:
# Path: vulk/math/vector.py
# class Vector():
# class XMixin():
# class YMixin():
# class ZMixin():
# class WMixin():
# class Vector2(Vector, XMixin, YMixin):
# class Vector3(Vector, XMixin, YMixin, ZMixin):
# class Vector4(Vector, XMixin, YMixin, ZMixin, WMixin):
# def __init__(self, values):
# def __iter__(self):
# def __len__(self):
# def __add__(self, value):
# def __iadd__(self, value):
# def __sub__(self, value):
# def __isub__(self, value):
# def __mul__(self, value):
# def __imul__(self, value):
# def __matmul__(self, value):
# def __imatmul__(self, value):
# def __truediv__(self, value):
# def __itruediv__(self, value):
# def __str__(self):
# def __eq__(self, other):
# def __copy__(self):
# def values(self):
# def values(self, values):
# def size(self):
# def nor(self):
# def crs(self, vector):
# def crs2(self, values):
# def sub(self, vector):
# def sub2(self, values):
# def add(self, vector):
# def add2(self, values):
# def x(self):
# def x(self, value):
# def y(self):
# def y(self, value):
# def z(self):
# def z(self, value):
# def w(self):
# def w(self, value):
# def __init__(self, values=None):
# def __init__(self, values=None):
# def mul(self, vector):
# def mul2(self, matrix):
# def prj(self, matrix):
# def set(self, x, y, z):
# def set2(self, vector):
# def __init__(self, values=None):
# def set(self, vector):
# def set2(self, vector):
# def mul(self, vector):
# def mul2(self, matrix):
# def norw(self):
# X = None
# Y = None
# X = None
# Y = None
# Z = None
. Output only the next line. | normal = vector.Vector3([0, 0, 0]) |
Predict the next line for this snippet: <|code_start|> view.shape = (4, 4)
tmp_mat = np.matrix(view, copy=False)
self._values[:] = tmp_mat.I.flatten()
def to_identity(self):
'''Set this matrix to identity matrix'''
self._values[:] = 0.
self._values[0] = 1.
self._values[5] = 1.
self._values[10] = 1.
self._values[15] = 1.
return self
class ViewMatrix(Matrix4):
'''This class represents a view Matrix.
View Matrix convert vertex from World space to View space.
'''
def to_look_at_direction(self, direction, up):
'''
Set this matrix to a *look at* matrix with a `direction` and a `up`
vector.
*Parameters:*
- `direction`: Direction `Vector3`
- `up`: Up `Vector3`
'''
<|code_end|>
with the help of current file imports:
import numpy as np
from vulk.math.vector import Vector3
and context from other files:
# Path: vulk/math/vector.py
# class Vector3(Vector, XMixin, YMixin, ZMixin):
# '''Vector3 class represents a Vector in 3D space.
# It has three components `x`, `y` and `z`.
# '''
# X = None
# Y = None
# Z = None
# Zero = None
#
# def __init__(self, values=None):
# '''
# *Parameters:*
#
# - `values`: `list` of 3 `float`
# '''
# if not values:
# super().__init__([0, 0, 0])
# elif len(values) == 3:
# super().__init__(values)
# else:
# raise ValueError("Vector3 needs 3 components")
#
# # tmp properties used during computation
# self.tmp_v4 = Vector4()
#
# def mul(self, vector):
# '''Multiply this vector by `vector`.
#
# *Parameters:*
#
# - `vector`: `Vector3`
# '''
# # TODO: To test and valid
# self._values *= vector.values
#
# def mul2(self, matrix):
# '''Multiply this vector by a `Matrix4`
#
# *Parameters:*
#
# - `matrix`: `Matrix4`
# '''
# self.tmp_v4.set2(self).mul2(matrix)
# self._values[:] = self.tmp_v4.values[0:3]
# return self
#
# def prj(self, matrix):
# '''
# Project this vector to the `matrix` parameter.
# It's just a multiplication followed by a division by w.
#
#
#
# *Parameters:*
#
# - `matrix`: `Matrix4`
# '''
# self.tmp_v4.set2(self).mul2(matrix).norw()
# self._values[:] = self.tmp_v4.values[0:3]
#
# def set(self, x, y, z):
# '''Set values of this vector
#
# *Parameters:*
#
# - `x`, `y`, `z`: `float`
# '''
# self._values[0] = x
# self._values[1] = y
# self._values[2] = z
#
# def set2(self, vector):
# '''Set values of this vector
#
# *Parameters:*
#
# - `vector`: `Vector3`
# '''
# self.set(vector.x, vector.y, vector.z)
, which may contain function names, class names, or code. Output only the next line. | vec_z = Vector3(direction).nor() |
Predict the next line for this snippet: <|code_start|>'''Audio module
This module contains all audio related classes.
'''
logger = logging.getLogger()
class VulkAudio():
'''This class is only used in baseapp.
It initializes and close the audio system.
'''
def open(self, configuration):
'''Open and configure audio system
*Parameters:*
- `configuration`: Configuration parameters from Application
'''
if sdl2.SDL_InitSubSystem(sdl2.SDL_INIT_AUDIO) != 0:
msg = "Cannot initialize audio system: %s" % sdl2.SDL_GetError()
logger.critical(msg)
<|code_end|>
with the help of current file imports:
import logging
import sdl2
from sdl2 import sdlmixer as mixer
from sdl2.ext.compat import byteify
from vulk.exception import SDL2Error, SoundError
and context from other files:
# Path: vulk/exception.py
# class SDL2Error(VulkError):
# pass
#
# class SoundError(VulkError):
# pass
, which may contain function names, class names, or code. Output only the next line. | raise SDL2Error(msg) |
Given snippet: <|code_start|>
def close(self):
'''Close the audio system'''
mixer.Mix_CloseAudio()
sdl2.SDL_Quit(sdl2.SDL_INIT_AUDIO)
logger.info("Audio stopped")
class Sound():
'''
Sound effects are small audio samples, usually no longer than a few
seconds, that are played back on specific game events such as a character
jumping or shooting a gun.
Sound effects can be stored in various formats. Vulk is based on SDL2 and
thus supports WAVE, AIFF, RIFF, OGG, and VOC files.
'''
def __init__(self, path):
'''Load the sound file
*Parameters:*
- `path`: Path to the sound file
'''
self.sample = mixer.Mix_LoadWAV(byteify(path, "utf-8"))
if not self.sample:
msg = "Cannot load file %s" % path
logger.error(msg)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import logging
import sdl2
from sdl2 import sdlmixer as mixer
from sdl2.ext.compat import byteify
from vulk.exception import SDL2Error, SoundError
and context:
# Path: vulk/exception.py
# class SDL2Error(VulkError):
# pass
#
# class SoundError(VulkError):
# pass
which might include code, classes, or functions. Output only the next line. | raise SoundError(msg) |
Given the following code snippet before the placeholder: <|code_start|>
class MeshPart():
def __init__(self):
self.primitive = 0
self.offset = 0
self.size = 0
self.mesh = None
<|code_end|>
, predict the next line using imports from the current file:
from vulk.math.vector import Vector3
and context including class names, function names, and sometimes code from other files:
# Path: vulk/math/vector.py
# class Vector3(Vector, XMixin, YMixin, ZMixin):
# '''Vector3 class represents a Vector in 3D space.
# It has three components `x`, `y` and `z`.
# '''
# X = None
# Y = None
# Z = None
# Zero = None
#
# def __init__(self, values=None):
# '''
# *Parameters:*
#
# - `values`: `list` of 3 `float`
# '''
# if not values:
# super().__init__([0, 0, 0])
# elif len(values) == 3:
# super().__init__(values)
# else:
# raise ValueError("Vector3 needs 3 components")
#
# # tmp properties used during computation
# self.tmp_v4 = Vector4()
#
# def mul(self, vector):
# '''Multiply this vector by `vector`.
#
# *Parameters:*
#
# - `vector`: `Vector3`
# '''
# # TODO: To test and valid
# self._values *= vector.values
#
# def mul2(self, matrix):
# '''Multiply this vector by a `Matrix4`
#
# *Parameters:*
#
# - `matrix`: `Matrix4`
# '''
# self.tmp_v4.set2(self).mul2(matrix)
# self._values[:] = self.tmp_v4.values[0:3]
# return self
#
# def prj(self, matrix):
# '''
# Project this vector to the `matrix` parameter.
# It's just a multiplication followed by a division by w.
#
#
#
# *Parameters:*
#
# - `matrix`: `Matrix4`
# '''
# self.tmp_v4.set2(self).mul2(matrix).norw()
# self._values[:] = self.tmp_v4.values[0:3]
#
# def set(self, x, y, z):
# '''Set values of this vector
#
# *Parameters:*
#
# - `x`, `y`, `z`: `float`
# '''
# self._values[0] = x
# self._values[1] = y
# self._values[2] = z
#
# def set2(self, vector):
# '''Set values of this vector
#
# *Parameters:*
#
# - `vector`: `Vector3`
# '''
# self.set(vector.x, vector.y, vector.z)
. Output only the next line. | self.center = Vector3() |
Given the following code snippet before the placeholder: <|code_start|> '''
Call event listener until one of them return False.
*Parameters:*
'''
return any(list(takewhile(lambda x: x.handle(event), self.listeners)))
class DispatchEventListener(RawEventListener):
'''
This class dispatch each event to its specific function.
This class is very basic and performs no logic.
To get more logic, you must use `BaseEventListener`.
'''
def handle(self, event):
'''Called for each event received
*Parameters:*
- `event`: `eventconstant.BaseEvent`
*Returns:*
- `True` if event handled
- `False` otherwise
'''
# Unknow event
if not event:
return False
<|code_end|>
, predict the next line using imports from the current file:
from abc import ABC, abstractmethod
from itertools import takewhile
from vulk import eventconstant as ec
and context including class names, function names, and sometimes code from other files:
# Path: vulk/eventconstant.py
# class Button(IntEnum):
# class EventType(IntEnum):
# class KeyCode(IntEnum):
# class BaseEvent():
# class KeyboardEvent(BaseEvent):
# class MouseButtonEvent(BaseEvent):
# class MouseMotionEvent(BaseEvent):
# class QuitEvent(BaseEvent):
# class WindowEvent():
# class WindowResizedEvent(WindowEvent):
# LEFT = sdl2.SDL_BUTTON_LEFT
# MIDDLE = sdl2.SDL_BUTTON_MIDDLE
# RIGHT = sdl2.SDL_BUTTON_RIGHT
# X1 = sdl2.SDL_BUTTON_X1
# X2 = sdl2.SDL_BUTTON_X2
# AUDIO_DEVICE_ADDED = sdl2.SDL_AUDIODEVICEADDED
# AUDIO_DEVICE_REMOVED = sdl2.SDL_AUDIODEVICEREMOVED
# CONTROLLER_AXIS_MOTION = sdl2.SDL_CONTROLLERAXISMOTION
# CONTROLLER_BUTTON_DOWN = sdl2.SDL_CONTROLLERBUTTONDOWN
# CONTROLLER_BUTTON_UP = sdl2.SDL_CONTROLLERBUTTONUP
# CONTROLLER_DEVICE_ADDED = sdl2.SDL_CONTROLLERDEVICEADDED
# CONTROLLER_DEVICE_REMOVED = sdl2.SDL_CONTROLLERDEVICEREMOVED
# CONTROLLER_DEVICE_REMAPPED = sdl2.SDL_CONTROLLERDEVICEREMAPPED
# DROP_FILE = sdl2.SDL_DROPFILE
# DROP_TEXT = sdl2.SDL_DROPTEXT
# DROP_BEGIN = sdl2.SDL_DROPBEGIN
# DROP_COMPLETE = sdl2.SDL_DROPCOMPLETE
# FINGER_MOTION = sdl2.SDL_FINGERMOTION
# FINGER_DOWN = sdl2.SDL_FINGERDOWN
# FINGER_UP = sdl2.SDL_FINGERUP
# KEY_DOWN = sdl2.SDL_KEYDOWN
# KEY_UP = sdl2.SDL_KEYUP
# JOY_AXISMOTION = sdl2.SDL_JOYAXISMOTION
# JOY_BALLMOTION = sdl2.SDL_JOYBALLMOTION
# JOY_HATMOTION = sdl2.SDL_JOYHATMOTION
# JOY_BUTTONDOWN = sdl2.SDL_JOYBUTTONDOWN
# JOY_BUTTONUP = sdl2.SDL_JOYBUTTONUP
# JOY_DEVICEADDED = sdl2.SDL_JOYDEVICEADDED
# JOY_DEVICEREMOVED = sdl2.SDL_JOYDEVICEREMOVED
# MOUSE_MOTION = sdl2.SDL_MOUSEMOTION
# MOUSE_BUTTONDOWN = sdl2.SDL_MOUSEBUTTONDOWN
# MOUSE_BUTTONUP = sdl2.SDL_MOUSEBUTTONUP
# MOUSE_WHEEL = sdl2.SDL_MOUSEWHEEL
# QUIT = sdl2.SDL_QUIT
# WINDOW = sdl2.SDL_WINDOWEVENT
# WINDOW_RESIZED = sdl2.SDL_WINDOWEVENT_RESIZED
# LEFT = sdl2.SDL_SCANCODE_LEFT
# RIGHT = sdl2.SDL_SCANCODE_RIGHT
# def __init__(self, event):
# def __init__(self, event):
# def __init__(self, event):
# def __init__(self, event):
# def __init__(self, event):
# def __init__(self, event):
# def window_event_builder(event):
# def to_vulk_event(event):
. Output only the next line. | if event.type == ec.EventType.KEY_DOWN: |
Predict the next line for this snippet: <|code_start|>#!flask/bin/python
db.create_all()
if not os.path.exists(SQLALCHEMY_MIGRATE_REPO):
api.create(SQLALCHEMY_MIGRATE_REPO, 'database2 repository')
<|code_end|>
with the help of current file imports:
from migrate.versioning import api
from config import SQLALCHEMY_DATABASE_URI
from config import SQLALCHEMY_MIGRATE_REPO
from app import db
import os.path
and context from other files:
# Path: config.py
# SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
#
# Path: config.py
# SQLALCHEMY_MIGRATE_REPO = os.path.join(basedir, 'db2_repository')
, which may contain function names, class names, or code. Output only the next line. | api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO) |
Given the code snippet: <|code_start|> # Print current TrueSkill values for both players
print "CURRENT TrueSkill ({0}):".format(region_name), winner_user.tag, winner_user_rating, "VS.", loser_user.tag, loser_user_rating
# Record set result, victory for winner_user and loss for loser_user
new_winner_rating, new_loser_rating = rate_1vs1(winner_user_rating, loser_user_rating)
print "UPDATED TrueSkill ({0}):".format(region_name), winner_user.tag, new_winner_rating, "VS.", loser_user.tag, new_loser_rating
# Store and overwrite existing trueskill object with new Rating values
winner_user.trueskills[region_num].region=region_name
winner_user.trueskills[region_num].mu=new_winner_rating.mu
winner_user.trueskills[region_num].sigma=new_winner_rating.sigma
winner_user.trueskills[region_num].cons_mu=new_winner_rating.mu - STD*new_winner_rating.sigma
loser_user.trueskills[region_num].region=region_name
loser_user.trueskills[region_num].mu=new_loser_rating.mu
loser_user.trueskills[region_num].sigma=new_loser_rating.sigma
loser_user.trueskills[region_num].cons_mu=new_loser_rating.mu - STD*new_loser_rating.sigma
def recalculate_trueskill():
"""Resets, then recalculates all Trueskills for all Users.
Args:
None
Returns:
String indicating success. This value is never used.
"""
# Iterate through all Sets in order and recalculate Trueskill; currently in order of set.id
# order Sets by tournament date, then by set id, oldest being at index 0
setlist = Set.query.all()
<|code_end|>
, generate the next line using the imports in this file:
from app import app, db
from app.models import *
from sort_utils import sort_setlist
from misc_utils import print_ignore
from trueskill import setup, Rating, quality_1vs1, rate_1vs1
import time
and context (functions, classes, or occasionally code) from other files:
# Path: sort_utils.py
# def sort_setlist(setlist):
# sorted_setlist = sorted(setlist, key=attrgetter('tournament.date', 'id'))
# try:
# return sorted_setlist
# except:
# UnicodeEncodeError
#
# Path: misc_utils.py
# def print_ignore(input):
# try:
# print input
# except UnicodeError:
# pass
. Output only the next line. | sorted_setlist = sort_setlist(setlist) |
Continue the code snippet: <|code_start|>
Args:
None
Returns:
String indicating success. This value is never used.
"""
# Iterate through all Sets in order and recalculate Trueskill; currently in order of set.id
# order Sets by tournament date, then by set id, oldest being at index 0
setlist = Set.query.all()
sorted_setlist = sort_setlist(setlist)
# BUG: if user.tag changed for a User, the Set winner/loser tag will still remain, so when querying for User using the Set's outdated tag, queried User becomes None.
# Solution: Check and sanitize winner_tag, loser_tag again. But if it wasn't recognized in the first place, still an issue
# This takes a long time to run. How to optimize?
for set in sorted_setlist:
winner_user = User.query.filter(User.tag==set.winner_tag).first()
loser_user = User.query.filter(User.tag==set.loser_tag).first()
update_rating(winner_user, loser_user)
print sorted_setlist.index(set)
print "All trueskills recalculated"
def trueskills_dict():
'''
Returns a dictionary with every user represented as a dictionary key User.tag
Dictionary values are the user's corresponding Trueskills
'''
skills_by_user = {}
userlist = User.query.all()
for user in userlist:
<|code_end|>
. Use current file imports:
from app import app, db
from app.models import *
from sort_utils import sort_setlist
from misc_utils import print_ignore
from trueskill import setup, Rating, quality_1vs1, rate_1vs1
import time
and context (classes, functions, or code) from other files:
# Path: sort_utils.py
# def sort_setlist(setlist):
# sorted_setlist = sorted(setlist, key=attrgetter('tournament.date', 'id'))
# try:
# return sorted_setlist
# except:
# UnicodeEncodeError
#
# Path: misc_utils.py
# def print_ignore(input):
# try:
# print input
# except UnicodeError:
# pass
. Output only the next line. | print_ignore(user.tag) |
Given snippet: <|code_start|> return 'UserPlacements(tournament_name=%s, placement=%s, seed=%s, tournament=%s)' % \
(self.tournament_name, self.placement, self.seed, self.tournament)
def h2h_get_mutual_tournaments(user1, user2):
'''
given two User objects, returns list of lists containing two UserPlacements objects (which contain tournament_name,
placement, and seed), corresponding to user1 and user2 for each mutual tournament attended
call len() on the result of this method to get total number of tournaments
attended together.
'''
# Debug this
user1_placements = get_placement_info(user1)
user2_placements = get_placement_info(user2)
# if identical names for tournament (both attended same tournament), add to list of mutual tournaments
mutual_tournaments = []
for user1_placement in user1_placements:
mutual_tournament = next((user2_placement for user2_placement in user2_placements if user1_placement.tournament_name==user2_placement.tournament_name), None)
if mutual_tournament is not None:
mutual_tournaments.append([user1_placement, mutual_tournament])
return mutual_tournaments
# Make this a class function in models?
def get_placement_info(user):
'''
Returns list of UserPlacements object, each storing info for each tournament, placement, and seed
'''
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from app import *
from app.models import *
from operator import attrgetter
from sort_utils import sort_placementlist, sort_setlist
import collections
and context:
# Path: sort_utils.py
# def sort_placementlist(placementlist):
# sorted_placementlist = sorted(placementlist, key=attrgetter('tournament.date', 'tournament.name'), reverse=True)
# return sorted_placementlist
#
# def sort_setlist(setlist):
# sorted_setlist = sorted(setlist, key=attrgetter('tournament.date', 'id'))
# try:
# return sorted_setlist
# except:
# UnicodeEncodeError
which might include code, classes, or functions. Output only the next line. | user_placements_sorted = sort_placementlist(user.tournament_assocs) |
Predict the next line for this snippet: <|code_start|> '''
Returns list of UserPlacements object, each storing info for each tournament, placement, and seed
'''
user_placements_sorted = sort_placementlist(user.tournament_assocs)
placings = []
for tournament_placement in user_placements_sorted:
user_placement = UserPlacements(tournament_placement.tournament.name)
user_placement.tournament = tournament_placement.tournament
user_placement.placement = convert_placement(tournament_placement.placement)
placings.append(user_placement)
return placings
def h2h_get_sets_played(user1, user2):
"""Given two users, returns all sets played between them, sorted by set id.
Args:
user1 : User(models.py) : First user object to query for sets.
user2 : User(models.py) : Second user object to query for sets.
Returns:
A list of Set(models.py) objects sorted by set id of sets played between
the two users.
"""
user1_won_sets = h2h_get_sets_won(user1, user2)
user2_won_sets = h2h_get_sets_won(user2, user1)
# Any set user2 has won, user1 has lost, so user2_won == number of sets user1 has lost.
h2h_sets_played = user1_won_sets + user2_won_sets
<|code_end|>
with the help of current file imports:
from app import *
from app.models import *
from operator import attrgetter
from sort_utils import sort_placementlist, sort_setlist
import collections
and context from other files:
# Path: sort_utils.py
# def sort_placementlist(placementlist):
# sorted_placementlist = sorted(placementlist, key=attrgetter('tournament.date', 'tournament.name'), reverse=True)
# return sorted_placementlist
#
# def sort_setlist(setlist):
# sorted_setlist = sorted(setlist, key=attrgetter('tournament.date', 'id'))
# try:
# return sorted_setlist
# except:
# UnicodeEncodeError
, which may contain function names, class names, or code. Output only the next line. | h2h_sets_played = sort_setlist(h2h_sets_played) |
Given snippet: <|code_start|>def parse_bracket_entrants(sub_bracket_json, sub_tournament):
condensed_entrants = sub_bracket_json['entities']['seeds']
# pprint(condensed_entrants)
entrant_list = []
for entrant in condensed_entrants:
# pprint(entrant)
entrant_id = str(entrant.get("entrantId"))
participant_id = str(entrant['mutations']['entrants'][entrant_id]['participantIds'][0])
player_id = str(entrant['mutations']['entrants'][entrant_id]['playerIds'][participant_id])
print entrant_id, participant_id, player_id
entrant_name = entrant['mutations']['entrants'][entrant_id].get("name")
entrant_info = EntrantInfo(int(entrant_id), entrant_name)
# entrant['mutations']['players'][entrant_id] returns list containing one dictionary
entrant_info.player_tag = entrant['mutations']['players'][player_id].get("gamerTag")
entrant_info.player_prefix = entrant['mutations']['players'][player_id].get("prefix")
entrant_info.player_id = entrant['mutations']['players'][player_id].get("id")
entrant_info.player_region = entrant['mutations']['players'][player_id].get("region")
entrant_info.player_country = entrant['mutations']['players'][player_id].get("country")
entrant_info.player_state = entrant['mutations']['players'][player_id].get("state")
entrant_info.player_sub_seed = entrant.get("groupSeedNum")
entrant_info.player_super_seed = entrant.get("seedNum")
entrant_info.player_sub_placing = entrant.get("placement")
entrant_info.player_super_placing = entrant.get("placement")
entrant_list.append(entrant_info)
print "\n---ENTRANTS---"
for entrant in entrant_list:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import sys
import urllib3
import json
import requests
from app.models import *
from pprint import pprint
from date_utils import *
from trueskill_functions import *
from misc_utils import print_ignore
and context:
# Path: misc_utils.py
# def print_ignore(input):
# try:
# print input
# except UnicodeError:
# pass
which might include code, classes, or functions. Output only the next line. | print_ignore(entrant) |
Continue the code snippet: <|code_start|> sub_bracket_info.host = sub_bracket['subdomain']
# Inherited from parent tournament header
sub_bracket_info.parent = tournament_info.name
sub_bracket_info.bracket_type = tournament_info.bracket_type
sub_bracket_info.game_type = tournament_info.game_type
print sub_bracket_info
sub_tournament = import_sub_tournament_info(sub_bracket_info)
# Process bracket entrants and sets, passing bracket object info
entrant_list = process_entrants(sub_bracket_info, sub_tournament)
process_sets(sub_bracket_info, entrant_list, sub_tournament)
def process_entrants(sub_bracket_info, sub_tournament):
entrants = challonge.participants.index(sub_bracket_info.id)
# pprint(entrants)
entrant_list = []
for entrant in entrants:
entrant_info = EntrantInfo(entrant['display-name'])
entrant_info.id = int(entrant['id'])
entrant_info.account_name = entrant['name']
entrant_info.sub_seed = entrant['seed']
entrant_info.super_seed = entrant['seed']
entrant_info.sub_placing = entrant['final-rank'] # If tournament not finished, None. have to parse
entrant_info.super_placing = entrant['final-rank'] # If tournament not finished, None. have to parse
entrant_list.append(entrant_info)
print "\n---ENTRANTS---"
for entrant in entrant_list:
<|code_end|>
. Use current file imports:
import sys
import urllib3
import json
import requests
import challonge
from app.models import *
from bs4 import BeautifulSoup
from pprint import pprint
from date_utils import *
from trueskill_functions import *
from misc_utils import print_ignore
and context (classes, functions, or code) from other files:
# Path: misc_utils.py
# def print_ignore(input):
# try:
# print input
# except UnicodeError:
# pass
. Output only the next line. | print_ignore(entrant) |
Predict the next line for this snippet: <|code_start|> # Find User if tag not registered
if sanitized_tag==new_tag:
# this means user was not matched to sanitized tag, so query for user with tag==new_tag
root_user = User.query.filter(User.tag==new_tag).first()
if root_user is not None:
print "ROOT USER", root_user
merge_user(root_user.tag, user.tag)
else:
# if still can't find root tag to merge with, then root tag doesn't exist. Change the tag
change_tag(user.tag, new_tag)
else:
# if found sanitized User, merge them
merge_user(sanitized_tag, user.tag)
print '\n'
# Given a User tag and region name, changes user.region and changes regional trueskill if region is valid, otherwise deletes it
def change_region(tag, region_name):
user = User.query.filter(User.tag==tag).first()
region = Region.query.filter(Region.region==region_name).first()
if not user and not region:
return "User or Region not found"
if user.region is not None and user.region.region==region_name:
return "Region %s is already region of %s" % (region_name, tag)
user.region = region
# Repopulate regional trueskill for new region, to the default. First call deletes obsolete region, second call repopulates regional trueskill with new region.
# If new region is None, deletes obsolete region and does nothing else
# If user.region was already None, does nothing
<|code_end|>
with the help of current file imports:
from app import app, db
from app.models import *
from sanitize_utils import *
from trueskill import setup, Rating, quality_1vs1, rate_1vs1
from trueskill_functions import MU, SIGMA, CONS_MU, BETA, TAU, DRAW_PROBABILITY, populate_trueskills
from misc_utils import *
import datetime
import sys
and context from other files:
# Path: trueskill_functions.py
# MU = 25
#
# SIGMA = 8.333333333333334
#
# CONS_MU = MU - (STD*SIGMA)
#
# BETA = 4.166666666666667
#
# TAU = 0.08333333333333334
#
# DRAW_PROBABILITY = 0.0
#
# def populate_trueskills(user):
# """Populates TrueSkill associations of User
#
# Args:
# user: A User object.
#
# Returns:
# If User already has Global and appropriate Regional TrueSkill, returns True.
# Adds TrueSkill association for Global if it does not already exist.
# Deletes TrueSkill association for Region if User no longer is associated with that region.
# """
#
# # case for when User has no TrueSkills; if User has region, populate both Global and region Trueskill
# if len(user.trueskills)<=0:
# user.trueskills.append(TrueSkill(region="Global", mu=MU, sigma=SIGMA, cons_mu=CONS_MU))
# if user.region is not None:
# user.trueskills.append(TrueSkill(region=user.region.region, mu=MU, sigma=SIGMA, cons_mu=CONS_MU))
# # case for when User is initialized with no region (Tournament has no region attribute during)
# # if the one regional TrueSkill is Global, and user.region is not None, populate regional TrueSkill
# elif len(user.trueskills)==1:
# if user.trueskills[0].region=="Global" and user.region is not None:
# user.trueskills.append(TrueSkill(region=user.region.region, mu=MU, sigma=SIGMA, cons_mu=CONS_MU))
# db.session.commit()
# else:
# return True
# # If User has 2 Trueskills (Global and Region), check to make sure he should have a regional TrueSkill (if he belongs to a region)
# # if User Region does not match TrueSkill region, remove it
# elif len(user.trueskills)>=2:
# if user.region is None or user.region.region!=user.trueskills[1].region:
# user.trueskills.remove(user.trueskills[1])
# db.session.commit()
# else:
# return True
, which may contain function names, class names, or code. Output only the next line. | populate_trueskills(user) |
Given snippet: <|code_start|>
return render_template("head_to_head.html",
title="Head to Head",
tag1=tag1,
tag2=tag2,
user1=user1,
user2=user2,
user1_set_win_count=user1_set_win_count,
user2_set_win_count=user2_set_win_count,
user1_match_win_count=user1_match_win_count,
user2_match_win_count=user2_match_win_count,
user1_score_matches_won=user1_score_matches_won,
user2_score_matches_won=user2_score_matches_won,
h2h_sets_played=h2h_sets_played,
h2h_matches_played=h2h_matches_played,
h2h_stages_played=h2h_stages_played,
mutual_tournaments=mutual_tournaments,
form=form)
# browse all Users, 25 per page
@app.route('/browse_users')
@app.route('/browse_users/<region>')
@app.route('/browse_users/<region>/<int:page>')
def browse_users(region, page=1):
g.region = region
print g.region
# if viewing global information, don't filter query by g.region
# if character=="Main", or the default SelectField "title", don't filter for any character
if g.region=="Global" or g.region=="National":
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from flask import render_template, flash, redirect, request, url_for, g, session
from app import app, db
from models import *
from forms import UserCreate, UserEdit, SetCreate, SetEdit, MatchSubmit, HeadToHead, SearchForm, CharacterFilter, character_choices, character_list, RegionSelect
from sqlalchemy import and_, or_
from config import USERS_PER_PAGE, TOURNAMENTS_PER_PAGE, CHAR_USERS_PER_PAGE
from sanitize_utils import check_and_sanitize_tag, check_and_sanitize_tag_multiple
from sort_utils import sort_placementlist, sort_userlist
from misc_utils import sanitize_url
from h2h_stats_functions import *
import collections
import sys
and context:
# Path: config.py
# USERS_PER_PAGE = 25
#
# TOURNAMENTS_PER_PAGE = 15
#
# CHAR_USERS_PER_PAGE = 15
#
# Path: sort_utils.py
# def sort_placementlist(placementlist):
# sorted_placementlist = sorted(placementlist, key=attrgetter('tournament.date', 'tournament.name'), reverse=True)
# return sorted_placementlist
#
# def sort_userlist(userlist):
# sorted_userlist = sorted(userlist, key=attrgetter('trueskill.mu'), reverse=True)
#
# Path: misc_utils.py
# def sanitize_url(tournament_name):
# tournament_name = tournament_name.replace("%20", ' ')
# tournament_name = tournament_name.replace("%2F", '/')
# tournament_name = tournament_name.replace("%2D", '-')
# tournament_name = tournament_name.replace("%2E", '.')
# return tournament_name
which might include code, classes, or functions. Output only the next line. | userlist = User.query.join(User.trueskills).filter(TrueSkill.region=="Global").order_by(TrueSkill.cons_mu.desc()).paginate(page, USERS_PER_PAGE, False) |
Given the following code snippet before the placeholder: <|code_start|>@app.route('/character/<character>/<int:page>')
def character(character, page=1):
# "Convert" character parameter, which is currently a string, to Character object.
character_object = Character.query.filter(Character.name==character).first()
if character_object is None:
return render_template('404.html'), 404
# if viewing Global information, don't filter query by g.region
if g.region=="Global" or g.region=="National":
matching_users = User.query.join(TrueSkill.user, User).filter(and_(TrueSkill.region=="Global", User.character.contains(character_object))).order_by(TrueSkill.cons_mu.desc()).paginate(page, CHAR_USERS_PER_PAGE, False)
# if viewing national information, filter query to take Users with User.region==None
else:
matching_users = User.query.join(TrueSkill.user, User).join(Region, User.region).filter(and_(TrueSkill.region==g.region, User.characters.contains(character_object), Region.region==g.region)).order_by(TrueSkill.cons_mu.desc()).paginate(page, CHAR_USERS_PER_PAGE, False)
if matching_users.total <= 0:
flash('No players found that play this character')
return render_template("character.html",
matching_users=matching_users,
character=character,
current_region=g.region)
# Lists tournament_headers in database, 15 per page
@app.route('/browse_tournaments')
@app.route('/browse_tournaments/<region>')
@app.route('/browse_tournaments/<region>/<int:page>')
def browse_tournaments(region, page=1):
# if viewing Global information, don't filter query by g.region
g.region = region
if g.region=="Global":
<|code_end|>
, predict the next line using imports from the current file:
from flask import render_template, flash, redirect, request, url_for, g, session
from app import app, db
from models import *
from forms import UserCreate, UserEdit, SetCreate, SetEdit, MatchSubmit, HeadToHead, SearchForm, CharacterFilter, character_choices, character_list, RegionSelect
from sqlalchemy import and_, or_
from config import USERS_PER_PAGE, TOURNAMENTS_PER_PAGE, CHAR_USERS_PER_PAGE
from sanitize_utils import check_and_sanitize_tag, check_and_sanitize_tag_multiple
from sort_utils import sort_placementlist, sort_userlist
from misc_utils import sanitize_url
from h2h_stats_functions import *
import collections
import sys
and context including class names, function names, and sometimes code from other files:
# Path: config.py
# USERS_PER_PAGE = 25
#
# TOURNAMENTS_PER_PAGE = 15
#
# CHAR_USERS_PER_PAGE = 15
#
# Path: sort_utils.py
# def sort_placementlist(placementlist):
# sorted_placementlist = sorted(placementlist, key=attrgetter('tournament.date', 'tournament.name'), reverse=True)
# return sorted_placementlist
#
# def sort_userlist(userlist):
# sorted_userlist = sorted(userlist, key=attrgetter('trueskill.mu'), reverse=True)
#
# Path: misc_utils.py
# def sanitize_url(tournament_name):
# tournament_name = tournament_name.replace("%20", ' ')
# tournament_name = tournament_name.replace("%2F", '/')
# tournament_name = tournament_name.replace("%2D", '-')
# tournament_name = tournament_name.replace("%2E", '.')
# return tournament_name
. Output only the next line. | tournament_headers = TournamentHeader.query.order_by(TournamentHeader.date.desc()).paginate(page, TOURNAMENTS_PER_PAGE, False) |
Given the following code snippet before the placeholder: <|code_start|> print "session['region_name']", session['region_name']
flash("Now Viewing Region: " + str(session['region_name']))
g.region = session['region_name']
print "g.region", g.region
return render_template("region.html",
region=region,
current_region=current_region)
# Displays a list of all SSBM characters, each of which links to /character/<character>
@app.route('/browse_characters')
def browse_characters():
characterlist = main_char_list
return render_template("browse_characters.html",
characterlist=characterlist,
current_region=g.region)
# Displays all users who play a certain character. Routed to from /browse_characters
@app.route('/character/<character>')
@app.route('/character/<character>/<int:page>')
def character(character, page=1):
# "Convert" character parameter, which is currently a string, to Character object.
character_object = Character.query.filter(Character.name==character).first()
if character_object is None:
return render_template('404.html'), 404
# if viewing Global information, don't filter query by g.region
if g.region=="Global" or g.region=="National":
<|code_end|>
, predict the next line using imports from the current file:
from flask import render_template, flash, redirect, request, url_for, g, session
from app import app, db
from models import *
from forms import UserCreate, UserEdit, SetCreate, SetEdit, MatchSubmit, HeadToHead, SearchForm, CharacterFilter, character_choices, character_list, RegionSelect
from sqlalchemy import and_, or_
from config import USERS_PER_PAGE, TOURNAMENTS_PER_PAGE, CHAR_USERS_PER_PAGE
from sanitize_utils import check_and_sanitize_tag, check_and_sanitize_tag_multiple
from sort_utils import sort_placementlist, sort_userlist
from misc_utils import sanitize_url
from h2h_stats_functions import *
import collections
import sys
and context including class names, function names, and sometimes code from other files:
# Path: config.py
# USERS_PER_PAGE = 25
#
# TOURNAMENTS_PER_PAGE = 15
#
# CHAR_USERS_PER_PAGE = 15
#
# Path: sort_utils.py
# def sort_placementlist(placementlist):
# sorted_placementlist = sorted(placementlist, key=attrgetter('tournament.date', 'tournament.name'), reverse=True)
# return sorted_placementlist
#
# def sort_userlist(userlist):
# sorted_userlist = sorted(userlist, key=attrgetter('trueskill.mu'), reverse=True)
#
# Path: misc_utils.py
# def sanitize_url(tournament_name):
# tournament_name = tournament_name.replace("%20", ' ')
# tournament_name = tournament_name.replace("%2F", '/')
# tournament_name = tournament_name.replace("%2D", '-')
# tournament_name = tournament_name.replace("%2E", '.')
# return tournament_name
. Output only the next line. | matching_users = User.query.join(TrueSkill.user, User).filter(and_(TrueSkill.region=="Global", User.character.contains(character_object))).order_by(TrueSkill.cons_mu.desc()).paginate(page, CHAR_USERS_PER_PAGE, False) |
Predict the next line for this snippet: <|code_start|>
def __init__(self, tournament):
self.tournament = tournament
def __str__(self):
return "UserTournamentSets(tournament_name=%s, tournament=%s, sets=%s)" % (self.tournament_name, self.tournament, self.sets)
# User profile page
@app.route('/user/<tag>')
@app.route('/user/<tag>/<int:page>')
def user(tag, page=1):
# Pagination variables
tournaments_per_page = 10
start_index = (page - 1) * tournaments_per_page
end_index = start_index + tournaments_per_page
user = User.query.filter(User.tag==tag).first()
# If routed to user profile page (user/<tag>), check to make sure user exists
if user is None:
flash('User %s not found.' % tag)
return redirect(url_for('browse_users', region=g.region))
# get User secondaries
user_characters = user.get_characters()
# create ordered dictionary with Tournament name and respective placement; important to keep order so placements can be displayed in order of tournament.date
user_sets_by_tournament = collections.OrderedDict()
# sort by Placement.tournament.date, in reverse order (most recent first). Sort by tournament.name as secondary sort
<|code_end|>
with the help of current file imports:
from flask import render_template, flash, redirect, request, url_for, g, session
from app import app, db
from models import *
from forms import UserCreate, UserEdit, SetCreate, SetEdit, MatchSubmit, HeadToHead, SearchForm, CharacterFilter, character_choices, character_list, RegionSelect
from sqlalchemy import and_, or_
from config import USERS_PER_PAGE, TOURNAMENTS_PER_PAGE, CHAR_USERS_PER_PAGE
from sanitize_utils import check_and_sanitize_tag, check_and_sanitize_tag_multiple
from sort_utils import sort_placementlist, sort_userlist
from misc_utils import sanitize_url
from h2h_stats_functions import *
import collections
import sys
and context from other files:
# Path: config.py
# USERS_PER_PAGE = 25
#
# TOURNAMENTS_PER_PAGE = 15
#
# CHAR_USERS_PER_PAGE = 15
#
# Path: sort_utils.py
# def sort_placementlist(placementlist):
# sorted_placementlist = sorted(placementlist, key=attrgetter('tournament.date', 'tournament.name'), reverse=True)
# return sorted_placementlist
#
# def sort_userlist(userlist):
# sorted_userlist = sorted(userlist, key=attrgetter('trueskill.mu'), reverse=True)
#
# Path: misc_utils.py
# def sanitize_url(tournament_name):
# tournament_name = tournament_name.replace("%20", ' ')
# tournament_name = tournament_name.replace("%2F", '/')
# tournament_name = tournament_name.replace("%2D", '-')
# tournament_name = tournament_name.replace("%2E", '.')
# return tournament_name
, which may contain function names, class names, or code. Output only the next line. | user_tournaments_sorted = sort_placementlist(user.tournament_assocs) |
Given snippet: <|code_start|> tournament_headers = TournamentHeader.query.filter(TournamentHeader.region==None).order_by(TournamentHeader.date.desc()).paginate(page, TOURNAMENTS_PER_PAGE, False)
else:
# filter for Tournaments by g.region, by joining Region and TournamentHeader.region
tournament_headers = TournamentHeader.query.join(Region, TournamentHeader.region).filter(Region.region==g.region).order_by(TournamentHeader.date.desc()).paginate(page, TOURNAMENTS_PER_PAGE, False)
return render_template("browse_tournament_headers.html",
tournament_headers=tournament_headers,
current_region=g.region)
# Lists tournaments in database, 15 per page
def browse_tournaments(region, page=1):
pass
# if viewing Global information, don't filter query by g.region
g.region = region
if g.region=="Global":
tournamentlist = Tournament.query.order_by(Tournament.date.desc()).paginate(page, TOURNAMENTS_PER_PAGE, False)
# if viewing national information, filter query to take Tournaments with region==None
elif g.region=="National":
tournamentlist = Tournament.query.filter(Tournament.region==None).order_by(Tournament.date.desc()).paginate(page, TOURNAMENTS_PER_PAGE, False)
else:
# filter for Tournaments by g.region, by joining Region and Tournament.region
tournamentlist = Tournament.query.join(Region, Tournament.region).filter(Region.region==g.region).order_by(Tournament.date.desc()).paginate(page, TOURNAMENTS_PER_PAGE, False)
return render_template("browse_tournaments.html",
tournamentlist=tournamentlist,
current_region=g.region)
# Displays all subtournaments in a TournamentHeader
@app.route('/tournament/<tournament_name>')
def tournamentHeader(tournament_name):
print tournament_name
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from flask import render_template, flash, redirect, request, url_for, g, session
from app import app, db
from models import *
from forms import UserCreate, UserEdit, SetCreate, SetEdit, MatchSubmit, HeadToHead, SearchForm, CharacterFilter, character_choices, character_list, RegionSelect
from sqlalchemy import and_, or_
from config import USERS_PER_PAGE, TOURNAMENTS_PER_PAGE, CHAR_USERS_PER_PAGE
from sanitize_utils import check_and_sanitize_tag, check_and_sanitize_tag_multiple
from sort_utils import sort_placementlist, sort_userlist
from misc_utils import sanitize_url
from h2h_stats_functions import *
import collections
import sys
and context:
# Path: config.py
# USERS_PER_PAGE = 25
#
# TOURNAMENTS_PER_PAGE = 15
#
# CHAR_USERS_PER_PAGE = 15
#
# Path: sort_utils.py
# def sort_placementlist(placementlist):
# sorted_placementlist = sorted(placementlist, key=attrgetter('tournament.date', 'tournament.name'), reverse=True)
# return sorted_placementlist
#
# def sort_userlist(userlist):
# sorted_userlist = sorted(userlist, key=attrgetter('trueskill.mu'), reverse=True)
#
# Path: misc_utils.py
# def sanitize_url(tournament_name):
# tournament_name = tournament_name.replace("%20", ' ')
# tournament_name = tournament_name.replace("%2F", '/')
# tournament_name = tournament_name.replace("%2D", '-')
# tournament_name = tournament_name.replace("%2E", '.')
# return tournament_name
which might include code, classes, or functions. Output only the next line. | tournament_name = sanitize_url(tournament_name) |
Predict the next line for this snippet: <|code_start|># Copyright (C) 2009 Gaël Utard
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
def get_latest_blog_posts():
f = feedparser.parse("http://news.maposmatic.org/?feed=rss2")
return f.entries[:4]
def get_osm_database_last_update():
"""Returns the timestamp of the last PostGIS database update, which is
placed into the maposmatic_admin table in the PostGIS database by the
planet-update incremental update script."""
cursor = None
try:
<|code_end|>
with the help of current file imports:
import django
import django.utils.translation
import feedparser
import datetime
import www.settings
import psycopg2
from django.core.urlresolvers import reverse
from models import MapRenderingJob
from www.maposmatic import gisdb
from www.maposmatic import forms
and context from other files:
# Path: www/maposmatic/gisdb.py
# _DB = None
# _DB = psycopg2.connect("dbname='%s' user='%s' host='%s' password='%s' port='%s'" %
# (www.settings.GIS_DATABASE_NAME,
# www.settings.GIS_DATABASE_USER,
# www.settings.GIS_DATABASE_HOST,
# www.settings.GIS_DATABASE_PASSWORD,
# www.settings.GIS_DATABASE_PORT))
# _DB = None
# def get():
#
# Path: www/maposmatic/forms.py
# class MapSearchForm(forms.Form):
# class MapRenderingJobForm(forms.ModelForm):
# class Meta:
# class MapPaperSizeForm(forms.Form):
# class MapRecreateForm(forms.Form):
# class MapCancelForm(forms.Form):
# MODES = (('admin', _('Administrative boundary')),
# ('bbox', _('Bounding box')))
# ORIENTATION = (('portrait', _('Portrait')),
# ('landscape', _('Landscape')))
# def __init__(self, *args, **kwargs):
# def _build_papersize_description(p):
# def clean(self):
# def _check_osm_id(self, osm_id):
# def clean(self):
# def clean(self):
, which may contain function names, class names, or code. Output only the next line. | db = gisdb.get() |
Based on the snippet: <|code_start|> # the rss feed
if (django.VERSION[1] >= 4 and request.path == reverse('rss-feed')) or \
(django.VERSION[1] < 4 and request.path == reverse('rss-feed', args=['maps'])):
return {}
l = django.utils.translation.get_language()
if www.settings.PAYPAL_LANGUAGES.has_key(l):
paypal_lang_code = www.settings.PAYPAL_LANGUAGES[l][0]
paypal_country_code = www.settings.PAYPAL_LANGUAGES[l][1]
else:
paypal_lang_code = "en_US"
paypal_country_code = "US"
daemon_running = www.settings.is_daemon_running()
gis_lastupdate = get_osm_database_last_update()
gis_lag_ok = (gis_lastupdate
and datetime.datetime.utcnow() - gis_lastupdate < datetime.timedelta(minutes=10)
or False)
platform_status = 'off'
if daemon_running and gis_lag_ok:
platform_status = 'ok'
elif daemon_running and gis_lastupdate and not gis_lag_ok:
platform_status = 'warning-sign'
return {
'DEBUG': www.settings.DEBUG,
'LANGUAGES': www.settings.LANGUAGES,
'MAP_LANGUAGES': www.settings.MAP_LANGUAGES,
'BBOX_MAXIMUM_LENGTH_IN_METERS': www.settings.BBOX_MAXIMUM_LENGTH_IN_METERS,
<|code_end|>
, predict the immediate next line with the help of imports:
import django
import django.utils.translation
import feedparser
import datetime
import www.settings
import psycopg2
from django.core.urlresolvers import reverse
from models import MapRenderingJob
from www.maposmatic import gisdb
from www.maposmatic import forms
and context (classes, functions, sometimes code) from other files:
# Path: www/maposmatic/gisdb.py
# _DB = None
# _DB = psycopg2.connect("dbname='%s' user='%s' host='%s' password='%s' port='%s'" %
# (www.settings.GIS_DATABASE_NAME,
# www.settings.GIS_DATABASE_USER,
# www.settings.GIS_DATABASE_HOST,
# www.settings.GIS_DATABASE_PASSWORD,
# www.settings.GIS_DATABASE_PORT))
# _DB = None
# def get():
#
# Path: www/maposmatic/forms.py
# class MapSearchForm(forms.Form):
# class MapRenderingJobForm(forms.ModelForm):
# class Meta:
# class MapPaperSizeForm(forms.Form):
# class MapRecreateForm(forms.Form):
# class MapCancelForm(forms.Form):
# MODES = (('admin', _('Administrative boundary')),
# ('bbox', _('Bounding box')))
# ORIENTATION = (('portrait', _('Portrait')),
# ('landscape', _('Landscape')))
# def __init__(self, *args, **kwargs):
# def _build_papersize_description(p):
# def clean(self):
# def _check_osm_id(self, osm_id):
# def clean(self):
# def clean(self):
. Output only the next line. | 'searchform': forms.MapSearchForm(request.GET), |
Here is a snippet: <|code_start|>
if details is None:
entry["ocitysmap_params"] \
= dict(valid=False,
reason="no-admin",
reason_text=ugettext("No administrative boundary details from GIS"))
else:
(osm_id, admin_level, table_name,
valid, reason, reason_text) = details
entry["ocitysmap_params"] \
= dict(table=table_name, id=osm_id,
admin_level=admin_level,
valid=valid,
reason=reason,
reason_text=reason_text)
else:
entry["ocitysmap_params"] \
= dict(valid=False,
reason="no-admin",
reason_text=ugettext("No administrative boundary"))
def _prepare_and_filter_entries(entries):
"""Try to retrieve additional OSM information for the given nominatim
entries. Among the information, we try to determine the real ID in
an OSM table for each of these entries. All these additional data
are stored in the "ocitysmap_params" key of the entry."""
if not www.settings.has_gis_database():
return entries
<|code_end|>
. Write the next line using the current file imports:
from django.utils.translation import ugettext
from urllib import urlencode
from xml.etree.ElementTree import parse as XMLTree
from www.maposmatic import gisdb
import logging
import psycopg2
import urllib2
import ocitysmap
import www.settings
import pprint, sys
and context from other files:
# Path: www/maposmatic/gisdb.py
# _DB = None
# _DB = psycopg2.connect("dbname='%s' user='%s' host='%s' password='%s' port='%s'" %
# (www.settings.GIS_DATABASE_NAME,
# www.settings.GIS_DATABASE_USER,
# www.settings.GIS_DATABASE_HOST,
# www.settings.GIS_DATABASE_PASSWORD,
# www.settings.GIS_DATABASE_PORT))
# _DB = None
# def get():
, which may include functions, classes, or code. Output only the next line. | db = gisdb.get() |
Predict the next line after this snippet: <|code_start|># License, or any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Forms for MapOSMatic
class MapSearchForm(forms.Form):
"""
The map search form, allowing search through the rendered maps.
"""
query = forms.CharField(min_length=1, required=True,
widget=forms.TextInput(attrs=
{'placeholder': _('Search for a map'),
'class': 'span2'}))
class MapRenderingJobForm(forms.ModelForm):
"""
The main map rendering form, displayed on the 'Create Map' page. It's a
ModelForm based on the MapRenderingJob model.
"""
class Meta:
<|code_end|>
using the current file's imports:
from django import forms
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from www.maposmatic import models, widgets
import time
import ocitysmap
import www.settings
and any relevant context from other files:
# Path: www/maposmatic/models.py
# class MapRenderingJobManager(models.Manager):
# class MapRenderingJob(models.Model):
# def to_render(self):
# def queue_size(self):
# def get_random_with_thumbnail(self):
# def get_by_filename(self, name):
# def __str__(self):
# def maptitle_computized(self):
# def files_prefix(self):
# def start_rendering(self):
# def end_rendering(self, resultmsg):
# def rendering_time_gt_1min(self):
# def __is_ok(self): return self.resultmsg == 'ok'
# def is_waiting(self): return self.status == 0
# def is_rendering(self): return self.status == 1
# def needs_waiting(self): return self.status < 2
# def is_done(self): return self.status == 2
# def is_done_ok(self): return self.is_done() and self.__is_ok()
# def is_done_failed(self): return self.is_done() and not self.__is_ok()
# def is_obsolete(self): return self.status == 3
# def is_obsolete_ok(self): return self.is_obsolete() and self.__is_ok()
# def is_obsolete_failed(self): return self.is_obsolete() and not self.__is_ok()
# def is_cancelled(self): return self.status == 4
# def can_recreate(self):
# def get_map_fileurl(self, format):
# def get_map_filepath(self, format):
# def output_files(self):
# def has_output_files(self):
# def remove_all_files(self):
# def cancel(self):
# def get_thumbnail(self):
# def current_position_in_queue(self):
# def rendering_estimated_start_time(self):
# def get_absolute_url(self):
# SPACE_REDUCE = re.compile(r"\s+")
# NONASCII_REMOVE = re.compile(r"[^A-Za-z0-9]+")
# STATUS_LIST = (
# (0, 'Submitted'),
# (1, 'In progress'),
# (2, 'Done'),
# (3, 'Done w/o files'),
# (4, 'Cancelled'),
# )
# NONCE_SIZE = 16
#
# Path: www/maposmatic/widgets.py
# class AreaWidget(forms.TextInput):
# class AreaField(forms.MultiValueField):
# def render(self, name, value, attrs=None):
# def value_from_datadict(self, data, files, name):
# def clean(self, value):
# def compress(self, data_list):
. Output only the next line. | model = models.MapRenderingJob |
Based on the snippet: <|code_start|> {'placeholder': _('Search for a map'),
'class': 'span2'}))
class MapRenderingJobForm(forms.ModelForm):
"""
The main map rendering form, displayed on the 'Create Map' page. It's a
ModelForm based on the MapRenderingJob model.
"""
class Meta:
model = models.MapRenderingJob
fields = ('maptitle', 'administrative_city',
'lat_upper_left', 'lon_upper_left',
'lat_bottom_right', 'lon_bottom_right')
MODES = (('admin', _('Administrative boundary')),
('bbox', _('Bounding box')))
ORIENTATION = (('portrait', _('Portrait')),
('landscape', _('Landscape')))
mode = forms.ChoiceField(choices=MODES, initial='admin',
widget=forms.RadioSelect)
layout = forms.ChoiceField(choices=(), widget=forms.RadioSelect)
stylesheet = forms.ChoiceField(choices=(), widget=forms.RadioSelect)
papersize = forms.ChoiceField(choices=(), widget=forms.RadioSelect)
paperorientation = forms.ChoiceField(choices=ORIENTATION,
widget=forms.RadioSelect)
paper_width_mm = forms.IntegerField(widget=forms.HiddenInput)
paper_height_mm = forms.IntegerField(widget=forms.HiddenInput)
maptitle = forms.CharField(max_length=256, required=False)
<|code_end|>
, predict the immediate next line with the help of imports:
from django import forms
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from www.maposmatic import models, widgets
import time
import ocitysmap
import www.settings
and context (classes, functions, sometimes code) from other files:
# Path: www/maposmatic/models.py
# class MapRenderingJobManager(models.Manager):
# class MapRenderingJob(models.Model):
# def to_render(self):
# def queue_size(self):
# def get_random_with_thumbnail(self):
# def get_by_filename(self, name):
# def __str__(self):
# def maptitle_computized(self):
# def files_prefix(self):
# def start_rendering(self):
# def end_rendering(self, resultmsg):
# def rendering_time_gt_1min(self):
# def __is_ok(self): return self.resultmsg == 'ok'
# def is_waiting(self): return self.status == 0
# def is_rendering(self): return self.status == 1
# def needs_waiting(self): return self.status < 2
# def is_done(self): return self.status == 2
# def is_done_ok(self): return self.is_done() and self.__is_ok()
# def is_done_failed(self): return self.is_done() and not self.__is_ok()
# def is_obsolete(self): return self.status == 3
# def is_obsolete_ok(self): return self.is_obsolete() and self.__is_ok()
# def is_obsolete_failed(self): return self.is_obsolete() and not self.__is_ok()
# def is_cancelled(self): return self.status == 4
# def can_recreate(self):
# def get_map_fileurl(self, format):
# def get_map_filepath(self, format):
# def output_files(self):
# def has_output_files(self):
# def remove_all_files(self):
# def cancel(self):
# def get_thumbnail(self):
# def current_position_in_queue(self):
# def rendering_estimated_start_time(self):
# def get_absolute_url(self):
# SPACE_REDUCE = re.compile(r"\s+")
# NONASCII_REMOVE = re.compile(r"[^A-Za-z0-9]+")
# STATUS_LIST = (
# (0, 'Submitted'),
# (1, 'In progress'),
# (2, 'Done'),
# (3, 'Done w/o files'),
# (4, 'Cancelled'),
# )
# NONCE_SIZE = 16
#
# Path: www/maposmatic/widgets.py
# class AreaWidget(forms.TextInput):
# class AreaField(forms.MultiValueField):
# def render(self, name, value, attrs=None):
# def value_from_datadict(self, data, files, name):
# def clean(self, value):
# def compress(self, data_list):
. Output only the next line. | bbox = widgets.AreaField(label=_("Area"), |
Next line prediction: <|code_start|> return render_to_response('maposmatic/about.html',
context_instance=RequestContext(request))
def donate(request):
"""The donate page."""
return render_to_response('maposmatic/donate.html',
context_instance=RequestContext(request))
def donate_thanks(request):
"""The thanks for donation page."""
return render_to_response('maposmatic/donate-thanks.html',
context_instance=RequestContext(request))
def new(request):
"""The map creation page and form."""
if request.method == 'POST':
form = forms.MapRenderingJobForm(request.POST)
if form.is_valid():
job = form.save(commit=False)
job.administrative_osmid = form.cleaned_data.get('administrative_osmid')
job.stylesheet = form.cleaned_data.get('stylesheet')
job.layout = form.cleaned_data.get('layout')
job.paper_width_mm = form.cleaned_data.get('paper_width_mm')
job.paper_height_mm = form.cleaned_data.get('paper_height_mm')
job.status = 0 # Submitted
job.submitterip = request.META['REMOTE_ADDR']
job.map_language = form.cleaned_data.get('map_language')
job.index_queue_at_submission = (models.MapRenderingJob.objects
.queue_size())
<|code_end|>
. Use current file imports:
(import datetime
import logging
import ocitysmap
import www.settings
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, HttpResponseBadRequest, HttpResponse
from django.shortcuts import get_object_or_404, render_to_response
from django.template import RequestContext
from django.utils.translation import ugettext_lazy as _
from www.maposmatic import helpers, forms, nominatim, models
from json import dumps as json_encode
from cjson import encode as json_encode
from json import write as json_encode)
and context including class names, function names, or small code snippets from other files:
# Path: www/maposmatic/helpers.py
# def rendering_already_exists_by_osmid(osmid):
# def rendering_already_exists_by_bbox(lat_upper_left, lon_upper_left,
# lat_bottom_right, lon_bottom_right):
# def rendering_already_exists(job):
# def get_pages_list(page, paginator):
# def generate_nonce(length):
#
# Path: www/maposmatic/forms.py
# class MapSearchForm(forms.Form):
# class MapRenderingJobForm(forms.ModelForm):
# class Meta:
# class MapPaperSizeForm(forms.Form):
# class MapRecreateForm(forms.Form):
# class MapCancelForm(forms.Form):
# MODES = (('admin', _('Administrative boundary')),
# ('bbox', _('Bounding box')))
# ORIENTATION = (('portrait', _('Portrait')),
# ('landscape', _('Landscape')))
# def __init__(self, *args, **kwargs):
# def _build_papersize_description(p):
# def clean(self):
# def _check_osm_id(self, osm_id):
# def clean(self):
# def clean(self):
#
# Path: www/maposmatic/nominatim.py
# NOMINATIM_BASE_URL = 'http://nominatim.openstreetmap.org'
# NOMINATIM_MAX_RESULTS_PER_RESPONSE = 10
# NOMINATIM_USER_AGENT = 'MapOSMatic'
# NOMINATIM_USER_AGENT = '%s (%s)' % (NOMINATIM_USER_AGENT,
# www.settings.ADMINS[0][1])
# def reverse_geo(lat, lon):
# def query(query_text, exclude, with_polygons=False, accept_language=None):
# def _fetch_xml(query_text, exclude, with_polygons, accept_language):
# def _extract_entries(xml):
# def _compute_prev_next_excludes(xml):
# def _canonicalize_data(data):
# def _get_admin_boundary_info_from_GIS(cursor, osm_id):
# def _prepare_entry(cursor, entry):
# def _prepare_and_filter_entries(entries):
#
# Path: www/maposmatic/models.py
# class MapRenderingJobManager(models.Manager):
# class MapRenderingJob(models.Model):
# def to_render(self):
# def queue_size(self):
# def get_random_with_thumbnail(self):
# def get_by_filename(self, name):
# def __str__(self):
# def maptitle_computized(self):
# def files_prefix(self):
# def start_rendering(self):
# def end_rendering(self, resultmsg):
# def rendering_time_gt_1min(self):
# def __is_ok(self): return self.resultmsg == 'ok'
# def is_waiting(self): return self.status == 0
# def is_rendering(self): return self.status == 1
# def needs_waiting(self): return self.status < 2
# def is_done(self): return self.status == 2
# def is_done_ok(self): return self.is_done() and self.__is_ok()
# def is_done_failed(self): return self.is_done() and not self.__is_ok()
# def is_obsolete(self): return self.status == 3
# def is_obsolete_ok(self): return self.is_obsolete() and self.__is_ok()
# def is_obsolete_failed(self): return self.is_obsolete() and not self.__is_ok()
# def is_cancelled(self): return self.status == 4
# def can_recreate(self):
# def get_map_fileurl(self, format):
# def get_map_filepath(self, format):
# def output_files(self):
# def has_output_files(self):
# def remove_all_files(self):
# def cancel(self):
# def get_thumbnail(self):
# def current_position_in_queue(self):
# def rendering_estimated_start_time(self):
# def get_absolute_url(self):
# SPACE_REDUCE = re.compile(r"\s+")
# NONASCII_REMOVE = re.compile(r"[^A-Za-z0-9]+")
# STATUS_LIST = (
# (0, 'Submitted'),
# (1, 'In progress'),
# (2, 'Done'),
# (3, 'Done w/o files'),
# (4, 'Cancelled'),
# )
# NONCE_SIZE = 16
. Output only the next line. | job.nonce = helpers.generate_nonce(models.MapRenderingJob.NONCE_SIZE) |
Using the snippet: <|code_start|># Copyright (C) 2009 Thomas Petazzoni
# Copyright (C) 2009 Gaël Utard
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Views for MapOSMatic
LOG = logging.getLogger('maposmatic')
try:
except ImportError:
try:
except ImportError:
def index(request):
"""The main page."""
<|code_end|>
, determine the next line of code. You have imports:
import datetime
import logging
import ocitysmap
import www.settings
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, HttpResponseBadRequest, HttpResponse
from django.shortcuts import get_object_or_404, render_to_response
from django.template import RequestContext
from django.utils.translation import ugettext_lazy as _
from www.maposmatic import helpers, forms, nominatim, models
from json import dumps as json_encode
from cjson import encode as json_encode
from json import write as json_encode
and context (class names, function names, or code) available:
# Path: www/maposmatic/helpers.py
# def rendering_already_exists_by_osmid(osmid):
# def rendering_already_exists_by_bbox(lat_upper_left, lon_upper_left,
# lat_bottom_right, lon_bottom_right):
# def rendering_already_exists(job):
# def get_pages_list(page, paginator):
# def generate_nonce(length):
#
# Path: www/maposmatic/forms.py
# class MapSearchForm(forms.Form):
# class MapRenderingJobForm(forms.ModelForm):
# class Meta:
# class MapPaperSizeForm(forms.Form):
# class MapRecreateForm(forms.Form):
# class MapCancelForm(forms.Form):
# MODES = (('admin', _('Administrative boundary')),
# ('bbox', _('Bounding box')))
# ORIENTATION = (('portrait', _('Portrait')),
# ('landscape', _('Landscape')))
# def __init__(self, *args, **kwargs):
# def _build_papersize_description(p):
# def clean(self):
# def _check_osm_id(self, osm_id):
# def clean(self):
# def clean(self):
#
# Path: www/maposmatic/nominatim.py
# NOMINATIM_BASE_URL = 'http://nominatim.openstreetmap.org'
# NOMINATIM_MAX_RESULTS_PER_RESPONSE = 10
# NOMINATIM_USER_AGENT = 'MapOSMatic'
# NOMINATIM_USER_AGENT = '%s (%s)' % (NOMINATIM_USER_AGENT,
# www.settings.ADMINS[0][1])
# def reverse_geo(lat, lon):
# def query(query_text, exclude, with_polygons=False, accept_language=None):
# def _fetch_xml(query_text, exclude, with_polygons, accept_language):
# def _extract_entries(xml):
# def _compute_prev_next_excludes(xml):
# def _canonicalize_data(data):
# def _get_admin_boundary_info_from_GIS(cursor, osm_id):
# def _prepare_entry(cursor, entry):
# def _prepare_and_filter_entries(entries):
#
# Path: www/maposmatic/models.py
# class MapRenderingJobManager(models.Manager):
# class MapRenderingJob(models.Model):
# def to_render(self):
# def queue_size(self):
# def get_random_with_thumbnail(self):
# def get_by_filename(self, name):
# def __str__(self):
# def maptitle_computized(self):
# def files_prefix(self):
# def start_rendering(self):
# def end_rendering(self, resultmsg):
# def rendering_time_gt_1min(self):
# def __is_ok(self): return self.resultmsg == 'ok'
# def is_waiting(self): return self.status == 0
# def is_rendering(self): return self.status == 1
# def needs_waiting(self): return self.status < 2
# def is_done(self): return self.status == 2
# def is_done_ok(self): return self.is_done() and self.__is_ok()
# def is_done_failed(self): return self.is_done() and not self.__is_ok()
# def is_obsolete(self): return self.status == 3
# def is_obsolete_ok(self): return self.is_obsolete() and self.__is_ok()
# def is_obsolete_failed(self): return self.is_obsolete() and not self.__is_ok()
# def is_cancelled(self): return self.status == 4
# def can_recreate(self):
# def get_map_fileurl(self, format):
# def get_map_filepath(self, format):
# def output_files(self):
# def has_output_files(self):
# def remove_all_files(self):
# def cancel(self):
# def get_thumbnail(self):
# def current_position_in_queue(self):
# def rendering_estimated_start_time(self):
# def get_absolute_url(self):
# SPACE_REDUCE = re.compile(r"\s+")
# NONASCII_REMOVE = re.compile(r"[^A-Za-z0-9]+")
# STATUS_LIST = (
# (0, 'Submitted'),
# (1, 'In progress'),
# (2, 'Done'),
# (3, 'Done w/o files'),
# (4, 'Cancelled'),
# )
# NONCE_SIZE = 16
. Output only the next line. | form = forms.MapSearchForm(request.GET) |
Here is a snippet: <|code_start|>def cancel(request):
if request.method == 'POST':
form = forms.MapCancelForm(request.POST)
if form.is_valid():
job = get_object_or_404(models.MapRenderingJob,
id=form.cleaned_data['id'],
nonce=form.cleaned_data['nonce'])
job.cancel()
return HttpResponseRedirect(reverse('map-by-id-and-nonce',
args=[job.id, job.nonce]))
return HttpResponseBadRequest("ERROR: Invalid request")
def api_nominatim(request):
"""Nominatim query gateway."""
exclude = request.GET.get('exclude', '')
squery = request.GET.get('q', '')
lang = None
if 'HTTP_ACCEPT_LANGUAGE' in request.META:
# Accept-Language headers typically look like
# fr,fr-fr;q=0.8,en-us;q=0.5,en;q=0.3. Unfortunately,
# Nominatim behaves improperly with such a string: it gives
# the region name in French, but the country name in
# English. We split at the first comma to only keep the
# preferred language, which makes Nominatim work properly.
lang = request.META['HTTP_ACCEPT_LANGUAGE'].split(',')[0]
try:
<|code_end|>
. Write the next line using the current file imports:
import datetime
import logging
import ocitysmap
import www.settings
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, HttpResponseBadRequest, HttpResponse
from django.shortcuts import get_object_or_404, render_to_response
from django.template import RequestContext
from django.utils.translation import ugettext_lazy as _
from www.maposmatic import helpers, forms, nominatim, models
from json import dumps as json_encode
from cjson import encode as json_encode
from json import write as json_encode
and context from other files:
# Path: www/maposmatic/helpers.py
# def rendering_already_exists_by_osmid(osmid):
# def rendering_already_exists_by_bbox(lat_upper_left, lon_upper_left,
# lat_bottom_right, lon_bottom_right):
# def rendering_already_exists(job):
# def get_pages_list(page, paginator):
# def generate_nonce(length):
#
# Path: www/maposmatic/forms.py
# class MapSearchForm(forms.Form):
# class MapRenderingJobForm(forms.ModelForm):
# class Meta:
# class MapPaperSizeForm(forms.Form):
# class MapRecreateForm(forms.Form):
# class MapCancelForm(forms.Form):
# MODES = (('admin', _('Administrative boundary')),
# ('bbox', _('Bounding box')))
# ORIENTATION = (('portrait', _('Portrait')),
# ('landscape', _('Landscape')))
# def __init__(self, *args, **kwargs):
# def _build_papersize_description(p):
# def clean(self):
# def _check_osm_id(self, osm_id):
# def clean(self):
# def clean(self):
#
# Path: www/maposmatic/nominatim.py
# NOMINATIM_BASE_URL = 'http://nominatim.openstreetmap.org'
# NOMINATIM_MAX_RESULTS_PER_RESPONSE = 10
# NOMINATIM_USER_AGENT = 'MapOSMatic'
# NOMINATIM_USER_AGENT = '%s (%s)' % (NOMINATIM_USER_AGENT,
# www.settings.ADMINS[0][1])
# def reverse_geo(lat, lon):
# def query(query_text, exclude, with_polygons=False, accept_language=None):
# def _fetch_xml(query_text, exclude, with_polygons, accept_language):
# def _extract_entries(xml):
# def _compute_prev_next_excludes(xml):
# def _canonicalize_data(data):
# def _get_admin_boundary_info_from_GIS(cursor, osm_id):
# def _prepare_entry(cursor, entry):
# def _prepare_and_filter_entries(entries):
#
# Path: www/maposmatic/models.py
# class MapRenderingJobManager(models.Manager):
# class MapRenderingJob(models.Model):
# def to_render(self):
# def queue_size(self):
# def get_random_with_thumbnail(self):
# def get_by_filename(self, name):
# def __str__(self):
# def maptitle_computized(self):
# def files_prefix(self):
# def start_rendering(self):
# def end_rendering(self, resultmsg):
# def rendering_time_gt_1min(self):
# def __is_ok(self): return self.resultmsg == 'ok'
# def is_waiting(self): return self.status == 0
# def is_rendering(self): return self.status == 1
# def needs_waiting(self): return self.status < 2
# def is_done(self): return self.status == 2
# def is_done_ok(self): return self.is_done() and self.__is_ok()
# def is_done_failed(self): return self.is_done() and not self.__is_ok()
# def is_obsolete(self): return self.status == 3
# def is_obsolete_ok(self): return self.is_obsolete() and self.__is_ok()
# def is_obsolete_failed(self): return self.is_obsolete() and not self.__is_ok()
# def is_cancelled(self): return self.status == 4
# def can_recreate(self):
# def get_map_fileurl(self, format):
# def get_map_filepath(self, format):
# def output_files(self):
# def has_output_files(self):
# def remove_all_files(self):
# def cancel(self):
# def get_thumbnail(self):
# def current_position_in_queue(self):
# def rendering_estimated_start_time(self):
# def get_absolute_url(self):
# SPACE_REDUCE = re.compile(r"\s+")
# NONASCII_REMOVE = re.compile(r"[^A-Za-z0-9]+")
# STATUS_LIST = (
# (0, 'Submitted'),
# (1, 'In progress'),
# (2, 'Done'),
# (3, 'Done w/o files'),
# (4, 'Cancelled'),
# )
# NONCE_SIZE = 16
, which may include functions, classes, or code. Output only the next line. | contents = nominatim.query(squery, exclude, with_polygons=False, |
Continue the code snippet: <|code_start|>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Views for MapOSMatic
LOG = logging.getLogger('maposmatic')
try:
except ImportError:
try:
except ImportError:
def index(request):
"""The main page."""
form = forms.MapSearchForm(request.GET)
<|code_end|>
. Use current file imports:
import datetime
import logging
import ocitysmap
import www.settings
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, HttpResponseBadRequest, HttpResponse
from django.shortcuts import get_object_or_404, render_to_response
from django.template import RequestContext
from django.utils.translation import ugettext_lazy as _
from www.maposmatic import helpers, forms, nominatim, models
from json import dumps as json_encode
from cjson import encode as json_encode
from json import write as json_encode
and context (classes, functions, or code) from other files:
# Path: www/maposmatic/helpers.py
# def rendering_already_exists_by_osmid(osmid):
# def rendering_already_exists_by_bbox(lat_upper_left, lon_upper_left,
# lat_bottom_right, lon_bottom_right):
# def rendering_already_exists(job):
# def get_pages_list(page, paginator):
# def generate_nonce(length):
#
# Path: www/maposmatic/forms.py
# class MapSearchForm(forms.Form):
# class MapRenderingJobForm(forms.ModelForm):
# class Meta:
# class MapPaperSizeForm(forms.Form):
# class MapRecreateForm(forms.Form):
# class MapCancelForm(forms.Form):
# MODES = (('admin', _('Administrative boundary')),
# ('bbox', _('Bounding box')))
# ORIENTATION = (('portrait', _('Portrait')),
# ('landscape', _('Landscape')))
# def __init__(self, *args, **kwargs):
# def _build_papersize_description(p):
# def clean(self):
# def _check_osm_id(self, osm_id):
# def clean(self):
# def clean(self):
#
# Path: www/maposmatic/nominatim.py
# NOMINATIM_BASE_URL = 'http://nominatim.openstreetmap.org'
# NOMINATIM_MAX_RESULTS_PER_RESPONSE = 10
# NOMINATIM_USER_AGENT = 'MapOSMatic'
# NOMINATIM_USER_AGENT = '%s (%s)' % (NOMINATIM_USER_AGENT,
# www.settings.ADMINS[0][1])
# def reverse_geo(lat, lon):
# def query(query_text, exclude, with_polygons=False, accept_language=None):
# def _fetch_xml(query_text, exclude, with_polygons, accept_language):
# def _extract_entries(xml):
# def _compute_prev_next_excludes(xml):
# def _canonicalize_data(data):
# def _get_admin_boundary_info_from_GIS(cursor, osm_id):
# def _prepare_entry(cursor, entry):
# def _prepare_and_filter_entries(entries):
#
# Path: www/maposmatic/models.py
# class MapRenderingJobManager(models.Manager):
# class MapRenderingJob(models.Model):
# def to_render(self):
# def queue_size(self):
# def get_random_with_thumbnail(self):
# def get_by_filename(self, name):
# def __str__(self):
# def maptitle_computized(self):
# def files_prefix(self):
# def start_rendering(self):
# def end_rendering(self, resultmsg):
# def rendering_time_gt_1min(self):
# def __is_ok(self): return self.resultmsg == 'ok'
# def is_waiting(self): return self.status == 0
# def is_rendering(self): return self.status == 1
# def needs_waiting(self): return self.status < 2
# def is_done(self): return self.status == 2
# def is_done_ok(self): return self.is_done() and self.__is_ok()
# def is_done_failed(self): return self.is_done() and not self.__is_ok()
# def is_obsolete(self): return self.status == 3
# def is_obsolete_ok(self): return self.is_obsolete() and self.__is_ok()
# def is_obsolete_failed(self): return self.is_obsolete() and not self.__is_ok()
# def is_cancelled(self): return self.status == 4
# def can_recreate(self):
# def get_map_fileurl(self, format):
# def get_map_filepath(self, format):
# def output_files(self):
# def has_output_files(self):
# def remove_all_files(self):
# def cancel(self):
# def get_thumbnail(self):
# def current_position_in_queue(self):
# def rendering_estimated_start_time(self):
# def get_absolute_url(self):
# SPACE_REDUCE = re.compile(r"\s+")
# NONASCII_REMOVE = re.compile(r"[^A-Za-z0-9]+")
# STATUS_LIST = (
# (0, 'Submitted'),
# (1, 'In progress'),
# (2, 'Done'),
# (3, 'Done w/o files'),
# (4, 'Cancelled'),
# )
# NONCE_SIZE = 16
. Output only the next line. | job_list = (models.MapRenderingJob.objects.all() |
Predict the next line for this snippet: <|code_start|># but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Feeds for MapOSMatic
class MapsFeed(Feed):
"""
This feeds syndicates the latest successfully rendered maps in MapOSMatic,
with their thumbnail, and links to the rendered files.
"""
title = www.settings.DEBUG and _('MapOSMatic maps') or _('MapOSMatic maps [DEV]')
link = '/maps/' # We can't use reverse here as the urlpatterns aren't
# defined yet at this point.
description = _('The latest rendered maps on MapOSMatic.')
description_template = 'maposmatic/map-feed.html'
def items(self):
"""Returns the successfully rendered maps from the last 24 hours, or
the last 10 maps/jobs if nothing happened recently."""
one_day_before = datetime.datetime.now() - datetime.timedelta(1)
<|code_end|>
with the help of current file imports:
import datetime
import www.settings
from django.contrib.gis.feeds import Feed
from django.utils.translation import ugettext_lazy as _
from www.maposmatic import models
and context from other files:
# Path: www/maposmatic/models.py
# class MapRenderingJobManager(models.Manager):
# class MapRenderingJob(models.Model):
# def to_render(self):
# def queue_size(self):
# def get_random_with_thumbnail(self):
# def get_by_filename(self, name):
# def __str__(self):
# def maptitle_computized(self):
# def files_prefix(self):
# def start_rendering(self):
# def end_rendering(self, resultmsg):
# def rendering_time_gt_1min(self):
# def __is_ok(self): return self.resultmsg == 'ok'
# def is_waiting(self): return self.status == 0
# def is_rendering(self): return self.status == 1
# def needs_waiting(self): return self.status < 2
# def is_done(self): return self.status == 2
# def is_done_ok(self): return self.is_done() and self.__is_ok()
# def is_done_failed(self): return self.is_done() and not self.__is_ok()
# def is_obsolete(self): return self.status == 3
# def is_obsolete_ok(self): return self.is_obsolete() and self.__is_ok()
# def is_obsolete_failed(self): return self.is_obsolete() and not self.__is_ok()
# def is_cancelled(self): return self.status == 4
# def can_recreate(self):
# def get_map_fileurl(self, format):
# def get_map_filepath(self, format):
# def output_files(self):
# def has_output_files(self):
# def remove_all_files(self):
# def cancel(self):
# def get_thumbnail(self):
# def current_position_in_queue(self):
# def rendering_estimated_start_time(self):
# def get_absolute_url(self):
# SPACE_REDUCE = re.compile(r"\s+")
# NONASCII_REMOVE = re.compile(r"[^A-Za-z0-9]+")
# STATUS_LIST = (
# (0, 'Submitted'),
# (1, 'In progress'),
# (2, 'Done'),
# (3, 'Done w/o files'),
# (4, 'Cancelled'),
# )
# NONCE_SIZE = 16
, which may contain function names, class names, or code. Output only the next line. | items = (models.MapRenderingJob.objects |
Based on the snippet: <|code_start|>try:
except ImportError:
def print_sent(sent):
print (u"\n".join(u"\t".join(cols) for cols in sent)).encode(u"utf-8")
parser = argparse.ArgumentParser(description='Options')
parser.add_argument('-d', required=True, help='Where to save the comments?')
args = parser.parse_args()
comms=dict()
sent_count=0
<|code_end|>
, predict the immediate next line with the help of imports:
from visualize import read_conll
import codecs
import json
import argparse
import compat.argparse as argparse
and context (classes, functions, sometimes code) from other files:
# Path: visualize.py
# def read_conll(inp,maxsent):
# """ Read conll format file and yield one sentence at a time as a list of lists of columns. If inp is a string it will be interpreted as filename, otherwise as open file for reading in unicode"""
# if isinstance(inp,basestring):
# f=codecs.open(inp,u"rt",u"utf-8")
# else:
# f=codecs.getreader("utf-8")(sys.stdin) # read stdin
# count=0
# sent=[]
# comments=[]
# for line in f:
# line=line.strip()
# if not line:
# if sent:
# count+=1
# yield sent, comments
# if maxsent!=0 and count>=maxsent:
# break
# sent=[]
# comments=[]
# elif line.startswith(u"#"):
# if sent:
# raise ValueError("Missing newline after sentence")
# comments.append(line)
# continue
# else:
# sent.append(line.split(u"\t"))
# else:
# if sent:
# yield sent, comments
#
# if isinstance(inp,basestring):
# f.close() #Close it if you opened it
. Output only the next line. | for sent,comments in read_conll(None,0): |
Predict the next line for this snippet: <|code_start|> d_row[HEAD]=gov
d_row[PHEAD]=gov
d_row[DEPREL]=u"dep"
d_row[PDEPREL]=u"dep"
return int(sent[r[0]][ID])-1 #the row index of the root
def cutAndPrintSentence(sent,comments):
subsents=cutSent(sent)
#The first sub-sentence will take on the comment of the whole sentence
print_sent(subsents[0],comments)
#and every other will have a comment marking it as a continuation of the prev. one
for x in subsents[1:]:
assert len(x)>0
print_sent(x,[u"#---sentence---splitter---JOIN-TO-PREVIOUS-SENTENCE---"])
if __name__=="__main__":
parser = argparse.ArgumentParser(description='Split/merge long sentences. Use --reverse to merge.')
parser.add_argument('--reverse', default=False, action="store_true", help='Reverse the splitting.')
parser.add_argument('-N', '--max-len', type=int, default=120, help='Pass sentences shorter or equal to this number of tokens through, split the rest. This will also be the absolute maximum chunk size ever fed into the parser. Default %(default)d.')
parser.add_argument('-C', '--chunk-size', type=int, default=80, help='Split into chunks of approximately this size. Default %(default)d.')
parser.add_argument('input', nargs='?', help='Input. Nothing or "-" for stdin.')
args = parser.parse_args()
args.leeway=args.chunk_size//3 #TODO - better value maybe?
if args.reverse:
last_len=None
last_root=None
<|code_end|>
with the help of current file imports:
from visualize import read_conll
import sys
import codecs
import argparse
import compat.argparse as argparse
and context from other files:
# Path: visualize.py
# def read_conll(inp,maxsent):
# """ Read conll format file and yield one sentence at a time as a list of lists of columns. If inp is a string it will be interpreted as filename, otherwise as open file for reading in unicode"""
# if isinstance(inp,basestring):
# f=codecs.open(inp,u"rt",u"utf-8")
# else:
# f=codecs.getreader("utf-8")(sys.stdin) # read stdin
# count=0
# sent=[]
# comments=[]
# for line in f:
# line=line.strip()
# if not line:
# if sent:
# count+=1
# yield sent, comments
# if maxsent!=0 and count>=maxsent:
# break
# sent=[]
# comments=[]
# elif line.startswith(u"#"):
# if sent:
# raise ValueError("Missing newline after sentence")
# comments.append(line)
# continue
# else:
# sent.append(line.split(u"\t"))
# else:
# if sent:
# yield sent, comments
#
# if isinstance(inp,basestring):
# f.close() #Close it if you opened it
, which may contain function names, class names, or code. Output only the next line. | for sent,comments in read_conll(args.input,0): |
Predict the next line for this snippet: <|code_start|>
try:
except ImportError:
SCRIPTDIR=os.path.dirname(os.path.abspath(__file__))
# 0 1 2 3 4 5 6 7 8 9 10 11
#conll-u ID FORM LEMMA CPOS POS FEAT HEAD DEPREL DEPS MISC
#conll-09 ID FORM LEMMA PLEMMA POS PPOS FEAT PFEAT HEAD PHEAD DEPREL PDEPREL _ _
def visualize_clauses(args):
data_to_print=u""
count=1
<|code_end|>
with the help of current file imports:
import codecs
import sys
import os
import argparse
import compat.argparse as argparse
from collections import defaultdict
from visualize import read_conll,sort_feat,header,footer
and context from other files:
# Path: visualize.py
# SCRIPTDIR=os.path.dirname(os.path.abspath(__file__))
# def read_conll(inp,maxsent):
# def sort_feat(f):
# def get_col(cols,idx):
# def visualize(args):
, which may contain function names, class names, or code. Output only the next line. | for sent,comments in read_conll(args.input,args.max_sent): |
Given the following code snippet before the placeholder: <|code_start|>
try:
except ImportError:
SCRIPTDIR=os.path.dirname(os.path.abspath(__file__))
# 0 1 2 3 4 5 6 7 8 9 10 11
#conll-u ID FORM LEMMA CPOS POS FEAT HEAD DEPREL DEPS MISC
#conll-09 ID FORM LEMMA PLEMMA POS PPOS FEAT PFEAT HEAD PHEAD DEPREL PDEPREL _ _
def visualize_clauses(args):
data_to_print=u""
count=1
for sent,comments in read_conll(args.input,args.max_sent):
d=defaultdict(lambda:[])
for line in sent:
if len(line)==10: #conll-u
<|code_end|>
, predict the next line using imports from the current file:
import codecs
import sys
import os
import argparse
import compat.argparse as argparse
from collections import defaultdict
from visualize import read_conll,sort_feat,header,footer
and context including class names, function names, and sometimes code from other files:
# Path: visualize.py
# SCRIPTDIR=os.path.dirname(os.path.abspath(__file__))
# def read_conll(inp,maxsent):
# def sort_feat(f):
# def get_col(cols,idx):
# def visualize(args):
. Output only the next line. | line[5]=sort_feat(line[5]) |
Continue the code snippet: <|code_start|> line[6]=sort_feat(line[6])
l=[line[i] for i in [0,1,2,4,5,6,8,10]] # take idx,token,lemma,pos,pos,feat,deprel,head
l.append(u"_") #DEPS
l.append(line[12]) #and MISC for CoNLL-U
idx=line[12]
d[count].append(l)
if idx!=u"_":
d[idx].append(l)
for idx,tree in sorted(d.iteritems()):
root=None
root_deprel=u"ROOT"
root_token=u"ROOT"
if idx!=count:
indexes={}
for i in xrange(0,len(tree)):
token=int(tree[i][0])
indexes[token]=len(indexes)+2
for line in tree:
line[0]=unicode(indexes[int(line[0])])
if int(line[6]) in indexes:
line[6]=unicode(indexes[int(line[6])])
else: # this is root
head=int(line[6])
line[6]=u"1"
root=line[0]
root_deprel=line[7]
if head!=0:
root_token=d[count][head-1][1]
# tree to text
<|code_end|>
. Use current file imports:
import codecs
import sys
import os
import argparse
import compat.argparse as argparse
from collections import defaultdict
from visualize import read_conll,sort_feat,header,footer
and context (classes, functions, or code) from other files:
# Path: visualize.py
# SCRIPTDIR=os.path.dirname(os.path.abspath(__file__))
# def read_conll(inp,maxsent):
# def sort_feat(f):
# def get_col(cols,idx):
# def visualize(args):
. Output only the next line. | text=header |
Based on the snippet: <|code_start|> indexes={}
for i in xrange(0,len(tree)):
token=int(tree[i][0])
indexes[token]=len(indexes)+2
for line in tree:
line[0]=unicode(indexes[int(line[0])])
if int(line[6]) in indexes:
line[6]=unicode(indexes[int(line[6])])
else: # this is root
head=int(line[6])
line[6]=u"1"
root=line[0]
root_deprel=line[7]
if head!=0:
root_token=d[count][head-1][1]
# tree to text
text=header
text+=u"# sentence-label\t%s\n"%(unicode(idx))
if root is not None:
text+=u"# visual-style\t%s\tbgColor:red\n"%(u"1")
text+=u"# visual-style %s %s %s\tcolor:red\n"%(u"1",root,root_deprel)
if comments:
text+=u"\n".join(comments)+u"\n"
if idx!=count:
root_token=u"**%s**"%(root_token)
text+=u"\t".join(t for t in [u"1",root_token,u"_",u"_",u"_",u"_",u"0",root_deprel,u"_",u"_"])+u"\n"
for line in tree:
text+=u"\t".join(line[i] for i in range(10))+u"\n"
text+=u"\n" #conll-u expects an empty line at the end of every tree
<|code_end|>
, predict the immediate next line with the help of imports:
import codecs
import sys
import os
import argparse
import compat.argparse as argparse
from collections import defaultdict
from visualize import read_conll,sort_feat,header,footer
and context (classes, functions, sometimes code) from other files:
# Path: visualize.py
# SCRIPTDIR=os.path.dirname(os.path.abspath(__file__))
# def read_conll(inp,maxsent):
# def sort_feat(f):
# def get_col(cols,idx):
# def visualize(args):
. Output only the next line. | text+=footer |
Using the snippet: <|code_start|>try:
except ImportError:
def print_sent(sent,comments):
if comments:
print (u"\n".join(comments)).encode(u"utf-8")
print (u"\n".join(u"\t".join(cols) for cols in sent)).encode(u"utf-8")
parser = argparse.ArgumentParser(description='Options')
parser.add_argument('-d', required=True, help='Where to read the comments?')
args = parser.parse_args()
comms=None
if os.path.isfile(args.d):
with open(args.d,"r") as f:
comms=json.load(f)
sent_count=0
<|code_end|>
, determine the next line of code. You have imports:
from visualize import read_conll
import codecs
import json
import os.path
import argparse
import compat.argparse as argparse
and context (class names, function names, or code) available:
# Path: visualize.py
# def read_conll(inp,maxsent):
# """ Read conll format file and yield one sentence at a time as a list of lists of columns. If inp is a string it will be interpreted as filename, otherwise as open file for reading in unicode"""
# if isinstance(inp,basestring):
# f=codecs.open(inp,u"rt",u"utf-8")
# else:
# f=codecs.getreader("utf-8")(sys.stdin) # read stdin
# count=0
# sent=[]
# comments=[]
# for line in f:
# line=line.strip()
# if not line:
# if sent:
# count+=1
# yield sent, comments
# if maxsent!=0 and count>=maxsent:
# break
# sent=[]
# comments=[]
# elif line.startswith(u"#"):
# if sent:
# raise ValueError("Missing newline after sentence")
# comments.append(line)
# continue
# else:
# sent.append(line.split(u"\t"))
# else:
# if sent:
# yield sent, comments
#
# if isinstance(inp,basestring):
# f.close() #Close it if you opened it
. Output only the next line. | for sent,comments in read_conll(None,0): |
Continue the code snippet: <|code_start|>
is_python3 = sys.version_info >= (3,)
# minutes before purging an event from the database
EVENT_TIMEOUT = 60 * 24
# attempt to trim this many events per pass
EVENT_TRIM_BATCH = 50
class EventDoesNotExist(Exception):
def __init__(self, message, current_id):
super(Exception, self).__init__(message)
self.current_id = current_id
class StorageBase(object):
def append_event(self, channel, event_type, data):
raise NotImplementedError()
def get_events(self, channel, last_id, limit=100):
raise NotImplementedError()
def get_current_id(self, channel):
raise NotImplementedError()
class DjangoModelStorage(StorageBase):
def append_event(self, channel, event_type, data):
<|code_end|>
. Use current file imports:
import sys
import json
import datetime
from django.utils import timezone
from django.core.serializers.json import DjangoJSONEncoder
from .event import Event
from . import models
from . import models
from . import models
from . import models
and context (classes, functions, or code) from other files:
# Path: django_eventstream/event.py
# class Event(object):
# def __init__(self, channel, type, data, id=None):
# self.channel = channel
# self.type = type
# self.data = data
# self.id = id
. Output only the next line. | db_event = models.Event( |
Here is a snippet: <|code_start|> room = ChatRoom.objects.get(eid=room_id)
cmsgs = ChatMessage.objects.filter(
room=room).order_by('-date')[:50]
msgs = [msg.to_data() for msg in cmsgs]
except ChatRoom.DoesNotExist:
msgs = []
body = json.dumps(
{
'messages': msgs,
'last-event-id': last_id
},
cls=DjangoJSONEncoder) + '\n'
return HttpResponse(body, content_type='application/json')
elif request.method == 'POST':
try:
room = ChatRoom.objects.get(eid=room_id)
except ChatRoom.DoesNotExist:
try:
room = ChatRoom(eid=room_id)
room.save()
except IntegrityError:
# someone else made the room. no problem
room = ChatRoom.objects.get(eid=room_id)
mfrom = request.POST['from']
text = request.POST['text']
with transaction.atomic():
msg = ChatMessage(room=room, user=mfrom, text=text)
msg.save()
<|code_end|>
. Write the next line using the current file imports:
import json
from django.http import HttpResponse, HttpResponseNotAllowed
from django.db import IntegrityError, transaction
from django.shortcuts import render, redirect
from django.core.serializers.json import DjangoJSONEncoder
from django_eventstream import send_event, get_current_event_id
from .models import ChatRoom, ChatMessage
and context from other files:
# Path: django_eventstream/eventstream.py
# def send_event(channel, event_type, data, skip_user_ids=None, async_publish=True, json_encode=True):
# from .event import Event
#
# if skip_user_ids is None:
# skip_user_ids = []
#
# storage = get_storage()
# channelmanager = get_channelmanager()
#
# if channelmanager.is_channel_reliable(channel) and storage:
# e = storage.append_event(channel, event_type, data)
# pub_id = str(e.id)
# pub_prev_id = str(e.id - 1)
# else:
# e = Event(channel, event_type, data)
# pub_id = None
# pub_prev_id = None
#
# if have_channels():
# from .consumers import get_listener_manager
# # send to local listeners
# get_listener_manager().add_to_queues(channel, e)
#
# # publish through grip proxy
# publish_event(
# channel,
# event_type,
# data,
# pub_id,
# pub_prev_id,
# skip_user_ids=skip_user_ids,
# blocking=(not async_publish),
# json_encode=json_encode)
#
# def get_current_event_id(channels):
# storage = get_storage()
#
# if not storage:
# raise ValueError('get_current_event_id requires storage to be enabled')
#
# cur_ids = {}
# for channel in channels:
# cur_ids[channel] = str(storage.get_current_id(channel))
#
# return make_id(cur_ids)
#
# Path: examples/chat/chat/models.py
# class ChatRoom(models.Model):
# eid = models.CharField(max_length=64, unique=True)
#
# class ChatMessage(models.Model):
# room = models.ForeignKey(ChatRoom, on_delete=models.CASCADE)
# user = models.CharField(max_length=64)
# date = models.DateTimeField(auto_now=True, db_index=True)
# text = models.TextField()
#
# def to_data(self):
# out = {}
# out['id'] = self.id
# out['from'] = self.user
# out['date'] = self.date
# out['text'] = self.text
# return out
, which may include functions, classes, or code. Output only the next line. | send_event('room-{}'.format(room_id), 'message', msg.to_data()) |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
def home(request, room_id=None):
user = request.GET.get('user')
if user:
if not room_id:
return redirect('/default?' + request.GET.urlencode())
<|code_end|>
, predict the next line using imports from the current file:
import json
from django.http import HttpResponse, HttpResponseNotAllowed
from django.db import IntegrityError, transaction
from django.shortcuts import render, redirect
from django.core.serializers.json import DjangoJSONEncoder
from django_eventstream import send_event, get_current_event_id
from .models import ChatRoom, ChatMessage
and context including class names, function names, and sometimes code from other files:
# Path: django_eventstream/eventstream.py
# def send_event(channel, event_type, data, skip_user_ids=None, async_publish=True, json_encode=True):
# from .event import Event
#
# if skip_user_ids is None:
# skip_user_ids = []
#
# storage = get_storage()
# channelmanager = get_channelmanager()
#
# if channelmanager.is_channel_reliable(channel) and storage:
# e = storage.append_event(channel, event_type, data)
# pub_id = str(e.id)
# pub_prev_id = str(e.id - 1)
# else:
# e = Event(channel, event_type, data)
# pub_id = None
# pub_prev_id = None
#
# if have_channels():
# from .consumers import get_listener_manager
# # send to local listeners
# get_listener_manager().add_to_queues(channel, e)
#
# # publish through grip proxy
# publish_event(
# channel,
# event_type,
# data,
# pub_id,
# pub_prev_id,
# skip_user_ids=skip_user_ids,
# blocking=(not async_publish),
# json_encode=json_encode)
#
# def get_current_event_id(channels):
# storage = get_storage()
#
# if not storage:
# raise ValueError('get_current_event_id requires storage to be enabled')
#
# cur_ids = {}
# for channel in channels:
# cur_ids[channel] = str(storage.get_current_id(channel))
#
# return make_id(cur_ids)
#
# Path: examples/chat/chat/models.py
# class ChatRoom(models.Model):
# eid = models.CharField(max_length=64, unique=True)
#
# class ChatMessage(models.Model):
# room = models.ForeignKey(ChatRoom, on_delete=models.CASCADE)
# user = models.CharField(max_length=64)
# date = models.DateTimeField(auto_now=True, db_index=True)
# text = models.TextField()
#
# def to_data(self):
# out = {}
# out['id'] = self.id
# out['from'] = self.user
# out['date'] = self.date
# out['text'] = self.text
# return out
. Output only the next line. | last_id = get_current_event_id(['room-{}'.format(room_id)]) |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
def home(request, room_id=None):
user = request.GET.get('user')
if user:
if not room_id:
return redirect('/default?' + request.GET.urlencode())
last_id = get_current_event_id(['room-{}'.format(room_id)])
try:
<|code_end|>
, predict the immediate next line with the help of imports:
import json
from django.http import HttpResponse, HttpResponseNotAllowed
from django.db import IntegrityError, transaction
from django.shortcuts import render, redirect
from django.core.serializers.json import DjangoJSONEncoder
from django_eventstream import send_event, get_current_event_id
from .models import ChatRoom, ChatMessage
and context (classes, functions, sometimes code) from other files:
# Path: django_eventstream/eventstream.py
# def send_event(channel, event_type, data, skip_user_ids=None, async_publish=True, json_encode=True):
# from .event import Event
#
# if skip_user_ids is None:
# skip_user_ids = []
#
# storage = get_storage()
# channelmanager = get_channelmanager()
#
# if channelmanager.is_channel_reliable(channel) and storage:
# e = storage.append_event(channel, event_type, data)
# pub_id = str(e.id)
# pub_prev_id = str(e.id - 1)
# else:
# e = Event(channel, event_type, data)
# pub_id = None
# pub_prev_id = None
#
# if have_channels():
# from .consumers import get_listener_manager
# # send to local listeners
# get_listener_manager().add_to_queues(channel, e)
#
# # publish through grip proxy
# publish_event(
# channel,
# event_type,
# data,
# pub_id,
# pub_prev_id,
# skip_user_ids=skip_user_ids,
# blocking=(not async_publish),
# json_encode=json_encode)
#
# def get_current_event_id(channels):
# storage = get_storage()
#
# if not storage:
# raise ValueError('get_current_event_id requires storage to be enabled')
#
# cur_ids = {}
# for channel in channels:
# cur_ids[channel] = str(storage.get_current_id(channel))
#
# return make_id(cur_ids)
#
# Path: examples/chat/chat/models.py
# class ChatRoom(models.Model):
# eid = models.CharField(max_length=64, unique=True)
#
# class ChatMessage(models.Model):
# room = models.ForeignKey(ChatRoom, on_delete=models.CASCADE)
# user = models.CharField(max_length=64)
# date = models.DateTimeField(auto_now=True, db_index=True)
# text = models.TextField()
#
# def to_data(self):
# out = {}
# out['id'] = self.id
# out['from'] = self.user
# out['date'] = self.date
# out['text'] = self.text
# return out
. Output only the next line. | room = ChatRoom.objects.get(eid=room_id) |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
def home(request, room_id=None):
user = request.GET.get('user')
if user:
if not room_id:
return redirect('/default?' + request.GET.urlencode())
last_id = get_current_event_id(['room-{}'.format(room_id)])
try:
room = ChatRoom.objects.get(eid=room_id)
<|code_end|>
, generate the next line using the imports in this file:
import json
from django.http import HttpResponse, HttpResponseNotAllowed
from django.db import IntegrityError, transaction
from django.shortcuts import render, redirect
from django.core.serializers.json import DjangoJSONEncoder
from django_eventstream import send_event, get_current_event_id
from .models import ChatRoom, ChatMessage
and context (functions, classes, or occasionally code) from other files:
# Path: django_eventstream/eventstream.py
# def send_event(channel, event_type, data, skip_user_ids=None, async_publish=True, json_encode=True):
# from .event import Event
#
# if skip_user_ids is None:
# skip_user_ids = []
#
# storage = get_storage()
# channelmanager = get_channelmanager()
#
# if channelmanager.is_channel_reliable(channel) and storage:
# e = storage.append_event(channel, event_type, data)
# pub_id = str(e.id)
# pub_prev_id = str(e.id - 1)
# else:
# e = Event(channel, event_type, data)
# pub_id = None
# pub_prev_id = None
#
# if have_channels():
# from .consumers import get_listener_manager
# # send to local listeners
# get_listener_manager().add_to_queues(channel, e)
#
# # publish through grip proxy
# publish_event(
# channel,
# event_type,
# data,
# pub_id,
# pub_prev_id,
# skip_user_ids=skip_user_ids,
# blocking=(not async_publish),
# json_encode=json_encode)
#
# def get_current_event_id(channels):
# storage = get_storage()
#
# if not storage:
# raise ValueError('get_current_event_id requires storage to be enabled')
#
# cur_ids = {}
# for channel in channels:
# cur_ids[channel] = str(storage.get_current_id(channel))
#
# return make_id(cur_ids)
#
# Path: examples/chat/chat/models.py
# class ChatRoom(models.Model):
# eid = models.CharField(max_length=64, unique=True)
#
# class ChatMessage(models.Model):
# room = models.ForeignKey(ChatRoom, on_delete=models.CASCADE)
# user = models.CharField(max_length=64)
# date = models.DateTimeField(auto_now=True, db_index=True)
# text = models.TextField()
#
# def to_data(self):
# out = {}
# out['id'] = self.id
# out['from'] = self.user
# out['date'] = self.date
# out['text'] = self.text
# return out
. Output only the next line. | cmsgs = ChatMessage.objects.filter( |
Continue the code snippet: <|code_start|>https://docs.djangoproject.com/en/2.1/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '$(_bts_5if59ns1(7u2!opjy*+3^+pwf_rr8=rm0o8ih+ts9xl'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
<|code_end|>
. Use current file imports:
import os
import dj_database_url
from django_eventstream.utils import have_channels
and context (classes, functions, or code) from other files:
# Path: django_eventstream/utils.py
# def have_channels():
# try:
# from channels.generic.http import AsyncHttpConsumer
# return True
# except ImportError:
# return False
. Output only the next line. | if have_channels(): |
Predict the next line after this snippet: <|code_start|>
def events(request, **kwargs):
try:
event_request = EventRequest(request, view_kwargs=kwargs)
event_response = get_events(event_request)
response = event_response.to_http_response(request)
except EventRequest.ResumeNotAllowedError as e:
response = HttpResponseBadRequest(
'Invalid request: %s.\n' % str(e))
except EventRequest.GripError as e:
if request.grip.proxied:
response = sse_error_response(
'internal-error',
'Invalid internal request.')
else:
response = sse_error_response(
'bad-request',
'Invalid request: %s.' % str(e))
except EventRequest.Error as e:
response = sse_error_response(
'bad-request',
'Invalid request: %s.' % str(e))
except EventPermissionError as e:
response = sse_error_response(
'forbidden',
str(e),
{'channels': e.channels})
<|code_end|>
using the current file's imports:
from django.http import HttpResponseBadRequest
from .utils import add_default_headers
from .eventrequest import EventRequest
from .eventstream import EventPermissionError, get_events
from .utils import sse_error_response
and any relevant context from other files:
# Path: django_eventstream/utils.py
# def add_default_headers(headers):
# headers['Cache-Control'] = 'no-cache'
# headers['X-Accel-Buffering'] = 'no'
# augment_cors_headers(headers)
. Output only the next line. | add_default_headers(response) |
Given snippet: <|code_start|>
def home(request):
context = {}
context['url'] = '/events/'
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.shortcuts import render
from django_eventstream import get_current_event_id
and context:
# Path: django_eventstream/eventstream.py
# def get_current_event_id(channels):
# storage = get_storage()
#
# if not storage:
# raise ValueError('get_current_event_id requires storage to be enabled')
#
# cur_ids = {}
# for channel in channels:
# cur_ids[channel] = str(storage.get_current_id(channel))
#
# return make_id(cur_ids)
which might include code, classes, or functions. Output only the next line. | context['last_id'] = get_current_event_id(['time']) |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
class DjangoStorageTest(TestCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
<|code_end|>
using the current file's imports:
from django.test import TestCase
from django_eventstream.storage import DjangoModelStorage, EventDoesNotExist
and any relevant context from other files:
# Path: django_eventstream/storage.py
# class DjangoModelStorage(StorageBase):
# def append_event(self, channel, event_type, data):
# from . import models
#
# db_event = models.Event(
# channel=channel,
# type=event_type,
# data=json.dumps(data, cls=DjangoJSONEncoder))
# db_event.save()
#
# self.trim_event_log()
#
# e = Event(
# db_event.channel,
# db_event.type,
# data,
# id=db_event.eid)
#
# return e
#
# def get_events(self, channel, last_id, limit=100):
# from . import models
#
# if is_python3:
# assert(isinstance(last_id, int))
# else:
# assert(isinstance(last_id, (int, long)))
#
# try:
# ec = models.EventCounter.objects.get(name=channel)
# cur_id = ec.value
# except models.EventCounter.DoesNotExist:
# cur_id = 0
#
# if last_id == cur_id:
# return []
#
# # look up the referenced event first, to avoid a range query when
# # the referenced event doesn't exist
# try:
# models.Event.objects.get(
# channel=channel,
# eid=last_id)
# except models.Event.DoesNotExist:
# raise EventDoesNotExist(
# 'No such event %d' % last_id,
# cur_id)
#
# # increase limit by 1 since we'll exclude the first result
# db_events = models.Event.objects.filter(
# channel=channel,
# eid__gte=last_id
# ).order_by('eid')[:limit + 1]
#
# # ensure the first result matches the referenced event
# if len(db_events) == 0 or db_events[0].eid != last_id:
# raise EventDoesNotExist(
# 'No such event %d' % last_id,
# cur_id)
#
# # exclude the first result
# db_events = db_events[1:]
#
# out = []
# for db_event in db_events:
# e = Event(
# db_event.channel,
# db_event.type,
# json.loads(db_event.data),
# id=db_event.eid)
# out.append(e)
#
# return out
#
# def get_current_id(self, channel):
# from . import models
#
# try:
# ec = models.EventCounter.objects.get(name=channel)
# return ec.value
# except models.EventCounter.DoesNotExist:
# return 0
#
# def trim_event_log(self):
# from . import models
#
# now = timezone.now()
# cutoff = now - datetime.timedelta(minutes=EVENT_TIMEOUT)
# while True:
# events = models.Event.objects.filter(
# created__lt=cutoff
# )[:EVENT_TRIM_BATCH]
# if len(events) < 1:
# break
# for e in events:
# try:
# e.delete()
# except models.Event.DoesNotExist:
# # someone else deleted. that's fine
# pass
#
# class EventDoesNotExist(Exception):
# def __init__(self, message, current_id):
# super(Exception, self).__init__(message)
# self.current_id = current_id
. Output only the next line. | cls.storage = DjangoModelStorage() |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
class DjangoStorageTest(TestCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.storage = DjangoModelStorage()
def test_empty_channel_id(self):
self.assertEqual(self.storage.get_current_id('empty'), 0)
def test_empty_channel_events(self):
self.assertEqual(self.storage.get_events('empty', 0), [])
def test_empty_channel_error(self):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.test import TestCase
from django_eventstream.storage import DjangoModelStorage, EventDoesNotExist
and context:
# Path: django_eventstream/storage.py
# class DjangoModelStorage(StorageBase):
# def append_event(self, channel, event_type, data):
# from . import models
#
# db_event = models.Event(
# channel=channel,
# type=event_type,
# data=json.dumps(data, cls=DjangoJSONEncoder))
# db_event.save()
#
# self.trim_event_log()
#
# e = Event(
# db_event.channel,
# db_event.type,
# data,
# id=db_event.eid)
#
# return e
#
# def get_events(self, channel, last_id, limit=100):
# from . import models
#
# if is_python3:
# assert(isinstance(last_id, int))
# else:
# assert(isinstance(last_id, (int, long)))
#
# try:
# ec = models.EventCounter.objects.get(name=channel)
# cur_id = ec.value
# except models.EventCounter.DoesNotExist:
# cur_id = 0
#
# if last_id == cur_id:
# return []
#
# # look up the referenced event first, to avoid a range query when
# # the referenced event doesn't exist
# try:
# models.Event.objects.get(
# channel=channel,
# eid=last_id)
# except models.Event.DoesNotExist:
# raise EventDoesNotExist(
# 'No such event %d' % last_id,
# cur_id)
#
# # increase limit by 1 since we'll exclude the first result
# db_events = models.Event.objects.filter(
# channel=channel,
# eid__gte=last_id
# ).order_by('eid')[:limit + 1]
#
# # ensure the first result matches the referenced event
# if len(db_events) == 0 or db_events[0].eid != last_id:
# raise EventDoesNotExist(
# 'No such event %d' % last_id,
# cur_id)
#
# # exclude the first result
# db_events = db_events[1:]
#
# out = []
# for db_event in db_events:
# e = Event(
# db_event.channel,
# db_event.type,
# json.loads(db_event.data),
# id=db_event.eid)
# out.append(e)
#
# return out
#
# def get_current_id(self, channel):
# from . import models
#
# try:
# ec = models.EventCounter.objects.get(name=channel)
# return ec.value
# except models.EventCounter.DoesNotExist:
# return 0
#
# def trim_event_log(self):
# from . import models
#
# now = timezone.now()
# cutoff = now - datetime.timedelta(minutes=EVENT_TIMEOUT)
# while True:
# events = models.Event.objects.filter(
# created__lt=cutoff
# )[:EVENT_TRIM_BATCH]
# if len(events) < 1:
# break
# for e in events:
# try:
# e.delete()
# except models.Event.DoesNotExist:
# # someone else deleted. that's fine
# pass
#
# class EventDoesNotExist(Exception):
# def __init__(self, message, current_id):
# super(Exception, self).__init__(message)
# self.current_id = current_id
which might include code, classes, or functions. Output only the next line. | with self.assertRaises(EventDoesNotExist) as cm: |
Using the snippet: <|code_start|>https://docs.djangoproject.com/en/2.1/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '$(_bts_5if59ns1(7u2!opjy*+3^+pwf_rr8=rm0o8ih+ts9xl'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
<|code_end|>
, determine the next line of code. You have imports:
import os
import dj_database_url
from django_eventstream.utils import have_channels
and context (class names, function names, or code) available:
# Path: django_eventstream/utils.py
# def have_channels():
# try:
# from channels.generic.http import AsyncHttpConsumer
# return True
# except ImportError:
# return False
. Output only the next line. | if have_channels(): |
Continue the code snippet: <|code_start|> response = None
except EventRequest.ResumeNotAllowedError as e:
response = HttpResponseBadRequest(
'Invalid request: %s.\n' % str(e))
except EventRequest.GripError as e:
if request.grip.proxied:
response = sse_error_response(
'internal-error',
'Invalid internal request.')
else:
response = sse_error_response(
'bad-request',
'Invalid request: %s.' % str(e))
except EventRequest.Error as e:
response = sse_error_response(
'bad-request',
'Invalid request: %s.' % str(e))
# for grip requests, prepare immediate response
if not response and request.grip.proxied:
try:
event_response = await self.get_events(event_request)
response = event_response.to_http_response(request)
except EventPermissionError as e:
response = sse_error_response(
'forbidden',
str(e),
{'channels': e.channels})
extra_headers = {}
<|code_end|>
. Use current file imports:
import copy
import threading
import asyncio
import six
from django.http import HttpResponseBadRequest
from channels.generic.http import AsyncHttpConsumer
from channels.http import AsgiRequest
from channels.db import database_sync_to_async
from .utils import add_default_headers
from .eventrequest import EventRequest
from .eventstream import get_events
from django_grip import GripMiddleware
from .eventrequest import EventRequest
from .eventstream import EventPermissionError
from .utils import sse_error_response
from .eventstream import EventPermissionError
from .utils import sse_encode_event, make_id
and context (classes, functions, or code) from other files:
# Path: django_eventstream/utils.py
# def add_default_headers(headers):
# headers['Cache-Control'] = 'no-cache'
# headers['X-Accel-Buffering'] = 'no'
# augment_cors_headers(headers)
. Output only the next line. | add_default_headers(extra_headers) |
Predict the next line for this snippet: <|code_start|> if len(channels) > channel_limit:
raise EventRequest.Error('Channel limit exceeded')
if http_request.GET.get('link') == 'next':
is_next = True
if http_request.GET.get('recover') == 'true':
channel_last_ids = {}
is_recover = True
for grip_channel, last_id in six.iteritems(http_request.grip.last):
if not grip_channel.startswith('events-'):
continue
channel = unquote(grip_channel[7:])
if channel in channels:
channel_last_ids[channel] = last_id
else:
last_event_id = http_request.META.get('HTTP_LAST_EVENT_ID')
if not last_event_id:
# take the first non-empty param, from the end
for val in reversed(http_request.GET.getlist('lastEventId')):
if val:
last_event_id = val
break
if last_event_id:
if last_event_id == 'error':
raise EventRequest.ResumeNotAllowedError(
'Can\'t resume session after stream-error')
try:
<|code_end|>
with the help of current file imports:
import time
import jwt
import six
from django.contrib.auth import get_user_model
from django.conf import settings
from .utils import parse_last_event_id, get_channelmanager
from urllib import unquote
from urllib.parse import unquote
and context from other files:
# Path: django_eventstream/utils.py
# def parse_last_event_id(s):
# out = {}
# parts = s.split(',')
# for part in parts:
# channel, last_id = part.split(':')
# out[channel] = last_id
# return out
#
# def get_channelmanager():
# return get_class_from_setting(
# 'EVENTSTREAM_CHANNELMANAGER_CLASS',
# 'django_eventstream.channelmanager.DefaultChannelManager')
, which may contain function names, class names, or code. Output only the next line. | parsed = parse_last_event_id(last_event_id) |
Given the code snippet: <|code_start|> self.channel_last_ids = {}
self.is_recover = False
self.user = None
if http_request:
self.apply_http_request(http_request,
channel_limit=channel_limit,
view_kwargs=view_kwargs)
def apply_http_request(self, http_request, channel_limit, view_kwargs):
is_next = False
is_recover = False
user = None
es_meta = {}
if http_request.GET.get('es-meta'):
es_meta = jwt.decode(http_request.GET['es-meta'], settings.SECRET_KEY.encode('utf-8'), algorithms=['HS256'])
if int(time.time()) >= es_meta['exp']:
raise ValueError('es-meta signature is expired')
if 'user' in es_meta:
if es_meta['user'] != 'anonymous':
user = get_user_model().objects.get(pk=es_meta['user'])
else:
if hasattr(http_request, 'user') and http_request.user.is_authenticated:
user = http_request.user
if 'channels' in es_meta:
channels = es_meta['channels']
else:
<|code_end|>
, generate the next line using the imports in this file:
import time
import jwt
import six
from django.contrib.auth import get_user_model
from django.conf import settings
from .utils import parse_last_event_id, get_channelmanager
from urllib import unquote
from urllib.parse import unquote
and context (functions, classes, or occasionally code) from other files:
# Path: django_eventstream/utils.py
# def parse_last_event_id(s):
# out = {}
# parts = s.split(',')
# for part in parts:
# channel, last_id = part.split(':')
# out[channel] = last_id
# return out
#
# def get_channelmanager():
# return get_class_from_setting(
# 'EVENTSTREAM_CHANNELMANAGER_CLASS',
# 'django_eventstream.channelmanager.DefaultChannelManager')
. Output only the next line. | channelmanager = get_channelmanager() |
Here is a snippet: <|code_start|>
try:
except ImportError:
class EventResponse(object):
def __init__(self):
self.channel_items = {}
self.channel_last_ids = {}
self.channel_reset = set()
self.channel_more = set()
self.is_next = False
self.is_recover = False
self.user = None
def to_http_response(self, http_request):
last_ids = copy.deepcopy(self.channel_last_ids)
event_id = make_id(last_ids)
body = ''
if not self.is_next:
body += ':' + (' ' * 2048) + '\n\n'
body += 'event: stream-open\ndata:\n\n'
if len(self.channel_reset) > 0:
<|code_end|>
. Write the next line using the current file imports:
import copy
import time
import jwt
import six
from gripcontrol import Channel
from django.conf import settings
from django.http import HttpResponse
from .utils import sse_encode_event, make_id, build_id_escape
from urllib import quote
from urllib.parse import quote
and context from other files:
# Path: django_eventstream/utils.py
# def sse_encode_event(event_type, data, event_id=None, escape=False, json_encode=True):
# if json_encode:
# data_str = json.dumps(data, cls=DjangoJSONEncoder)
# else:
# data_str = data
# if escape:
# event_type = build_id_escape(event_type)
# data_str = build_id_escape(data_str)
# out = 'event: %s\n' % event_type
# if event_id:
# out += 'id: %s\n' % event_id
# out += 'data: %s\n\n' % data_str
# return out
#
# def make_id(ids):
# id_parts = []
# for channel, id in six.iteritems(ids):
# enc_channel = quote(channel)
# id_parts.append('%s:%s' % (enc_channel, id))
# return ','.join(id_parts)
#
# def build_id_escape(s):
# out = ''
# for c in s:
# if c == '%':
# out += '%%'
# else:
# out += c
# return out
, which may include functions, classes, or code. Output only the next line. | body += sse_encode_event( |
Using the snippet: <|code_start|>
try:
except ImportError:
class EventResponse(object):
def __init__(self):
self.channel_items = {}
self.channel_last_ids = {}
self.channel_reset = set()
self.channel_more = set()
self.is_next = False
self.is_recover = False
self.user = None
def to_http_response(self, http_request):
last_ids = copy.deepcopy(self.channel_last_ids)
<|code_end|>
, determine the next line of code. You have imports:
import copy
import time
import jwt
import six
from gripcontrol import Channel
from django.conf import settings
from django.http import HttpResponse
from .utils import sse_encode_event, make_id, build_id_escape
from urllib import quote
from urllib.parse import quote
and context (class names, function names, or code) available:
# Path: django_eventstream/utils.py
# def sse_encode_event(event_type, data, event_id=None, escape=False, json_encode=True):
# if json_encode:
# data_str = json.dumps(data, cls=DjangoJSONEncoder)
# else:
# data_str = data
# if escape:
# event_type = build_id_escape(event_type)
# data_str = build_id_escape(data_str)
# out = 'event: %s\n' % event_type
# if event_id:
# out += 'id: %s\n' % event_id
# out += 'data: %s\n\n' % data_str
# return out
#
# def make_id(ids):
# id_parts = []
# for channel, id in six.iteritems(ids):
# enc_channel = quote(channel)
# id_parts.append('%s:%s' % (enc_channel, id))
# return ','.join(id_parts)
#
# def build_id_escape(s):
# out = ''
# for c in s:
# if c == '%':
# out += '%%'
# else:
# out += c
# return out
. Output only the next line. | event_id = make_id(last_ids) |
Given the code snippet: <|code_start|> 'user': user_id
}
params['es-meta'] = six.ensure_text(jwt.encode(es_meta,
settings.SECRET_KEY.encode('utf-8')))
next_uri = http_request.path + '?' + params.urlencode()
instruct = http_request.grip.start_instruct()
instruct.set_next_link(next_uri)
for channel in six.iterkeys(self.channel_items):
enc_channel = quote(channel)
last_id = last_ids.get(channel)
gc = Channel('events-%s' % enc_channel, prev_id=last_id)
if last_id:
gc.filters.append('build-id')
gc.filters.append('skip-users')
instruct.add_channel(gc)
gc = Channel('user-%s' % user_id)
gc.filters.append('require-sub')
instruct.add_channel(gc)
if not more:
instruct.set_hold_stream()
if len(last_ids) > 0:
id_parts = []
for channel in six.iterkeys(last_ids):
enc_channel = quote(channel)
<|code_end|>
, generate the next line using the imports in this file:
import copy
import time
import jwt
import six
from gripcontrol import Channel
from django.conf import settings
from django.http import HttpResponse
from .utils import sse_encode_event, make_id, build_id_escape
from urllib import quote
from urllib.parse import quote
and context (functions, classes, or occasionally code) from other files:
# Path: django_eventstream/utils.py
# def sse_encode_event(event_type, data, event_id=None, escape=False, json_encode=True):
# if json_encode:
# data_str = json.dumps(data, cls=DjangoJSONEncoder)
# else:
# data_str = data
# if escape:
# event_type = build_id_escape(event_type)
# data_str = build_id_escape(data_str)
# out = 'event: %s\n' % event_type
# if event_id:
# out += 'id: %s\n' % event_id
# out += 'data: %s\n\n' % data_str
# return out
#
# def make_id(ids):
# id_parts = []
# for channel, id in six.iteritems(ids):
# enc_channel = quote(channel)
# id_parts.append('%s:%s' % (enc_channel, id))
# return ','.join(id_parts)
#
# def build_id_escape(s):
# out = ''
# for c in s:
# if c == '%':
# out += '%%'
# else:
# out += c
# return out
. Output only the next line. | id_parts.append('%s:%%(events-%s)s' % (build_id_escape( |
Using the snippet: <|code_start|>
class TimeappConfig(AppConfig):
name = 'timeapp'
def ready(self):
ensure_worker_started()
worker_started = False
def ensure_worker_started():
global worker_started
if worker_started:
return
if not is_db_ready():
return
worker_started = True
thread = threading.Thread(target=send_worker)
thread.daemon = True
thread.start()
def send_worker():
while True:
data = datetime.datetime.utcnow().isoformat()
<|code_end|>
, determine the next line of code. You have imports:
import time
import datetime
import threading
from django.apps import AppConfig
from django_eventstream import send_event
from django.db import DatabaseError
from django_eventstream.models import Event
and context (class names, function names, or code) available:
# Path: django_eventstream/eventstream.py
# def send_event(channel, event_type, data, skip_user_ids=None, async_publish=True, json_encode=True):
# from .event import Event
#
# if skip_user_ids is None:
# skip_user_ids = []
#
# storage = get_storage()
# channelmanager = get_channelmanager()
#
# if channelmanager.is_channel_reliable(channel) and storage:
# e = storage.append_event(channel, event_type, data)
# pub_id = str(e.id)
# pub_prev_id = str(e.id - 1)
# else:
# e = Event(channel, event_type, data)
# pub_id = None
# pub_prev_id = None
#
# if have_channels():
# from .consumers import get_listener_manager
# # send to local listeners
# get_listener_manager().add_to_queues(channel, e)
#
# # publish through grip proxy
# publish_event(
# channel,
# event_type,
# data,
# pub_id,
# pub_prev_id,
# skip_user_ids=skip_user_ids,
# blocking=(not async_publish),
# json_encode=json_encode)
. Output only the next line. | send_event('time', 'message', data) |
Continue the code snippet: <|code_start|>
class TFParallelTest(test.SparkTest):
@classmethod
def setUpClass(cls):
super(TFParallelTest, cls).setUpClass()
@classmethod
def tearDownClass(cls):
super(TFParallelTest, cls).tearDownClass()
def test_basic_tf(self):
"""Single-node TF graph (w/ args) running independently on multiple executors."""
def _map_fun(args, ctx):
x = tf.constant(args['x'])
y = tf.constant(args['y'])
sum = tf.math.add(x, y)
assert sum.numpy() == 3
args = {'x': 1, 'y': 2}
<|code_end|>
. Use current file imports:
import unittest
import test
import tensorflow as tf
import tensorflow as tf
import tensorflow as tf
from tensorflowonspark import TFParallel
and context (classes, functions, or code) from other files:
# Path: tensorflowonspark/TFParallel.py
# def run(sc, map_fn, tf_args, num_executors, use_barrier=True):
# def _run(it):
. Output only the next line. | TFParallel.run(self.sc, _map_fun, tf_args=args, num_executors=self.num_workers, use_barrier=False) |
Given the following code snippet before the placeholder: <|code_start|> map_fn = TFSparkNode.run(self.default_fn, tf_args, self.cluster_meta, self.tensorboard, self.log_dir, self.queues, self.background)
map_fn([0])
@patch('tensorflowonspark.gpu_info.get_gpus')
@patch('tensorflowonspark.gpu_info.is_gpu_available')
def test_gpu_available(self, mock_available, mock_get_gpus):
"""Request available GPU"""
mock_available.return_value = True
mock_get_gpus.return_value = ['0']
self.parser.add_argument("--num_gpus", help="number of gpus to use", type=int)
tf_args = self.parser.parse_args(["--num_gpus", "1"])
map_fn = TFSparkNode.run(self.default_fn, tf_args, self.cluster_meta, self.tensorboard, self.log_dir, self.queues, self.background)
map_fn([0])
self.assertEqual(os.environ['CUDA_VISIBLE_DEVICES'], '0')
@patch('tensorflowonspark.gpu_info.get_gpus')
@patch('tensorflowonspark.gpu_info.is_gpu_available')
def test_gpu_default(self, mock_available, mock_get_gpus):
"""Default to one GPU if not explicitly requested"""
mock_available.return_value = True
mock_get_gpus.return_value = ['0']
tf_args = self.parser.parse_args([])
map_fn = TFSparkNode.run(self.default_fn, tf_args, self.cluster_meta, self.tensorboard, self.log_dir, self.queues, self.background)
map_fn([0])
self.assertEqual(os.environ['CUDA_VISIBLE_DEVICES'], '0')
<|code_end|>
, predict the next line using imports from the current file:
import argparse
import os
import random
import unittest
from tensorflowonspark import gpu_info, reservation, TFSparkNode
from unittest.mock import patch
and context including class names, function names, and sometimes code from other files:
# Path: tensorflowonspark/gpu_info.py
# MAX_RETRIES = 3 #: Maximum retries to allocate GPUs
# AS_STRING = 'string'
# AS_LIST = 'list'
# def is_gpu_available():
# def get_gpus(num_gpu=1, worker_index=-1, format=AS_STRING):
# def parse_gpu(gpu_str):
#
# Path: tensorflowonspark/reservation.py
# TFOS_SERVER_PORT = "TFOS_SERVER_PORT"
# TFOS_SERVER_HOST = "TFOS_SERVER_HOST"
# BUFSIZE = 1024
# MAX_RETRIES = 3
# CONNECTIONS = []
# class Reservations:
# class MessageSocket(object):
# class Server(MessageSocket):
# class Client(MessageSocket):
# def __init__(self, required):
# def add(self, meta):
# def done(self):
# def get(self):
# def remaining(self):
# def receive(self, sock):
# def send(self, sock, msg):
# def __init__(self, count):
# def await_reservations(self, sc, status={}, timeout=600):
# def _handle_message(self, sock, msg):
# def start(self):
# def _listen(self, sock):
# def get_server_ip(self):
# def get_server_ports(self):
# def start_listening_socket(self):
# def stop(self):
# def __init__(self, server_addr):
# def _request(self, msg_type, msg_data=None):
# def close(self):
# def register(self, reservation):
# def get_reservations(self):
# def await_reservations(self):
# def request_stop(self):
#
# Path: tensorflowonspark/TFSparkNode.py
# class TFSparkNode(object):
# """Low-level functions used by the high-level TFCluster APIs to manage cluster state.
#
# **This class is not intended for end-users (see TFNode for end-user APIs)**.
#
# For cluster management, this wraps the per-node cluster logic as Spark RDD mapPartitions functions, where the RDD is expected to be
# a "nodeRDD" of the form: ``nodeRDD = sc.parallelize(range(num_executors), num_executors)``.
#
# For data feeding, this wraps the feeding logic as Spark RDD mapPartitions functions on a standard "dataRDD".
#
# This also manages a reference to the TFManager "singleton" per executor. Since Spark can spawn more than one python-worker
# per executor, this will reconnect to the "singleton" instance as needed.
# """
# mgr = None #: TFManager instance
# cluster_id = None #: Unique ID for a given TensorFlowOnSpark cluster, used for invalidating state for new clusters.
. Output only the next line. | mock_get_gpus.assert_called_with(1, 0, format=gpu_info.AS_LIST) |
Given the code snippet: <|code_start|>
self.default_fn = lambda args, ctx: print("{}:{} args: {}".format(ctx.job_name, ctx.task_index, args))
self.job_name = 'chief'
self.task_index = 0
self.cluster_meta = {
'id': random.getrandbits(64),
'cluster_template': {self.job_name: [0]},
'num_executors': 1,
'default_fs': 'file://',
'working_dir': '.',
'server_addr': self.server_addr
}
self.tensorboard = False
self.log_dir = None
self.queues = ['input']
self.background = False
def tearDown(self):
client = reservation.Client(self.server_addr)
client.request_stop()
client.close()
def test_run(self):
"""Minimal function w/ args and ctx"""
def fn(args, ctx):
print("{}:{} args: {}".format(ctx.job_name, ctx.task_index, args))
self.assertEqual(ctx.job_name, self.job_name)
self.assertEqual(ctx.task_index, 0)
tf_args = self.parser.parse_args([])
<|code_end|>
, generate the next line using the imports in this file:
import argparse
import os
import random
import unittest
from tensorflowonspark import gpu_info, reservation, TFSparkNode
from unittest.mock import patch
and context (functions, classes, or occasionally code) from other files:
# Path: tensorflowonspark/gpu_info.py
# MAX_RETRIES = 3 #: Maximum retries to allocate GPUs
# AS_STRING = 'string'
# AS_LIST = 'list'
# def is_gpu_available():
# def get_gpus(num_gpu=1, worker_index=-1, format=AS_STRING):
# def parse_gpu(gpu_str):
#
# Path: tensorflowonspark/reservation.py
# TFOS_SERVER_PORT = "TFOS_SERVER_PORT"
# TFOS_SERVER_HOST = "TFOS_SERVER_HOST"
# BUFSIZE = 1024
# MAX_RETRIES = 3
# CONNECTIONS = []
# class Reservations:
# class MessageSocket(object):
# class Server(MessageSocket):
# class Client(MessageSocket):
# def __init__(self, required):
# def add(self, meta):
# def done(self):
# def get(self):
# def remaining(self):
# def receive(self, sock):
# def send(self, sock, msg):
# def __init__(self, count):
# def await_reservations(self, sc, status={}, timeout=600):
# def _handle_message(self, sock, msg):
# def start(self):
# def _listen(self, sock):
# def get_server_ip(self):
# def get_server_ports(self):
# def start_listening_socket(self):
# def stop(self):
# def __init__(self, server_addr):
# def _request(self, msg_type, msg_data=None):
# def close(self):
# def register(self, reservation):
# def get_reservations(self):
# def await_reservations(self):
# def request_stop(self):
#
# Path: tensorflowonspark/TFSparkNode.py
# class TFSparkNode(object):
# """Low-level functions used by the high-level TFCluster APIs to manage cluster state.
#
# **This class is not intended for end-users (see TFNode for end-user APIs)**.
#
# For cluster management, this wraps the per-node cluster logic as Spark RDD mapPartitions functions, where the RDD is expected to be
# a "nodeRDD" of the form: ``nodeRDD = sc.parallelize(range(num_executors), num_executors)``.
#
# For data feeding, this wraps the feeding logic as Spark RDD mapPartitions functions on a standard "dataRDD".
#
# This also manages a reference to the TFManager "singleton" per executor. Since Spark can spawn more than one python-worker
# per executor, this will reconnect to the "singleton" instance as needed.
# """
# mgr = None #: TFManager instance
# cluster_id = None #: Unique ID for a given TensorFlowOnSpark cluster, used for invalidating state for new clusters.
. Output only the next line. | map_fn = TFSparkNode.run(fn, tf_args, self.cluster_meta, self.tensorboard, self.log_dir, self.queues, self.background) |
Next line prediction: <|code_start|>
class TFNodeTest(unittest.TestCase):
def test_hdfs_path(self):
"""Normalization of absolution & relative string paths depending on filesystem"""
cwd = os.getcwd()
user = getpass.getuser()
fs = ["file://", "hdfs://", "viewfs://"]
paths = {
"hdfs://foo/bar": ["hdfs://foo/bar", "hdfs://foo/bar", "hdfs://foo/bar"],
"viewfs://foo/bar": ["viewfs://foo/bar", "viewfs://foo/bar", "viewfs://foo/bar"],
"file://foo/bar": ["file://foo/bar", "file://foo/bar", "file://foo/bar"],
"/foo/bar": ["file:///foo/bar", "hdfs:///foo/bar", "viewfs:///foo/bar"],
"foo/bar": ["file://{}/foo/bar".format(cwd), "hdfs:///user/{}/foo/bar".format(user), "viewfs:///user/{}/foo/bar".format(user)],
}
for i in range(len(fs)):
ctx = type('MockContext', (), {'defaultFS': fs[i], 'working_dir': cwd})
for path, expected in paths.items():
final_path = TFNode.hdfs_path(ctx, path)
self.assertEqual(final_path, expected[i], "fs({}) + path({}) => {}, expected {}".format(fs[i], path, final_path, expected[i]))
def test_datafeed(self):
"""TFNode.DataFeed basic operations"""
<|code_end|>
. Use current file imports:
(import getpass
import os
import unittest
from tensorflowonspark import TFManager, TFNode)
and context including class names, function names, or small code snippets from other files:
# Path: tensorflowonspark/TFManager.py
# class TFManager(BaseManager):
# """Python multiprocessing.Manager for distributed, multi-process communication."""
# pass
#
# Path: tensorflowonspark/TFNode.py
# TF_VERSION = pkg_resources.get_distribution('tensorflow').version
# HADOOP_SCHEMES = ['adl://',
# 'file://',
# 'hdfs://',
# 'oss://',
# 's3://',
# 's3a://',
# 's3n://',
# 'swift://',
# 'viewfs://',
# 'wasb://']
# def hdfs_path(ctx, path):
# def start_cluster_server(ctx, num_gpus=1, rdma=False):
# def next_batch(mgr, batch_size, qname='input'):
# def export_saved_model(sess, export_dir, tag_set, signatures):
# def release_port(ctx):
# def batch_results(mgr, results, qname='output'):
# def terminate(mgr, qname='input'):
# def __init__(self, mgr, train_mode=True, qname_in='input', qname_out='output', input_mapping=None):
# def next_batch(self, batch_size):
# def should_stop(self):
# def batch_results(self, results):
# def terminate(self):
# class DataFeed(object):
. Output only the next line. | mgr = TFManager.start('abc'.encode('utf-8'), ['input', 'output'], 'local') |
Given the following code snippet before the placeholder: <|code_start|>
class TFNodeTest(unittest.TestCase):
def test_hdfs_path(self):
"""Normalization of absolution & relative string paths depending on filesystem"""
cwd = os.getcwd()
user = getpass.getuser()
fs = ["file://", "hdfs://", "viewfs://"]
paths = {
"hdfs://foo/bar": ["hdfs://foo/bar", "hdfs://foo/bar", "hdfs://foo/bar"],
"viewfs://foo/bar": ["viewfs://foo/bar", "viewfs://foo/bar", "viewfs://foo/bar"],
"file://foo/bar": ["file://foo/bar", "file://foo/bar", "file://foo/bar"],
"/foo/bar": ["file:///foo/bar", "hdfs:///foo/bar", "viewfs:///foo/bar"],
"foo/bar": ["file://{}/foo/bar".format(cwd), "hdfs:///user/{}/foo/bar".format(user), "viewfs:///user/{}/foo/bar".format(user)],
}
for i in range(len(fs)):
ctx = type('MockContext', (), {'defaultFS': fs[i], 'working_dir': cwd})
for path, expected in paths.items():
<|code_end|>
, predict the next line using imports from the current file:
import getpass
import os
import unittest
from tensorflowonspark import TFManager, TFNode
and context including class names, function names, and sometimes code from other files:
# Path: tensorflowonspark/TFManager.py
# class TFManager(BaseManager):
# """Python multiprocessing.Manager for distributed, multi-process communication."""
# pass
#
# Path: tensorflowonspark/TFNode.py
# TF_VERSION = pkg_resources.get_distribution('tensorflow').version
# HADOOP_SCHEMES = ['adl://',
# 'file://',
# 'hdfs://',
# 'oss://',
# 's3://',
# 's3a://',
# 's3n://',
# 'swift://',
# 'viewfs://',
# 'wasb://']
# def hdfs_path(ctx, path):
# def start_cluster_server(ctx, num_gpus=1, rdma=False):
# def next_batch(mgr, batch_size, qname='input'):
# def export_saved_model(sess, export_dir, tag_set, signatures):
# def release_port(ctx):
# def batch_results(mgr, results, qname='output'):
# def terminate(mgr, qname='input'):
# def __init__(self, mgr, train_mode=True, qname_in='input', qname_out='output', input_mapping=None):
# def next_batch(self, batch_size):
# def should_stop(self):
# def batch_results(self, results):
# def terminate(self):
# class DataFeed(object):
. Output only the next line. | final_path = TFNode.hdfs_path(ctx, path) |
Using the snippet: <|code_start|>
class DFUtilTest(test.SparkTest):
@classmethod
def setUpClass(cls):
super(DFUtilTest, cls).setUpClass()
# define model_dir and export_dir for tests
cls.tfrecord_dir = os.getcwd() + os.sep + "test_tfr"
@classmethod
def tearDownClass(cls):
super(DFUtilTest, cls).tearDownClass()
def setUp(self):
super(DFUtilTest, self).setUp()
# remove any prior test artifacts
shutil.rmtree(self.tfrecord_dir, ignore_errors=True)
def tearDown(self):
# Note: don't clean up artifacts after test (in case we need to view/debug)
pass
def test_dfutils(self):
# create a DataFrame of a single row consisting of standard types (str, int, int_array, float, float_array, binary)
row1 = ('text string', 1, [2, 3, 4, 5], -1.1, [-2.2, -3.3, -4.4, -5.5], bytearray(b'\xff\xfe\xfd\xfc'))
rdd = self.sc.parallelize([row1])
df1 = self.spark.createDataFrame(rdd, ['a', 'b', 'c', 'd', 'e', 'f'])
print("schema: {}".format(df1.schema))
# save the DataFrame as TFRecords
<|code_end|>
, determine the next line of code. You have imports:
import os
import shutil
import test
import unittest
from tensorflowonspark import dfutil
and context (class names, function names, or code) available:
# Path: tensorflowonspark/dfutil.py
# def isLoadedDF(df):
# def saveAsTFRecords(df, output_dir):
# def loadTFRecords(sc, input_dir, binary_features=[]):
# def toTFExample(dtypes):
# def _toTFExample(iter):
# def _toTFFeature(name, dtype, row):
# def infer_schema(example, binary_features=[]):
# def _infer_sql_type(k, v):
# def fromTFExample(iter, binary_features=[]):
# def _get_value(k, v):
. Output only the next line. | dfutil.saveAsTFRecords(df1, self.tfrecord_dir) |
Next line prediction: <|code_start|># Copyright 2017 Yahoo Inc.
# Licensed under the terms of the Apache 2.0 license.
# Please see LICENSE file in the project root for terms.
"""
Simple utility to shutdown a Spark StreamingContext by signaling the reservation Server.
Note: use the reservation server address (host, port) reported in the driver logs.
"""
if __name__ == "__main__":
host = sys.argv[1]
port = int(sys.argv[2])
addr = (host, port)
<|code_end|>
. Use current file imports:
(from tensorflowonspark import reservation
import sys)
and context including class names, function names, or small code snippets from other files:
# Path: tensorflowonspark/reservation.py
# TFOS_SERVER_PORT = "TFOS_SERVER_PORT"
# TFOS_SERVER_HOST = "TFOS_SERVER_HOST"
# BUFSIZE = 1024
# MAX_RETRIES = 3
# CONNECTIONS = []
# class Reservations:
# class MessageSocket(object):
# class Server(MessageSocket):
# class Client(MessageSocket):
# def __init__(self, required):
# def add(self, meta):
# def done(self):
# def get(self):
# def remaining(self):
# def receive(self, sock):
# def send(self, sock, msg):
# def __init__(self, count):
# def await_reservations(self, sc, status={}, timeout=600):
# def _handle_message(self, sock, msg):
# def start(self):
# def _listen(self, sock):
# def get_server_ip(self):
# def get_server_ports(self):
# def start_listening_socket(self):
# def stop(self):
# def __init__(self, server_addr):
# def _request(self, msg_type, msg_data=None):
# def close(self):
# def register(self, reservation):
# def get_reservations(self):
# def await_reservations(self):
# def request_stop(self):
. Output only the next line. | client = reservation.Client(addr) |
Predict the next line for this snippet: <|code_start|>"""Start demo GUI for Spriteworld task configs.
To play a task, run this on the task config:
```bash
python run_demo.py --config=$path_to_task_config$
```
Be aware that this demo overrides the action space and renderer for ease of
playing, so those will be different from what are specified in the task config.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
FLAGS = flags.FLAGS
flags.DEFINE_string('config', 'spriteworld.configs.cobra.clustering',
'Module name of task config to use.')
flags.DEFINE_string('mode', 'train', 'Task mode, "train" or "test"]')
flags.DEFINE_boolean('task_hsv_colors', True,
'Whether the task config uses HSV as color factors.')
flags.DEFINE_integer('render_size', 256,
'Height and width of the output image.')
flags.DEFINE_integer('anti_aliasing', 10, 'Renderer anti-aliasing factor.')
def main(_):
config = importlib.import_module(FLAGS.config)
config = config.get_config(FLAGS.mode)
<|code_end|>
with the help of current file imports:
import importlib
from absl import app
from absl import flags
from spriteworld import demo_ui
and context from other files:
# Path: spriteworld/demo_ui.py
# class MatplotlibUI(object):
# class HumanDragAndDropAgent(object):
# class HumanEmbodiedAgent(object):
# def __init__(self):
# def ax_image(self):
# def _setup_callbacks(self):
# def _onkeypress(event):
# def _draw_observation(self, image, action):
# def _draw_rewards(self):
# def register_callback(self, event_name, callback):
# def update(self, timestep, action):
# def __init__(self, action_space, timeout=600):
# def help(self):
# def register_callbacks(self, ui):
# def _onclick(event):
# def begin_episode(self):
# def step(self, timestep):
# def _get_click():
# def _get_action():
# def __init__(self, action_space, timeout=600):
# def help(self):
# def register_callbacks(self, ui):
# def _onkeypress(event):
# def _onkeyrelease(event):
# def begin_episode(self):
# def step(self, timestep):
# def _wait_for_movement_key_press():
# def _get_action():
# def setup_run_ui(env_config, render_size, task_hsv_colors, anti_aliasing):
# MOTION_KEY_TO_ACTION = {
# 'up': 0,
# 'left': 1,
# 'down': 2,
# 'right': 3,
# 'w': 0,
# 'a': 1,
# 's': 2,
# 'd': 3
# }
, which may contain function names, class names, or code. Output only the next line. | demo_ui.setup_run_ui(config, FLAGS.render_size, FLAGS.task_hsv_colors, |
Given the code snippet: <|code_start|>#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
# python2 python3
"""Tests for shapes."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
class ShapesTest(parameterized.TestCase):
def _test_area(self, path):
im_size = 1000
path = im_size * path / 2 + im_size / 2
im = Image.new('RGB', (im_size, im_size))
draw = ImageDraw.Draw(im)
draw.polygon([tuple(p) for p in path], fill=(255, 255, 255))
desired_area = 0.25 * im_size * im_size * 3
true_area = np.sum(np.array(im) > 0)
self.assertAlmostEqual(desired_area / true_area, 1, delta=1e-2)
@parameterized.parameters(3, 4, 5, 6, 7, 8, 10)
def testPolygon(self, num_sides):
<|code_end|>
, generate the next line using the imports in this file:
from absl.testing import absltest
from absl.testing import parameterized
from PIL import Image
from PIL import ImageDraw
from spriteworld import shapes
import numpy as np
and context (functions, classes, or occasionally code) from other files:
# Path: spriteworld/shapes.py
# def _polar2cartesian(r, theta):
# def polygon(num_sides, theta_0=0.):
# def star(num_sides, point_height=1, theta_0=0.):
# def spokes(num_sides, spoke_height=1, theta_0=0.):
. Output only the next line. | path = shapes.polygon(num_sides) |
Predict the next line for this snippet: <|code_start|>Those sprites must be brought to the goal location, which is the center of the
arena. There are also distractor sprites, which are blue-purple-ish color and do
not contribute to the reward. In train mode there is 1 distractor, while in test
mode there are two.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
TERMINATE_DISTANCE = 0.075
NUM_TARGETS = 2
MODES_NUM_DISTRACTORS = {
'train': 1,
'test': 2,
}
def get_config(mode='train'):
"""Generate environment config.
Args:
mode: 'train' or 'test'.
Returns:
config: Dictionary defining task/environment configuration. Can be fed as
kwargs to environment.Environment.
"""
<|code_end|>
with the help of current file imports:
import os
from spriteworld import factor_distributions as distribs
from spriteworld import sprite_generators
from spriteworld import tasks
from spriteworld.configs.cobra import common
and context from other files:
# Path: spriteworld/factor_distributions.py
# _MAX_TRIES = int(1e5)
# class AbstractDistribution(object):
# class Continuous(AbstractDistribution):
# class Discrete(AbstractDistribution):
# class Mixture(AbstractDistribution):
# class Intersection(AbstractDistribution):
# class Product(AbstractDistribution):
# class SetMinus(AbstractDistribution):
# class Selection(AbstractDistribution):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def __str__(self):
# def _get_rng(self, rng=None):
# def keys(self):
# def __init__(self, key, minval, maxval, dtype='float32'):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, key, candidates, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, index_for_sampling=0):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, hold_out):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, filtering):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
#
# Path: spriteworld/sprite_generators.py
# def generate_sprites(factor_dist, num_sprites=1):
# def _generate():
# def chain_generators(*sprite_generators):
# def _generate():
# def sample_generator(sprite_generators, p=None):
# def _generate():
# def shuffle(sprite_generator):
# def _generate():
#
# Path: spriteworld/tasks.py
# class AbstractTask(object):
# class NoReward(AbstractTask):
# class FindGoalPosition(AbstractTask):
# class Clustering(AbstractTask):
# class MetaAggregated(AbstractTask):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self):
# def reward(self, unused_sprites):
# def success(self, unused_sprites):
# def __init__(self,
# filter_distrib=None,
# goal_position=(0.5, 0.5),
# terminate_distance=0.05,
# terminate_bonus=0.0,
# weights_dimensions=(1, 1),
# sparse_reward=False,
# raw_reward_multiplier=50):
# def _single_sprite_reward(self, sprite):
# def _filtered_sprites_rewards(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# cluster_distribs,
# termination_threshold=2.5,
# terminate_bonus=0.0,
# sparse_reward=False,
# reward_range=10):
# def _cluster_assignments(self, sprites):
# def _compute_clustering_metric(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# subtasks,
# reward_aggregator='sum',
# termination_criterion='all',
# terminate_bonus=0.0):
# def reward(self, sprites):
# def success(self, sprites):
# REWARD_AGGREGATOR = {
# 'sum': np.nansum,
# 'max': np.nanmax,
# 'min': np.nanmin,
# 'mean': np.nanmean
# }
# TERMINATION_CRITERION = {'all': np.all, 'any': np.any}
#
# Path: spriteworld/configs/cobra/common.py
# def action_space():
# def renderers():
, which may contain function names, class names, or code. Output only the next line. | shared_factors = distribs.Product([ |
Here is a snippet: <|code_start|>def get_config(mode='train'):
"""Generate environment config.
Args:
mode: 'train' or 'test'.
Returns:
config: Dictionary defining task/environment configuration. Can be fed as
kwargs to environment.Environment.
"""
shared_factors = distribs.Product([
distribs.Continuous('x', 0.1, 0.9),
distribs.Continuous('y', 0.1, 0.9),
distribs.Discrete('shape', ['square', 'triangle', 'circle']),
distribs.Discrete('scale', [0.13]),
distribs.Continuous('c1', 0.3, 1.),
distribs.Continuous('c2', 0.9, 1.),
])
target_hue = distribs.Continuous('c0', 0., 0.4)
distractor_hue = distribs.Continuous('c0', 0.5, 0.9)
target_factors = distribs.Product([
target_hue,
shared_factors,
])
distractor_factors = distribs.Product([
distractor_hue,
shared_factors,
])
<|code_end|>
. Write the next line using the current file imports:
import os
from spriteworld import factor_distributions as distribs
from spriteworld import sprite_generators
from spriteworld import tasks
from spriteworld.configs.cobra import common
and context from other files:
# Path: spriteworld/factor_distributions.py
# _MAX_TRIES = int(1e5)
# class AbstractDistribution(object):
# class Continuous(AbstractDistribution):
# class Discrete(AbstractDistribution):
# class Mixture(AbstractDistribution):
# class Intersection(AbstractDistribution):
# class Product(AbstractDistribution):
# class SetMinus(AbstractDistribution):
# class Selection(AbstractDistribution):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def __str__(self):
# def _get_rng(self, rng=None):
# def keys(self):
# def __init__(self, key, minval, maxval, dtype='float32'):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, key, candidates, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, index_for_sampling=0):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, hold_out):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, filtering):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
#
# Path: spriteworld/sprite_generators.py
# def generate_sprites(factor_dist, num_sprites=1):
# def _generate():
# def chain_generators(*sprite_generators):
# def _generate():
# def sample_generator(sprite_generators, p=None):
# def _generate():
# def shuffle(sprite_generator):
# def _generate():
#
# Path: spriteworld/tasks.py
# class AbstractTask(object):
# class NoReward(AbstractTask):
# class FindGoalPosition(AbstractTask):
# class Clustering(AbstractTask):
# class MetaAggregated(AbstractTask):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self):
# def reward(self, unused_sprites):
# def success(self, unused_sprites):
# def __init__(self,
# filter_distrib=None,
# goal_position=(0.5, 0.5),
# terminate_distance=0.05,
# terminate_bonus=0.0,
# weights_dimensions=(1, 1),
# sparse_reward=False,
# raw_reward_multiplier=50):
# def _single_sprite_reward(self, sprite):
# def _filtered_sprites_rewards(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# cluster_distribs,
# termination_threshold=2.5,
# terminate_bonus=0.0,
# sparse_reward=False,
# reward_range=10):
# def _cluster_assignments(self, sprites):
# def _compute_clustering_metric(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# subtasks,
# reward_aggregator='sum',
# termination_criterion='all',
# terminate_bonus=0.0):
# def reward(self, sprites):
# def success(self, sprites):
# REWARD_AGGREGATOR = {
# 'sum': np.nansum,
# 'max': np.nanmax,
# 'min': np.nanmin,
# 'mean': np.nanmean
# }
# TERMINATION_CRITERION = {'all': np.all, 'any': np.any}
#
# Path: spriteworld/configs/cobra/common.py
# def action_space():
# def renderers():
, which may include functions, classes, or code. Output only the next line. | target_sprite_gen = sprite_generators.generate_sprites( |
Predict the next line for this snippet: <|code_start|> """
shared_factors = distribs.Product([
distribs.Continuous('x', 0.1, 0.9),
distribs.Continuous('y', 0.1, 0.9),
distribs.Discrete('shape', ['square', 'triangle', 'circle']),
distribs.Discrete('scale', [0.13]),
distribs.Continuous('c1', 0.3, 1.),
distribs.Continuous('c2', 0.9, 1.),
])
target_hue = distribs.Continuous('c0', 0., 0.4)
distractor_hue = distribs.Continuous('c0', 0.5, 0.9)
target_factors = distribs.Product([
target_hue,
shared_factors,
])
distractor_factors = distribs.Product([
distractor_hue,
shared_factors,
])
target_sprite_gen = sprite_generators.generate_sprites(
target_factors, num_sprites=NUM_TARGETS)
distractor_sprite_gen = sprite_generators.generate_sprites(
distractor_factors, num_sprites=MODES_NUM_DISTRACTORS[mode])
sprite_gen = sprite_generators.chain_generators(target_sprite_gen,
distractor_sprite_gen)
# Randomize sprite ordering to eliminate any task information from occlusions
sprite_gen = sprite_generators.shuffle(sprite_gen)
<|code_end|>
with the help of current file imports:
import os
from spriteworld import factor_distributions as distribs
from spriteworld import sprite_generators
from spriteworld import tasks
from spriteworld.configs.cobra import common
and context from other files:
# Path: spriteworld/factor_distributions.py
# _MAX_TRIES = int(1e5)
# class AbstractDistribution(object):
# class Continuous(AbstractDistribution):
# class Discrete(AbstractDistribution):
# class Mixture(AbstractDistribution):
# class Intersection(AbstractDistribution):
# class Product(AbstractDistribution):
# class SetMinus(AbstractDistribution):
# class Selection(AbstractDistribution):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def __str__(self):
# def _get_rng(self, rng=None):
# def keys(self):
# def __init__(self, key, minval, maxval, dtype='float32'):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, key, candidates, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, index_for_sampling=0):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, hold_out):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, filtering):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
#
# Path: spriteworld/sprite_generators.py
# def generate_sprites(factor_dist, num_sprites=1):
# def _generate():
# def chain_generators(*sprite_generators):
# def _generate():
# def sample_generator(sprite_generators, p=None):
# def _generate():
# def shuffle(sprite_generator):
# def _generate():
#
# Path: spriteworld/tasks.py
# class AbstractTask(object):
# class NoReward(AbstractTask):
# class FindGoalPosition(AbstractTask):
# class Clustering(AbstractTask):
# class MetaAggregated(AbstractTask):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self):
# def reward(self, unused_sprites):
# def success(self, unused_sprites):
# def __init__(self,
# filter_distrib=None,
# goal_position=(0.5, 0.5),
# terminate_distance=0.05,
# terminate_bonus=0.0,
# weights_dimensions=(1, 1),
# sparse_reward=False,
# raw_reward_multiplier=50):
# def _single_sprite_reward(self, sprite):
# def _filtered_sprites_rewards(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# cluster_distribs,
# termination_threshold=2.5,
# terminate_bonus=0.0,
# sparse_reward=False,
# reward_range=10):
# def _cluster_assignments(self, sprites):
# def _compute_clustering_metric(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# subtasks,
# reward_aggregator='sum',
# termination_criterion='all',
# terminate_bonus=0.0):
# def reward(self, sprites):
# def success(self, sprites):
# REWARD_AGGREGATOR = {
# 'sum': np.nansum,
# 'max': np.nanmax,
# 'min': np.nanmin,
# 'mean': np.nanmean
# }
# TERMINATION_CRITERION = {'all': np.all, 'any': np.any}
#
# Path: spriteworld/configs/cobra/common.py
# def action_space():
# def renderers():
, which may contain function names, class names, or code. Output only the next line. | task = tasks.FindGoalPosition( |
Predict the next line for this snippet: <|code_start|> distribs.Discrete('shape', ['square', 'triangle', 'circle']),
distribs.Discrete('scale', [0.13]),
distribs.Continuous('c1', 0.3, 1.),
distribs.Continuous('c2', 0.9, 1.),
])
target_hue = distribs.Continuous('c0', 0., 0.4)
distractor_hue = distribs.Continuous('c0', 0.5, 0.9)
target_factors = distribs.Product([
target_hue,
shared_factors,
])
distractor_factors = distribs.Product([
distractor_hue,
shared_factors,
])
target_sprite_gen = sprite_generators.generate_sprites(
target_factors, num_sprites=NUM_TARGETS)
distractor_sprite_gen = sprite_generators.generate_sprites(
distractor_factors, num_sprites=MODES_NUM_DISTRACTORS[mode])
sprite_gen = sprite_generators.chain_generators(target_sprite_gen,
distractor_sprite_gen)
# Randomize sprite ordering to eliminate any task information from occlusions
sprite_gen = sprite_generators.shuffle(sprite_gen)
task = tasks.FindGoalPosition(
filter_distrib=target_hue, terminate_distance=TERMINATE_DISTANCE)
config = {
'task': task,
<|code_end|>
with the help of current file imports:
import os
from spriteworld import factor_distributions as distribs
from spriteworld import sprite_generators
from spriteworld import tasks
from spriteworld.configs.cobra import common
and context from other files:
# Path: spriteworld/factor_distributions.py
# _MAX_TRIES = int(1e5)
# class AbstractDistribution(object):
# class Continuous(AbstractDistribution):
# class Discrete(AbstractDistribution):
# class Mixture(AbstractDistribution):
# class Intersection(AbstractDistribution):
# class Product(AbstractDistribution):
# class SetMinus(AbstractDistribution):
# class Selection(AbstractDistribution):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def __str__(self):
# def _get_rng(self, rng=None):
# def keys(self):
# def __init__(self, key, minval, maxval, dtype='float32'):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, key, candidates, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, index_for_sampling=0):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, hold_out):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, filtering):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
#
# Path: spriteworld/sprite_generators.py
# def generate_sprites(factor_dist, num_sprites=1):
# def _generate():
# def chain_generators(*sprite_generators):
# def _generate():
# def sample_generator(sprite_generators, p=None):
# def _generate():
# def shuffle(sprite_generator):
# def _generate():
#
# Path: spriteworld/tasks.py
# class AbstractTask(object):
# class NoReward(AbstractTask):
# class FindGoalPosition(AbstractTask):
# class Clustering(AbstractTask):
# class MetaAggregated(AbstractTask):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self):
# def reward(self, unused_sprites):
# def success(self, unused_sprites):
# def __init__(self,
# filter_distrib=None,
# goal_position=(0.5, 0.5),
# terminate_distance=0.05,
# terminate_bonus=0.0,
# weights_dimensions=(1, 1),
# sparse_reward=False,
# raw_reward_multiplier=50):
# def _single_sprite_reward(self, sprite):
# def _filtered_sprites_rewards(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# cluster_distribs,
# termination_threshold=2.5,
# terminate_bonus=0.0,
# sparse_reward=False,
# reward_range=10):
# def _cluster_assignments(self, sprites):
# def _compute_clustering_metric(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# subtasks,
# reward_aggregator='sum',
# termination_criterion='all',
# terminate_bonus=0.0):
# def reward(self, sprites):
# def success(self, sprites):
# REWARD_AGGREGATOR = {
# 'sum': np.nansum,
# 'max': np.nanmax,
# 'min': np.nanmin,
# 'mean': np.nanmean
# }
# TERMINATION_CRITERION = {'all': np.all, 'any': np.any}
#
# Path: spriteworld/configs/cobra/common.py
# def action_space():
# def renderers():
, which may contain function names, class names, or code. Output only the next line. | 'action_space': common.action_space(), |
Given the code snippet: <|code_start|>there is one target, while in test mode there are two. All target sprites must
be brought to the goal location, which is the center of the arena. There are
always two distractor sprites, which are blue-purple-ish color and do not
contribute to the reward.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
TERMINATE_DISTANCE = 0.075
NUM_DISTRACTORS = 2
MODES_NUM_TARGETS = {
'train': 1,
'test': 2,
}
def get_config(mode='train'):
"""Generate environment config.
Args:
mode: 'train' or 'test'.
Returns:
config: Dictionary defining task/environment configuration. Can be fed as
kwargs to environment.Environment.
"""
<|code_end|>
, generate the next line using the imports in this file:
import os
from spriteworld import factor_distributions as distribs
from spriteworld import sprite_generators
from spriteworld import tasks
from spriteworld.configs.cobra import common
and context (functions, classes, or occasionally code) from other files:
# Path: spriteworld/factor_distributions.py
# _MAX_TRIES = int(1e5)
# class AbstractDistribution(object):
# class Continuous(AbstractDistribution):
# class Discrete(AbstractDistribution):
# class Mixture(AbstractDistribution):
# class Intersection(AbstractDistribution):
# class Product(AbstractDistribution):
# class SetMinus(AbstractDistribution):
# class Selection(AbstractDistribution):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def __str__(self):
# def _get_rng(self, rng=None):
# def keys(self):
# def __init__(self, key, minval, maxval, dtype='float32'):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, key, candidates, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, index_for_sampling=0):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, hold_out):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, filtering):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
#
# Path: spriteworld/sprite_generators.py
# def generate_sprites(factor_dist, num_sprites=1):
# def _generate():
# def chain_generators(*sprite_generators):
# def _generate():
# def sample_generator(sprite_generators, p=None):
# def _generate():
# def shuffle(sprite_generator):
# def _generate():
#
# Path: spriteworld/tasks.py
# class AbstractTask(object):
# class NoReward(AbstractTask):
# class FindGoalPosition(AbstractTask):
# class Clustering(AbstractTask):
# class MetaAggregated(AbstractTask):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self):
# def reward(self, unused_sprites):
# def success(self, unused_sprites):
# def __init__(self,
# filter_distrib=None,
# goal_position=(0.5, 0.5),
# terminate_distance=0.05,
# terminate_bonus=0.0,
# weights_dimensions=(1, 1),
# sparse_reward=False,
# raw_reward_multiplier=50):
# def _single_sprite_reward(self, sprite):
# def _filtered_sprites_rewards(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# cluster_distribs,
# termination_threshold=2.5,
# terminate_bonus=0.0,
# sparse_reward=False,
# reward_range=10):
# def _cluster_assignments(self, sprites):
# def _compute_clustering_metric(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# subtasks,
# reward_aggregator='sum',
# termination_criterion='all',
# terminate_bonus=0.0):
# def reward(self, sprites):
# def success(self, sprites):
# REWARD_AGGREGATOR = {
# 'sum': np.nansum,
# 'max': np.nanmax,
# 'min': np.nanmin,
# 'mean': np.nanmean
# }
# TERMINATION_CRITERION = {'all': np.all, 'any': np.any}
#
# Path: spriteworld/configs/cobra/common.py
# def action_space():
# def renderers():
. Output only the next line. | shared_factors = distribs.Product([ |
Given the following code snippet before the placeholder: <|code_start|>def get_config(mode='train'):
"""Generate environment config.
Args:
mode: 'train' or 'test'.
Returns:
config: Dictionary defining task/environment configuration. Can be fed as
kwargs to environment.Environment.
"""
shared_factors = distribs.Product([
distribs.Continuous('x', 0.1, 0.9),
distribs.Continuous('y', 0.1, 0.9),
distribs.Discrete('shape', ['square', 'triangle', 'circle']),
distribs.Discrete('scale', [0.13]),
distribs.Continuous('c1', 0.3, 1.),
distribs.Continuous('c2', 0.9, 1.),
])
target_hue = distribs.Continuous('c0', 0., 0.4)
distractor_hue = distribs.Continuous('c0', 0.5, 0.9)
target_factors = distribs.Product([
target_hue,
shared_factors,
])
distractor_factors = distribs.Product([
distractor_hue,
shared_factors,
])
<|code_end|>
, predict the next line using imports from the current file:
import os
from spriteworld import factor_distributions as distribs
from spriteworld import sprite_generators
from spriteworld import tasks
from spriteworld.configs.cobra import common
and context including class names, function names, and sometimes code from other files:
# Path: spriteworld/factor_distributions.py
# _MAX_TRIES = int(1e5)
# class AbstractDistribution(object):
# class Continuous(AbstractDistribution):
# class Discrete(AbstractDistribution):
# class Mixture(AbstractDistribution):
# class Intersection(AbstractDistribution):
# class Product(AbstractDistribution):
# class SetMinus(AbstractDistribution):
# class Selection(AbstractDistribution):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def __str__(self):
# def _get_rng(self, rng=None):
# def keys(self):
# def __init__(self, key, minval, maxval, dtype='float32'):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, key, candidates, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, index_for_sampling=0):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, hold_out):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, filtering):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
#
# Path: spriteworld/sprite_generators.py
# def generate_sprites(factor_dist, num_sprites=1):
# def _generate():
# def chain_generators(*sprite_generators):
# def _generate():
# def sample_generator(sprite_generators, p=None):
# def _generate():
# def shuffle(sprite_generator):
# def _generate():
#
# Path: spriteworld/tasks.py
# class AbstractTask(object):
# class NoReward(AbstractTask):
# class FindGoalPosition(AbstractTask):
# class Clustering(AbstractTask):
# class MetaAggregated(AbstractTask):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self):
# def reward(self, unused_sprites):
# def success(self, unused_sprites):
# def __init__(self,
# filter_distrib=None,
# goal_position=(0.5, 0.5),
# terminate_distance=0.05,
# terminate_bonus=0.0,
# weights_dimensions=(1, 1),
# sparse_reward=False,
# raw_reward_multiplier=50):
# def _single_sprite_reward(self, sprite):
# def _filtered_sprites_rewards(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# cluster_distribs,
# termination_threshold=2.5,
# terminate_bonus=0.0,
# sparse_reward=False,
# reward_range=10):
# def _cluster_assignments(self, sprites):
# def _compute_clustering_metric(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# subtasks,
# reward_aggregator='sum',
# termination_criterion='all',
# terminate_bonus=0.0):
# def reward(self, sprites):
# def success(self, sprites):
# REWARD_AGGREGATOR = {
# 'sum': np.nansum,
# 'max': np.nanmax,
# 'min': np.nanmin,
# 'mean': np.nanmean
# }
# TERMINATION_CRITERION = {'all': np.all, 'any': np.any}
#
# Path: spriteworld/configs/cobra/common.py
# def action_space():
# def renderers():
. Output only the next line. | target_sprite_gen = sprite_generators.generate_sprites( |
Given snippet: <|code_start|> """
shared_factors = distribs.Product([
distribs.Continuous('x', 0.1, 0.9),
distribs.Continuous('y', 0.1, 0.9),
distribs.Discrete('shape', ['square', 'triangle', 'circle']),
distribs.Discrete('scale', [0.13]),
distribs.Continuous('c1', 0.3, 1.),
distribs.Continuous('c2', 0.9, 1.),
])
target_hue = distribs.Continuous('c0', 0., 0.4)
distractor_hue = distribs.Continuous('c0', 0.5, 0.9)
target_factors = distribs.Product([
target_hue,
shared_factors,
])
distractor_factors = distribs.Product([
distractor_hue,
shared_factors,
])
target_sprite_gen = sprite_generators.generate_sprites(
target_factors, num_sprites=MODES_NUM_TARGETS[mode])
distractor_sprite_gen = sprite_generators.generate_sprites(
distractor_factors, num_sprites=NUM_DISTRACTORS)
sprite_gen = sprite_generators.chain_generators(target_sprite_gen,
distractor_sprite_gen)
# Randomize sprite ordering to eliminate any task information from occlusions
sprite_gen = sprite_generators.shuffle(sprite_gen)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
from spriteworld import factor_distributions as distribs
from spriteworld import sprite_generators
from spriteworld import tasks
from spriteworld.configs.cobra import common
and context:
# Path: spriteworld/factor_distributions.py
# _MAX_TRIES = int(1e5)
# class AbstractDistribution(object):
# class Continuous(AbstractDistribution):
# class Discrete(AbstractDistribution):
# class Mixture(AbstractDistribution):
# class Intersection(AbstractDistribution):
# class Product(AbstractDistribution):
# class SetMinus(AbstractDistribution):
# class Selection(AbstractDistribution):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def __str__(self):
# def _get_rng(self, rng=None):
# def keys(self):
# def __init__(self, key, minval, maxval, dtype='float32'):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, key, candidates, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, index_for_sampling=0):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, hold_out):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, filtering):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
#
# Path: spriteworld/sprite_generators.py
# def generate_sprites(factor_dist, num_sprites=1):
# def _generate():
# def chain_generators(*sprite_generators):
# def _generate():
# def sample_generator(sprite_generators, p=None):
# def _generate():
# def shuffle(sprite_generator):
# def _generate():
#
# Path: spriteworld/tasks.py
# class AbstractTask(object):
# class NoReward(AbstractTask):
# class FindGoalPosition(AbstractTask):
# class Clustering(AbstractTask):
# class MetaAggregated(AbstractTask):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self):
# def reward(self, unused_sprites):
# def success(self, unused_sprites):
# def __init__(self,
# filter_distrib=None,
# goal_position=(0.5, 0.5),
# terminate_distance=0.05,
# terminate_bonus=0.0,
# weights_dimensions=(1, 1),
# sparse_reward=False,
# raw_reward_multiplier=50):
# def _single_sprite_reward(self, sprite):
# def _filtered_sprites_rewards(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# cluster_distribs,
# termination_threshold=2.5,
# terminate_bonus=0.0,
# sparse_reward=False,
# reward_range=10):
# def _cluster_assignments(self, sprites):
# def _compute_clustering_metric(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# subtasks,
# reward_aggregator='sum',
# termination_criterion='all',
# terminate_bonus=0.0):
# def reward(self, sprites):
# def success(self, sprites):
# REWARD_AGGREGATOR = {
# 'sum': np.nansum,
# 'max': np.nanmax,
# 'min': np.nanmin,
# 'mean': np.nanmean
# }
# TERMINATION_CRITERION = {'all': np.all, 'any': np.any}
#
# Path: spriteworld/configs/cobra/common.py
# def action_space():
# def renderers():
which might include code, classes, or functions. Output only the next line. | task = tasks.FindGoalPosition( |
Continue the code snippet: <|code_start|> distribs.Discrete('shape', ['square', 'triangle', 'circle']),
distribs.Discrete('scale', [0.13]),
distribs.Continuous('c1', 0.3, 1.),
distribs.Continuous('c2', 0.9, 1.),
])
target_hue = distribs.Continuous('c0', 0., 0.4)
distractor_hue = distribs.Continuous('c0', 0.5, 0.9)
target_factors = distribs.Product([
target_hue,
shared_factors,
])
distractor_factors = distribs.Product([
distractor_hue,
shared_factors,
])
target_sprite_gen = sprite_generators.generate_sprites(
target_factors, num_sprites=MODES_NUM_TARGETS[mode])
distractor_sprite_gen = sprite_generators.generate_sprites(
distractor_factors, num_sprites=NUM_DISTRACTORS)
sprite_gen = sprite_generators.chain_generators(target_sprite_gen,
distractor_sprite_gen)
# Randomize sprite ordering to eliminate any task information from occlusions
sprite_gen = sprite_generators.shuffle(sprite_gen)
task = tasks.FindGoalPosition(
filter_distrib=target_hue, terminate_distance=TERMINATE_DISTANCE)
config = {
'task': task,
<|code_end|>
. Use current file imports:
import os
from spriteworld import factor_distributions as distribs
from spriteworld import sprite_generators
from spriteworld import tasks
from spriteworld.configs.cobra import common
and context (classes, functions, or code) from other files:
# Path: spriteworld/factor_distributions.py
# _MAX_TRIES = int(1e5)
# class AbstractDistribution(object):
# class Continuous(AbstractDistribution):
# class Discrete(AbstractDistribution):
# class Mixture(AbstractDistribution):
# class Intersection(AbstractDistribution):
# class Product(AbstractDistribution):
# class SetMinus(AbstractDistribution):
# class Selection(AbstractDistribution):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def __str__(self):
# def _get_rng(self, rng=None):
# def keys(self):
# def __init__(self, key, minval, maxval, dtype='float32'):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, key, candidates, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, probs=None):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components, index_for_sampling=0):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, components):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, hold_out):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
# def __init__(self, base, filtering):
# def sample(self, rng=None):
# def contains(self, spec):
# def to_str(self, indent):
# def keys(self):
#
# Path: spriteworld/sprite_generators.py
# def generate_sprites(factor_dist, num_sprites=1):
# def _generate():
# def chain_generators(*sprite_generators):
# def _generate():
# def sample_generator(sprite_generators, p=None):
# def _generate():
# def shuffle(sprite_generator):
# def _generate():
#
# Path: spriteworld/tasks.py
# class AbstractTask(object):
# class NoReward(AbstractTask):
# class FindGoalPosition(AbstractTask):
# class Clustering(AbstractTask):
# class MetaAggregated(AbstractTask):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self):
# def reward(self, unused_sprites):
# def success(self, unused_sprites):
# def __init__(self,
# filter_distrib=None,
# goal_position=(0.5, 0.5),
# terminate_distance=0.05,
# terminate_bonus=0.0,
# weights_dimensions=(1, 1),
# sparse_reward=False,
# raw_reward_multiplier=50):
# def _single_sprite_reward(self, sprite):
# def _filtered_sprites_rewards(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# cluster_distribs,
# termination_threshold=2.5,
# terminate_bonus=0.0,
# sparse_reward=False,
# reward_range=10):
# def _cluster_assignments(self, sprites):
# def _compute_clustering_metric(self, sprites):
# def reward(self, sprites):
# def success(self, sprites):
# def __init__(self,
# subtasks,
# reward_aggregator='sum',
# termination_criterion='all',
# terminate_bonus=0.0):
# def reward(self, sprites):
# def success(self, sprites):
# REWARD_AGGREGATOR = {
# 'sum': np.nansum,
# 'max': np.nanmax,
# 'min': np.nanmin,
# 'mean': np.nanmean
# }
# TERMINATION_CRITERION = {'all': np.all, 'any': np.any}
#
# Path: spriteworld/configs/cobra/common.py
# def action_space():
# def renderers():
. Output only the next line. | 'action_space': common.action_space(), |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.