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_secre... | 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(b... | 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 ... | 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... | '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 == Econom... | 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"... | 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 pla... | 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_scree... | 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 immediat... | 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.p... | 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.... | 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... | 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... | 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
... | 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_... | 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_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 = ... | 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.
... | 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_... | 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:
... | 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 = 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... | 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 ... | 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.... | 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 ... | 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, confi... | 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_c... | 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.o... | 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()])
... | 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... | 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.
sel... | 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):
''... | 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 pl... | 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 Vec... | 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):
'''
Th... | 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_... | 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_lo... | 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(... | 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 UserPlacement... | 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_pl... | 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 =... | 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_... | 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:
... | 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_... | 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()
i... | 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",
... | 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>')... | 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 = T... | 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 ver... | 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_LANGUAG... | '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, ... | 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... | 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.
"... | 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=Reque... | 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... | 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'],
... | 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 ho... | 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... | 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()
... | 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)
... | 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 PFEA... | 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 P... | 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]
... | 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... | 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', r... | 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... | 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.dum... | 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_en... | 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(['roo... | 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(['r... | 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://... | 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 = Htt... | 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/events... | 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 djan... | 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... | 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.dja... | 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',
'Inv... | 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_chann... | 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 =... | 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, h... | 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, h... | 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 i... | 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_star... | 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) r... | 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_... | 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_e... | 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... | 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://"]
... | 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)... | 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... | 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 differe... | 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 a... | 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.
"""
... | 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([
dis... | 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('... | 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 ... | '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__ impo... | 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_... | 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.),
dist... | 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.Co... | '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.