Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Predict the next line after this snippet: <|code_start|>
random_config = {
'discount': get_discount()
, 'N0': get_N0()
, 'min_eps': get_min_eps()
, 'initial_q_value': get_initial_q_value()
}
random_config.update(fixed_params)
return random_config
def build_graph(self, graph):
with graph.as_default():
tf.set_random_seed(self.random_seed)
self.inputs_plh = tf.placeholder(tf.int32, shape=[None], name="inputs_plh")
q_scope = tf.VariableScope(reuse=False, name='QValues')
with tf.variable_scope(q_scope):
self.Qs = tf.get_variable('Qs'
, shape=[self.nb_state, self.action_space.n]
, initializer=tf.constant_initializer(self.initial_q_value)
, dtype=tf.float32
)
tf.summary.histogram('Qarray', self.Qs)
self.q_preds_t = tf.gather(self.Qs, self.inputs_plh)
policy_scope = tf.VariableScope(reuse=False, name='Policy')
with tf.variable_scope(policy_scope):
if 'UCB' in self.config and self.config['UCB']:
<|code_end|>
using the current file's imports:
import numpy as np
import tensorflow as tf
from agents import TabularBasicAgent, capacities
and any relevant context from other files:
# Path: agents/capacities.py
# def swish(x):
# def eps_greedy(inputs_t, q_preds_t, nb_actions, N0, min_eps, nb_state=None):
# def tabular_eps_greedy(inputs_t, q_preds_t, nb_states, nb_actions, N0, min_eps):
# def tabular_UCB(Qs_t, inputs_t):
# def eligibility_traces(Qs_t, states_t, actions_t, discount, lambda_value):
# def eligibility_dutch_traces(Qs_t, states_t, actions_t, lr, discount, lambda_value):
# def get_expected_rewards(episode_rewards, discount=.99):
# def tf_get_n_step_expected_rewards(episode_rewards_t, estimates_t, discount, n_step):
# def get_n_step_expected_rewards(episode_rewards, estimates, discount=.99, n_step=1):
# def get_n_step_expected_rewards_mat(episode_rewards, estimates, discount=.99, n_step=1):
# def get_lambda_expected_rewards(episode_rewards, estimates, discount=.99, lambda_value=.9):
# def get_mc_target(rewards_t, discount):
# def get_td_target(Qs_t, rewards_t, next_states_t, next_actions_t, discount):
# def get_td_n_target(Qs_t, rewards_t, next_state_t, next_action_t, discount, n_step):
# def get_q_learning_target(Qs_t, rewards_t, next_states_t, discount):
# def get_expected_sarsa_target(Qs_t, rewards_t, next_states_t, next_probs_t, discount):
# def get_sigma_target(Qs_t, sigma, rewards_t, next_states_t, next_actions_t, next_probs_t, discount):
# def tabular_learning(Qs_t, states_t, actions_t, targets):
# def tabular_learning_with_lr(init_lr, decay_steps, Qs_t, states_t, actions_t, targets):
# def counter(name):
# def fix_scope(from_scope):
# def build_batches(dtKeys, sequence_history, batch_size):
# def policy(network_params, inputs, summary_collections=None):
# def value_f(network_params, inputs, summary_collections=None):
# def predictive_model(network_params, m_inputs, dynamic_batch_size, m_initial_state=None, summary_collections=None):
# def projection(proj_params, inputs, summary_collections=None):
# N = tf.Variable(1., trainable=False, dtype=tf.float32, name='N')
# N = tf.Variable(tf.ones(shape=[nb_state]), name='N', trainable=False)
# W1 = tf.get_variable('W1'
# , shape=[ network_params['nb_inputs'], network_params['nb_units'] ]
# , initializer=tf.random_normal_initializer(mean=network_params['initial_mean'], stddev=network_params['initial_stddev'])
# )
# W2 = tf.get_variable('W2'
# , shape=[ network_params['nb_units'], network_params['nb_units'] ]
# , initializer=tf.random_normal_initializer(mean=network_params['initial_mean'], stddev=network_params['initial_stddev'])
# )
# W3 = tf.get_variable('W3'
# , shape=[ network_params['nb_units'], network_params['nb_outputs'] ]
# , initializer=tf.random_normal_initializer(mean=network_params['initial_mean'], stddev=network_params['initial_stddev'])
# )
# W1 = tf.get_variable('W1'
# , shape=[ network_params['nb_inputs'], network_params['nb_units'] ]
# , initializer=w_init
# )
# W2 = tf.get_variable('W2'
# , shape=[ network_params['nb_units'], network_params['nb_units'] ]
# , initializer=w_init
# )
# W3 = tf.get_variable('W3'
# , shape=[ network_params['nb_units'], network_params['nb_outputs'] ]
# , initializer=w_init
# )
# W1 = tf.get_variable('W1'
# , shape=[ proj_params['nb_units'], proj_params['nb_units'] ]
# , initializer=w_init
# )
# W2 = tf.get_variable('W2'
# , shape=[ proj_params['nb_units'], proj_params['nb_actions'] ]
# , initializer=w_init
# )
#
# Path: agents/basic_agent.py
# class TabularBasicAgent(BasicAgent):
# """
# Agent implementing tabular Q-learning.
# """
# def __init__(self, config, env):
# if 'debug' in config:
# config.update(phis.getPhiConfig(config['env_name'], config['debug']))
# else:
# config.update(phis.getPhiConfig(config['env_name']))
# super(TabularBasicAgent, self).__init__(config, env)
. Output only the next line. | self.actions_t, self.probs_t = capacities.tabular_UCB( |
Given snippet: <|code_start|> 'lr': get_lr()
, 'lr_decay_steps': get_lr_decay_steps()
, 'discount': get_discount()
, 'N0': get_N0()
, 'min_eps': get_min_eps()
, 'initial_q_value': get_initial_q_value()
}
random_config.update(fixed_params)
return random_config
def build_graph(self, graph):
with graph.as_default():
tf.set_random_seed(self.random_seed)
self.inputs_plh = tf.placeholder(tf.int32, shape=[None], name="inputs_plh")
q_scope = tf.VariableScope(reuse=False, name='QValues')
with tf.variable_scope(q_scope):
self.Qs = tf.get_variable('Qs'
, shape=[self.nb_state, self.action_space.n]
, initializer=tf.constant_initializer(self.initial_q_value)
, dtype=tf.float32
)
tf.summary.histogram('Qarray', self.Qs)
self.q_preds_t = tf.gather(self.Qs, self.inputs_plh)
policy_scope = tf.VariableScope(reuse=False, name='Policy')
with tf.variable_scope(policy_scope):
if 'UCB' in self.config and self.config['UCB']:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import numpy as np
import tensorflow as tf
from agents import TabularBasicAgent, capacities
and context:
# Path: agents/capacities.py
# def swish(x):
# def eps_greedy(inputs_t, q_preds_t, nb_actions, N0, min_eps, nb_state=None):
# def tabular_eps_greedy(inputs_t, q_preds_t, nb_states, nb_actions, N0, min_eps):
# def tabular_UCB(Qs_t, inputs_t):
# def eligibility_traces(Qs_t, states_t, actions_t, discount, lambda_value):
# def eligibility_dutch_traces(Qs_t, states_t, actions_t, lr, discount, lambda_value):
# def get_expected_rewards(episode_rewards, discount=.99):
# def tf_get_n_step_expected_rewards(episode_rewards_t, estimates_t, discount, n_step):
# def get_n_step_expected_rewards(episode_rewards, estimates, discount=.99, n_step=1):
# def get_n_step_expected_rewards_mat(episode_rewards, estimates, discount=.99, n_step=1):
# def get_lambda_expected_rewards(episode_rewards, estimates, discount=.99, lambda_value=.9):
# def get_mc_target(rewards_t, discount):
# def get_td_target(Qs_t, rewards_t, next_states_t, next_actions_t, discount):
# def get_td_n_target(Qs_t, rewards_t, next_state_t, next_action_t, discount, n_step):
# def get_q_learning_target(Qs_t, rewards_t, next_states_t, discount):
# def get_expected_sarsa_target(Qs_t, rewards_t, next_states_t, next_probs_t, discount):
# def get_sigma_target(Qs_t, sigma, rewards_t, next_states_t, next_actions_t, next_probs_t, discount):
# def tabular_learning(Qs_t, states_t, actions_t, targets):
# def tabular_learning_with_lr(init_lr, decay_steps, Qs_t, states_t, actions_t, targets):
# def counter(name):
# def fix_scope(from_scope):
# def build_batches(dtKeys, sequence_history, batch_size):
# def policy(network_params, inputs, summary_collections=None):
# def value_f(network_params, inputs, summary_collections=None):
# def predictive_model(network_params, m_inputs, dynamic_batch_size, m_initial_state=None, summary_collections=None):
# def projection(proj_params, inputs, summary_collections=None):
# N = tf.Variable(1., trainable=False, dtype=tf.float32, name='N')
# N = tf.Variable(tf.ones(shape=[nb_state]), name='N', trainable=False)
# W1 = tf.get_variable('W1'
# , shape=[ network_params['nb_inputs'], network_params['nb_units'] ]
# , initializer=tf.random_normal_initializer(mean=network_params['initial_mean'], stddev=network_params['initial_stddev'])
# )
# W2 = tf.get_variable('W2'
# , shape=[ network_params['nb_units'], network_params['nb_units'] ]
# , initializer=tf.random_normal_initializer(mean=network_params['initial_mean'], stddev=network_params['initial_stddev'])
# )
# W3 = tf.get_variable('W3'
# , shape=[ network_params['nb_units'], network_params['nb_outputs'] ]
# , initializer=tf.random_normal_initializer(mean=network_params['initial_mean'], stddev=network_params['initial_stddev'])
# )
# W1 = tf.get_variable('W1'
# , shape=[ network_params['nb_inputs'], network_params['nb_units'] ]
# , initializer=w_init
# )
# W2 = tf.get_variable('W2'
# , shape=[ network_params['nb_units'], network_params['nb_units'] ]
# , initializer=w_init
# )
# W3 = tf.get_variable('W3'
# , shape=[ network_params['nb_units'], network_params['nb_outputs'] ]
# , initializer=w_init
# )
# W1 = tf.get_variable('W1'
# , shape=[ proj_params['nb_units'], proj_params['nb_units'] ]
# , initializer=w_init
# )
# W2 = tf.get_variable('W2'
# , shape=[ proj_params['nb_units'], proj_params['nb_actions'] ]
# , initializer=w_init
# )
#
# Path: agents/basic_agent.py
# class TabularBasicAgent(BasicAgent):
# """
# Agent implementing tabular Q-learning.
# """
# def __init__(self, config, env):
# if 'debug' in config:
# config.update(phis.getPhiConfig(config['env_name'], config['debug']))
# else:
# config.update(phis.getPhiConfig(config['env_name']))
# super(TabularBasicAgent, self).__init__(config, env)
which might include code, classes, or functions. Output only the next line. | self.actions_t, self.probs_t = capacities.tabular_UCB( |
Given the following code snippet before the placeholder: <|code_start|> 'lr': get_lr()
, 'lr_decay_steps': get_lr_decay_steps()
, 'discount': get_discount()
, 'N0': get_N0()
, 'min_eps': get_min_eps()
, 'initial_q_value': get_initial_q_value()
}
random_config.update(fixed_params)
return random_config
def build_graph(self, graph):
with graph.as_default():
tf.set_random_seed(self.random_seed)
self.inputs_plh = tf.placeholder(tf.int32, shape=[None], name="inputs_plh")
q_scope = tf.VariableScope(reuse=False, name='QValues')
with tf.variable_scope(q_scope):
self.Qs = tf.get_variable('Qs'
, shape=[self.nb_state, self.action_space.n]
, initializer=tf.constant_initializer(self.initial_q_value)
, dtype=tf.float32
)
tf.summary.histogram('Qarray', self.Qs)
self.q_preds_t = tf.gather(self.Qs, self.inputs_plh)
policy_scope = tf.VariableScope(reuse=False, name='Policy')
with tf.variable_scope(policy_scope):
if 'UCB' in self.config and self.config['UCB']:
<|code_end|>
, predict the next line using imports from the current file:
import numpy as np
import tensorflow as tf
from agents import TabularBasicAgent, capacities
and context including class names, function names, and sometimes code from other files:
# Path: agents/capacities.py
# def swish(x):
# def eps_greedy(inputs_t, q_preds_t, nb_actions, N0, min_eps, nb_state=None):
# def tabular_eps_greedy(inputs_t, q_preds_t, nb_states, nb_actions, N0, min_eps):
# def tabular_UCB(Qs_t, inputs_t):
# def eligibility_traces(Qs_t, states_t, actions_t, discount, lambda_value):
# def eligibility_dutch_traces(Qs_t, states_t, actions_t, lr, discount, lambda_value):
# def get_expected_rewards(episode_rewards, discount=.99):
# def tf_get_n_step_expected_rewards(episode_rewards_t, estimates_t, discount, n_step):
# def get_n_step_expected_rewards(episode_rewards, estimates, discount=.99, n_step=1):
# def get_n_step_expected_rewards_mat(episode_rewards, estimates, discount=.99, n_step=1):
# def get_lambda_expected_rewards(episode_rewards, estimates, discount=.99, lambda_value=.9):
# def get_mc_target(rewards_t, discount):
# def get_td_target(Qs_t, rewards_t, next_states_t, next_actions_t, discount):
# def get_td_n_target(Qs_t, rewards_t, next_state_t, next_action_t, discount, n_step):
# def get_q_learning_target(Qs_t, rewards_t, next_states_t, discount):
# def get_expected_sarsa_target(Qs_t, rewards_t, next_states_t, next_probs_t, discount):
# def get_sigma_target(Qs_t, sigma, rewards_t, next_states_t, next_actions_t, next_probs_t, discount):
# def tabular_learning(Qs_t, states_t, actions_t, targets):
# def tabular_learning_with_lr(init_lr, decay_steps, Qs_t, states_t, actions_t, targets):
# def counter(name):
# def fix_scope(from_scope):
# def build_batches(dtKeys, sequence_history, batch_size):
# def policy(network_params, inputs, summary_collections=None):
# def value_f(network_params, inputs, summary_collections=None):
# def predictive_model(network_params, m_inputs, dynamic_batch_size, m_initial_state=None, summary_collections=None):
# def projection(proj_params, inputs, summary_collections=None):
# N = tf.Variable(1., trainable=False, dtype=tf.float32, name='N')
# N = tf.Variable(tf.ones(shape=[nb_state]), name='N', trainable=False)
# W1 = tf.get_variable('W1'
# , shape=[ network_params['nb_inputs'], network_params['nb_units'] ]
# , initializer=tf.random_normal_initializer(mean=network_params['initial_mean'], stddev=network_params['initial_stddev'])
# )
# W2 = tf.get_variable('W2'
# , shape=[ network_params['nb_units'], network_params['nb_units'] ]
# , initializer=tf.random_normal_initializer(mean=network_params['initial_mean'], stddev=network_params['initial_stddev'])
# )
# W3 = tf.get_variable('W3'
# , shape=[ network_params['nb_units'], network_params['nb_outputs'] ]
# , initializer=tf.random_normal_initializer(mean=network_params['initial_mean'], stddev=network_params['initial_stddev'])
# )
# W1 = tf.get_variable('W1'
# , shape=[ network_params['nb_inputs'], network_params['nb_units'] ]
# , initializer=w_init
# )
# W2 = tf.get_variable('W2'
# , shape=[ network_params['nb_units'], network_params['nb_units'] ]
# , initializer=w_init
# )
# W3 = tf.get_variable('W3'
# , shape=[ network_params['nb_units'], network_params['nb_outputs'] ]
# , initializer=w_init
# )
# W1 = tf.get_variable('W1'
# , shape=[ proj_params['nb_units'], proj_params['nb_units'] ]
# , initializer=w_init
# )
# W2 = tf.get_variable('W2'
# , shape=[ proj_params['nb_units'], proj_params['nb_actions'] ]
# , initializer=w_init
# )
#
# Path: agents/basic_agent.py
# class TabularBasicAgent(BasicAgent):
# """
# Agent implementing tabular Q-learning.
# """
# def __init__(self, config, env):
# if 'debug' in config:
# config.update(phis.getPhiConfig(config['env_name'], config['debug']))
# else:
# config.update(phis.getPhiConfig(config['env_name']))
# super(TabularBasicAgent, self).__init__(config, env)
. Output only the next line. | self.actions_t, self.probs_t = capacities.tabular_UCB( |
Predict the next line after this snippet: <|code_start|> game.created_by = game.modified_by = self.request.user
game.save()
self._save_team_score(game, Team.RED, form.forms['team1'])
self._save_team_score(game, Team.BLUE, form.forms['team2'])
return redirect(self.get_success_url())
@staticmethod
def _save_team_score(game, side, form):
team = form.save(commit=False)
team.game = game
team.side = side
team.save()
form.save_m2m()
update_player_stats(team)
return team
class StatsView(LoginRequiredMixin, View):
"""
Given a `statistic` parameter, calls the stats function and returns the JSON configuration for Charts.js.
"""
def get(self, request, *args, **kwargs):
"""Using given `statistic`, return the result JSON."""
statistic = request.GET.get("statistic")
if not statistic:
return HttpResponseBadRequest()
# Call the stats function with request.GET parameters
<|code_end|>
using the current file's imports:
import inspect
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.urlresolvers import reverse_lazy
from django.db import transaction
from django.http.response import HttpResponseBadRequest, JsonResponse
from django.shortcuts import redirect
from django.views.generic import ListView, DetailView, FormView, View
from foosball.games import stats
from foosball.games.forms import GameForm
from foosball.games.stats import update_player_stats
from .models import Game, Team
and any relevant context from other files:
# Path: foosball/games/stats.py
# def update_player_stats(instance):
# def stats_red_or_blue(params):
# def stats_players(params):
#
# Path: foosball/games/forms.py
# class GameForm(SuperForm):
# game = ModelFormField(GameModelForm)
# team1 = ModelFormField(TeamModelForm)
# team2 = ModelFormField(TeamModelForm)
#
# def is_valid(self):
# return super().is_valid() & clean_team_forms(self.forms['team1'], self.forms['team2'])
#
# Path: foosball/games/stats.py
# def update_player_stats(instance):
# """
# Update player win and played counts for players of a Team.
#
# :param instance: Team that will be used to update players.
# :type instance: Team
# """
# for user in instance.players.all():
# totals = {1: 0, 2: 0}
# wins = {1: 0, 2: 0}
# teams = Team.objects.filter(players__id=user.id).prefetch_related("players")
# for team in teams:
# player_count = len(team.players.all())
# totals[player_count] += 1
# if team.score == 10:
# wins[player_count] += 1
# player, _created = Player.objects.get_or_create(user=user)
# player.singles_wins = wins[1]
# player.doubles_wins = wins[2]
# player.singles_played = totals[1]
# player.doubles_played = totals[2]
# if totals[1]:
# player.singles_win_percentage = round((wins[1]/totals[1])*100, 2)
# else:
# player.singles_win_percentage = 0
# if totals[2]:
# player.doubles_win_percentage = round((wins[2] / totals[2])*100, 2)
# else:
# player.doubles_win_percentage = 0
# player.total_played = totals[1] + totals[2]
# player.save()
#
# Path: foosball/games/models.py
# class Game(TimeStampedModel):
# created_by = models.ForeignKey(
# User, related_name="games_created", editable=False, null=True, verbose_name=_("created by")
# )
# modified_by = models.ForeignKey(
# User, related_name="games_modified", editable=False, null=True, verbose_name=_("modified by")
# )
#
# played_at = models.DateTimeField(
# default=timezone.now,
# verbose_name=_("played at"),
# help_text=_("Time when the game was played")
# )
#
# table = models.ForeignKey(Table, blank=True, null=True, related_name="games", verbose_name=_("table"))
#
# class Meta:
# ordering = ['-played_at']
#
# def __str__(self):
# return " - ".join(map(str, self.teams.all()))
#
# class Team(models.Model):
# UNKNOWN = 0
# RED = 1
# BLUE = 2
# SIDE_CHOICES = (
# (UNKNOWN, _("Unknown")),
# (RED, _("Red")),
# (BLUE, _("Blue")),
# )
# side = models.IntegerField(db_index=True, choices=SIDE_CHOICES, default=UNKNOWN, verbose_name=_("side"))
#
# game = models.ForeignKey(Game, related_name="teams", on_delete=models.CASCADE)
# score = models.PositiveSmallIntegerField(
# verbose_name=_("score"),
# help_text=_("Team's score in the game"),
# validators=[MaxValueValidator(limit_value=10)]
# )
# players = models.ManyToManyField(User)
#
# def __str__(self):
# return "%s (%s)" % (
# self.score,
# ", ".join(map(str, self.players.all()))
# )
. Output only the next line. | stats_func = getattr(stats, "stats_%s" % statistic, None) |
Given snippet: <|code_start|>
class GameListView(LoginRequiredMixin, ListView):
model = Game
paginate_by = 10
template_name = "games/game_list.jinja"
class GameDetailView(LoginRequiredMixin, DetailView):
model = Game
template_name = "games/game_detail.jinja"
class GameCreateView(LoginRequiredMixin, FormView):
template_name = "games/game_new.jinja"
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import inspect
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.urlresolvers import reverse_lazy
from django.db import transaction
from django.http.response import HttpResponseBadRequest, JsonResponse
from django.shortcuts import redirect
from django.views.generic import ListView, DetailView, FormView, View
from foosball.games import stats
from foosball.games.forms import GameForm
from foosball.games.stats import update_player_stats
from .models import Game, Team
and context:
# Path: foosball/games/stats.py
# def update_player_stats(instance):
# def stats_red_or_blue(params):
# def stats_players(params):
#
# Path: foosball/games/forms.py
# class GameForm(SuperForm):
# game = ModelFormField(GameModelForm)
# team1 = ModelFormField(TeamModelForm)
# team2 = ModelFormField(TeamModelForm)
#
# def is_valid(self):
# return super().is_valid() & clean_team_forms(self.forms['team1'], self.forms['team2'])
#
# Path: foosball/games/stats.py
# def update_player_stats(instance):
# """
# Update player win and played counts for players of a Team.
#
# :param instance: Team that will be used to update players.
# :type instance: Team
# """
# for user in instance.players.all():
# totals = {1: 0, 2: 0}
# wins = {1: 0, 2: 0}
# teams = Team.objects.filter(players__id=user.id).prefetch_related("players")
# for team in teams:
# player_count = len(team.players.all())
# totals[player_count] += 1
# if team.score == 10:
# wins[player_count] += 1
# player, _created = Player.objects.get_or_create(user=user)
# player.singles_wins = wins[1]
# player.doubles_wins = wins[2]
# player.singles_played = totals[1]
# player.doubles_played = totals[2]
# if totals[1]:
# player.singles_win_percentage = round((wins[1]/totals[1])*100, 2)
# else:
# player.singles_win_percentage = 0
# if totals[2]:
# player.doubles_win_percentage = round((wins[2] / totals[2])*100, 2)
# else:
# player.doubles_win_percentage = 0
# player.total_played = totals[1] + totals[2]
# player.save()
#
# Path: foosball/games/models.py
# class Game(TimeStampedModel):
# created_by = models.ForeignKey(
# User, related_name="games_created", editable=False, null=True, verbose_name=_("created by")
# )
# modified_by = models.ForeignKey(
# User, related_name="games_modified", editable=False, null=True, verbose_name=_("modified by")
# )
#
# played_at = models.DateTimeField(
# default=timezone.now,
# verbose_name=_("played at"),
# help_text=_("Time when the game was played")
# )
#
# table = models.ForeignKey(Table, blank=True, null=True, related_name="games", verbose_name=_("table"))
#
# class Meta:
# ordering = ['-played_at']
#
# def __str__(self):
# return " - ".join(map(str, self.teams.all()))
#
# class Team(models.Model):
# UNKNOWN = 0
# RED = 1
# BLUE = 2
# SIDE_CHOICES = (
# (UNKNOWN, _("Unknown")),
# (RED, _("Red")),
# (BLUE, _("Blue")),
# )
# side = models.IntegerField(db_index=True, choices=SIDE_CHOICES, default=UNKNOWN, verbose_name=_("side"))
#
# game = models.ForeignKey(Game, related_name="teams", on_delete=models.CASCADE)
# score = models.PositiveSmallIntegerField(
# verbose_name=_("score"),
# help_text=_("Team's score in the game"),
# validators=[MaxValueValidator(limit_value=10)]
# )
# players = models.ManyToManyField(User)
#
# def __str__(self):
# return "%s (%s)" % (
# self.score,
# ", ".join(map(str, self.players.all()))
# )
which might include code, classes, or functions. Output only the next line. | form_class = GameForm |
Predict the next line for this snippet: <|code_start|>
class GameDetailView(LoginRequiredMixin, DetailView):
model = Game
template_name = "games/game_detail.jinja"
class GameCreateView(LoginRequiredMixin, FormView):
template_name = "games/game_new.jinja"
form_class = GameForm
success_url = reverse_lazy("games:index")
@transaction.atomic
def form_valid(self, form):
game = form.forms['game'].save(commit=False)
game.created_by = game.modified_by = self.request.user
game.save()
self._save_team_score(game, Team.RED, form.forms['team1'])
self._save_team_score(game, Team.BLUE, form.forms['team2'])
return redirect(self.get_success_url())
@staticmethod
def _save_team_score(game, side, form):
team = form.save(commit=False)
team.game = game
team.side = side
team.save()
form.save_m2m()
<|code_end|>
with the help of current file imports:
import inspect
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.urlresolvers import reverse_lazy
from django.db import transaction
from django.http.response import HttpResponseBadRequest, JsonResponse
from django.shortcuts import redirect
from django.views.generic import ListView, DetailView, FormView, View
from foosball.games import stats
from foosball.games.forms import GameForm
from foosball.games.stats import update_player_stats
from .models import Game, Team
and context from other files:
# Path: foosball/games/stats.py
# def update_player_stats(instance):
# def stats_red_or_blue(params):
# def stats_players(params):
#
# Path: foosball/games/forms.py
# class GameForm(SuperForm):
# game = ModelFormField(GameModelForm)
# team1 = ModelFormField(TeamModelForm)
# team2 = ModelFormField(TeamModelForm)
#
# def is_valid(self):
# return super().is_valid() & clean_team_forms(self.forms['team1'], self.forms['team2'])
#
# Path: foosball/games/stats.py
# def update_player_stats(instance):
# """
# Update player win and played counts for players of a Team.
#
# :param instance: Team that will be used to update players.
# :type instance: Team
# """
# for user in instance.players.all():
# totals = {1: 0, 2: 0}
# wins = {1: 0, 2: 0}
# teams = Team.objects.filter(players__id=user.id).prefetch_related("players")
# for team in teams:
# player_count = len(team.players.all())
# totals[player_count] += 1
# if team.score == 10:
# wins[player_count] += 1
# player, _created = Player.objects.get_or_create(user=user)
# player.singles_wins = wins[1]
# player.doubles_wins = wins[2]
# player.singles_played = totals[1]
# player.doubles_played = totals[2]
# if totals[1]:
# player.singles_win_percentage = round((wins[1]/totals[1])*100, 2)
# else:
# player.singles_win_percentage = 0
# if totals[2]:
# player.doubles_win_percentage = round((wins[2] / totals[2])*100, 2)
# else:
# player.doubles_win_percentage = 0
# player.total_played = totals[1] + totals[2]
# player.save()
#
# Path: foosball/games/models.py
# class Game(TimeStampedModel):
# created_by = models.ForeignKey(
# User, related_name="games_created", editable=False, null=True, verbose_name=_("created by")
# )
# modified_by = models.ForeignKey(
# User, related_name="games_modified", editable=False, null=True, verbose_name=_("modified by")
# )
#
# played_at = models.DateTimeField(
# default=timezone.now,
# verbose_name=_("played at"),
# help_text=_("Time when the game was played")
# )
#
# table = models.ForeignKey(Table, blank=True, null=True, related_name="games", verbose_name=_("table"))
#
# class Meta:
# ordering = ['-played_at']
#
# def __str__(self):
# return " - ".join(map(str, self.teams.all()))
#
# class Team(models.Model):
# UNKNOWN = 0
# RED = 1
# BLUE = 2
# SIDE_CHOICES = (
# (UNKNOWN, _("Unknown")),
# (RED, _("Red")),
# (BLUE, _("Blue")),
# )
# side = models.IntegerField(db_index=True, choices=SIDE_CHOICES, default=UNKNOWN, verbose_name=_("side"))
#
# game = models.ForeignKey(Game, related_name="teams", on_delete=models.CASCADE)
# score = models.PositiveSmallIntegerField(
# verbose_name=_("score"),
# help_text=_("Team's score in the game"),
# validators=[MaxValueValidator(limit_value=10)]
# )
# players = models.ManyToManyField(User)
#
# def __str__(self):
# return "%s (%s)" % (
# self.score,
# ", ".join(map(str, self.players.all()))
# )
, which may contain function names, class names, or code. Output only the next line. | update_player_stats(team) |
Continue the code snippet: <|code_start|>
class GameListView(LoginRequiredMixin, ListView):
model = Game
paginate_by = 10
template_name = "games/game_list.jinja"
class GameDetailView(LoginRequiredMixin, DetailView):
model = Game
template_name = "games/game_detail.jinja"
class GameCreateView(LoginRequiredMixin, FormView):
template_name = "games/game_new.jinja"
form_class = GameForm
success_url = reverse_lazy("games:index")
@transaction.atomic
def form_valid(self, form):
game = form.forms['game'].save(commit=False)
game.created_by = game.modified_by = self.request.user
game.save()
<|code_end|>
. Use current file imports:
import inspect
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.urlresolvers import reverse_lazy
from django.db import transaction
from django.http.response import HttpResponseBadRequest, JsonResponse
from django.shortcuts import redirect
from django.views.generic import ListView, DetailView, FormView, View
from foosball.games import stats
from foosball.games.forms import GameForm
from foosball.games.stats import update_player_stats
from .models import Game, Team
and context (classes, functions, or code) from other files:
# Path: foosball/games/stats.py
# def update_player_stats(instance):
# def stats_red_or_blue(params):
# def stats_players(params):
#
# Path: foosball/games/forms.py
# class GameForm(SuperForm):
# game = ModelFormField(GameModelForm)
# team1 = ModelFormField(TeamModelForm)
# team2 = ModelFormField(TeamModelForm)
#
# def is_valid(self):
# return super().is_valid() & clean_team_forms(self.forms['team1'], self.forms['team2'])
#
# Path: foosball/games/stats.py
# def update_player_stats(instance):
# """
# Update player win and played counts for players of a Team.
#
# :param instance: Team that will be used to update players.
# :type instance: Team
# """
# for user in instance.players.all():
# totals = {1: 0, 2: 0}
# wins = {1: 0, 2: 0}
# teams = Team.objects.filter(players__id=user.id).prefetch_related("players")
# for team in teams:
# player_count = len(team.players.all())
# totals[player_count] += 1
# if team.score == 10:
# wins[player_count] += 1
# player, _created = Player.objects.get_or_create(user=user)
# player.singles_wins = wins[1]
# player.doubles_wins = wins[2]
# player.singles_played = totals[1]
# player.doubles_played = totals[2]
# if totals[1]:
# player.singles_win_percentage = round((wins[1]/totals[1])*100, 2)
# else:
# player.singles_win_percentage = 0
# if totals[2]:
# player.doubles_win_percentage = round((wins[2] / totals[2])*100, 2)
# else:
# player.doubles_win_percentage = 0
# player.total_played = totals[1] + totals[2]
# player.save()
#
# Path: foosball/games/models.py
# class Game(TimeStampedModel):
# created_by = models.ForeignKey(
# User, related_name="games_created", editable=False, null=True, verbose_name=_("created by")
# )
# modified_by = models.ForeignKey(
# User, related_name="games_modified", editable=False, null=True, verbose_name=_("modified by")
# )
#
# played_at = models.DateTimeField(
# default=timezone.now,
# verbose_name=_("played at"),
# help_text=_("Time when the game was played")
# )
#
# table = models.ForeignKey(Table, blank=True, null=True, related_name="games", verbose_name=_("table"))
#
# class Meta:
# ordering = ['-played_at']
#
# def __str__(self):
# return " - ".join(map(str, self.teams.all()))
#
# class Team(models.Model):
# UNKNOWN = 0
# RED = 1
# BLUE = 2
# SIDE_CHOICES = (
# (UNKNOWN, _("Unknown")),
# (RED, _("Red")),
# (BLUE, _("Blue")),
# )
# side = models.IntegerField(db_index=True, choices=SIDE_CHOICES, default=UNKNOWN, verbose_name=_("side"))
#
# game = models.ForeignKey(Game, related_name="teams", on_delete=models.CASCADE)
# score = models.PositiveSmallIntegerField(
# verbose_name=_("score"),
# help_text=_("Team's score in the game"),
# validators=[MaxValueValidator(limit_value=10)]
# )
# players = models.ManyToManyField(User)
#
# def __str__(self):
# return "%s (%s)" % (
# self.score,
# ", ".join(map(str, self.players.all()))
# )
. Output only the next line. | self._save_team_score(game, Team.RED, form.forms['team1']) |
Here is a snippet: <|code_start|> for user in instance.players.all():
totals = {1: 0, 2: 0}
wins = {1: 0, 2: 0}
teams = Team.objects.filter(players__id=user.id).prefetch_related("players")
for team in teams:
player_count = len(team.players.all())
totals[player_count] += 1
if team.score == 10:
wins[player_count] += 1
player, _created = Player.objects.get_or_create(user=user)
player.singles_wins = wins[1]
player.doubles_wins = wins[2]
player.singles_played = totals[1]
player.doubles_played = totals[2]
if totals[1]:
player.singles_win_percentage = round((wins[1]/totals[1])*100, 2)
else:
player.singles_win_percentage = 0
if totals[2]:
player.doubles_win_percentage = round((wins[2] / totals[2])*100, 2)
else:
player.doubles_win_percentage = 0
player.total_played = totals[1] + totals[2]
player.save()
def stats_red_or_blue(params):
"""
Return statistics on the most important question.
"""
<|code_end|>
. Write the next line using the current file imports:
from foosball.games.models import Game, Team, Player
and context from other files:
# Path: foosball/games/models.py
# class Game(TimeStampedModel):
# created_by = models.ForeignKey(
# User, related_name="games_created", editable=False, null=True, verbose_name=_("created by")
# )
# modified_by = models.ForeignKey(
# User, related_name="games_modified", editable=False, null=True, verbose_name=_("modified by")
# )
#
# played_at = models.DateTimeField(
# default=timezone.now,
# verbose_name=_("played at"),
# help_text=_("Time when the game was played")
# )
#
# table = models.ForeignKey(Table, blank=True, null=True, related_name="games", verbose_name=_("table"))
#
# class Meta:
# ordering = ['-played_at']
#
# def __str__(self):
# return " - ".join(map(str, self.teams.all()))
#
# class Team(models.Model):
# UNKNOWN = 0
# RED = 1
# BLUE = 2
# SIDE_CHOICES = (
# (UNKNOWN, _("Unknown")),
# (RED, _("Red")),
# (BLUE, _("Blue")),
# )
# side = models.IntegerField(db_index=True, choices=SIDE_CHOICES, default=UNKNOWN, verbose_name=_("side"))
#
# game = models.ForeignKey(Game, related_name="teams", on_delete=models.CASCADE)
# score = models.PositiveSmallIntegerField(
# verbose_name=_("score"),
# help_text=_("Team's score in the game"),
# validators=[MaxValueValidator(limit_value=10)]
# )
# players = models.ManyToManyField(User)
#
# def __str__(self):
# return "%s (%s)" % (
# self.score,
# ", ".join(map(str, self.players.all()))
# )
#
# class Player(models.Model):
# user = models.OneToOneField(User)
# singles_wins = models.PositiveIntegerField(
# verbose_name=_("wins - singles"),
# help_text=_("Wins in a single player team"),
# default=0
# )
# singles_win_percentage = models.DecimalField(
# verbose_name=_("win percentage - singles"),
# help_text=_("Win percentage for single player team games"),
# default=0,
# max_digits=5, decimal_places=2,
# validators=[MinValueValidator(limit_value=0), MaxValueValidator(limit_value=100)]
# )
# doubles_wins = models.PositiveIntegerField(
# verbose_name=_("wins - doubles"),
# help_text=_("Wins in a two player team"),
# default=0
# )
# doubles_win_percentage = models.DecimalField(
# verbose_name=_("win percentage - doubles"),
# help_text=_("Win percentage in two player team games"),
# default=0,
# max_digits=5, decimal_places=2,
# validators=[MinValueValidator(limit_value=0), MaxValueValidator(limit_value=100)]
# )
# total_played = models.PositiveIntegerField(
# verbose_name=_("total played"),
# help_text=_("Total games played in"),
# default=0
# )
# singles_played = models.PositiveIntegerField(
# verbose_name=_("singles played"),
# help_text=_("Total games played as a single player team"),
# default=0
# )
# doubles_played = models.PositiveIntegerField(
# verbose_name=_("doubles played"),
# help_text=_("Total games played in a two player team"),
# default=0
# )
# colour = models.CharField(
# verbose_name=_("colour code"),
# help_text=_("Player colour as a hex colour code"),
# max_length=7, null=True
# )
#
# def __str__(self):
# return "Player %s" % self.user.name if self.user.name else self.user.username
#
# def save(self, *args, **kwargs):
# """
# Init some data for the player.
# """
# if not self.pk or not self.colour:
# self.colour = random_colour()
# return super(Player, self).save(*args, **kwargs)
, which may include functions, classes, or code. Output only the next line. | red_wins = Game.objects.filter(teams__side=Team.RED, teams__score=10).count() |
Next line prediction: <|code_start|>
def update_player_stats(instance):
"""
Update player win and played counts for players of a Team.
:param instance: Team that will be used to update players.
:type instance: Team
"""
for user in instance.players.all():
totals = {1: 0, 2: 0}
wins = {1: 0, 2: 0}
<|code_end|>
. Use current file imports:
(from foosball.games.models import Game, Team, Player)
and context including class names, function names, or small code snippets from other files:
# Path: foosball/games/models.py
# class Game(TimeStampedModel):
# created_by = models.ForeignKey(
# User, related_name="games_created", editable=False, null=True, verbose_name=_("created by")
# )
# modified_by = models.ForeignKey(
# User, related_name="games_modified", editable=False, null=True, verbose_name=_("modified by")
# )
#
# played_at = models.DateTimeField(
# default=timezone.now,
# verbose_name=_("played at"),
# help_text=_("Time when the game was played")
# )
#
# table = models.ForeignKey(Table, blank=True, null=True, related_name="games", verbose_name=_("table"))
#
# class Meta:
# ordering = ['-played_at']
#
# def __str__(self):
# return " - ".join(map(str, self.teams.all()))
#
# class Team(models.Model):
# UNKNOWN = 0
# RED = 1
# BLUE = 2
# SIDE_CHOICES = (
# (UNKNOWN, _("Unknown")),
# (RED, _("Red")),
# (BLUE, _("Blue")),
# )
# side = models.IntegerField(db_index=True, choices=SIDE_CHOICES, default=UNKNOWN, verbose_name=_("side"))
#
# game = models.ForeignKey(Game, related_name="teams", on_delete=models.CASCADE)
# score = models.PositiveSmallIntegerField(
# verbose_name=_("score"),
# help_text=_("Team's score in the game"),
# validators=[MaxValueValidator(limit_value=10)]
# )
# players = models.ManyToManyField(User)
#
# def __str__(self):
# return "%s (%s)" % (
# self.score,
# ", ".join(map(str, self.players.all()))
# )
#
# class Player(models.Model):
# user = models.OneToOneField(User)
# singles_wins = models.PositiveIntegerField(
# verbose_name=_("wins - singles"),
# help_text=_("Wins in a single player team"),
# default=0
# )
# singles_win_percentage = models.DecimalField(
# verbose_name=_("win percentage - singles"),
# help_text=_("Win percentage for single player team games"),
# default=0,
# max_digits=5, decimal_places=2,
# validators=[MinValueValidator(limit_value=0), MaxValueValidator(limit_value=100)]
# )
# doubles_wins = models.PositiveIntegerField(
# verbose_name=_("wins - doubles"),
# help_text=_("Wins in a two player team"),
# default=0
# )
# doubles_win_percentage = models.DecimalField(
# verbose_name=_("win percentage - doubles"),
# help_text=_("Win percentage in two player team games"),
# default=0,
# max_digits=5, decimal_places=2,
# validators=[MinValueValidator(limit_value=0), MaxValueValidator(limit_value=100)]
# )
# total_played = models.PositiveIntegerField(
# verbose_name=_("total played"),
# help_text=_("Total games played in"),
# default=0
# )
# singles_played = models.PositiveIntegerField(
# verbose_name=_("singles played"),
# help_text=_("Total games played as a single player team"),
# default=0
# )
# doubles_played = models.PositiveIntegerField(
# verbose_name=_("doubles played"),
# help_text=_("Total games played in a two player team"),
# default=0
# )
# colour = models.CharField(
# verbose_name=_("colour code"),
# help_text=_("Player colour as a hex colour code"),
# max_length=7, null=True
# )
#
# def __str__(self):
# return "Player %s" % self.user.name if self.user.name else self.user.username
#
# def save(self, *args, **kwargs):
# """
# Init some data for the player.
# """
# if not self.pk or not self.colour:
# self.colour = random_colour()
# return super(Player, self).save(*args, **kwargs)
. Output only the next line. | teams = Team.objects.filter(players__id=user.id).prefetch_related("players") |
Here is a snippet: <|code_start|>
def update_player_stats(instance):
"""
Update player win and played counts for players of a Team.
:param instance: Team that will be used to update players.
:type instance: Team
"""
for user in instance.players.all():
totals = {1: 0, 2: 0}
wins = {1: 0, 2: 0}
teams = Team.objects.filter(players__id=user.id).prefetch_related("players")
for team in teams:
player_count = len(team.players.all())
totals[player_count] += 1
if team.score == 10:
wins[player_count] += 1
<|code_end|>
. Write the next line using the current file imports:
from foosball.games.models import Game, Team, Player
and context from other files:
# Path: foosball/games/models.py
# class Game(TimeStampedModel):
# created_by = models.ForeignKey(
# User, related_name="games_created", editable=False, null=True, verbose_name=_("created by")
# )
# modified_by = models.ForeignKey(
# User, related_name="games_modified", editable=False, null=True, verbose_name=_("modified by")
# )
#
# played_at = models.DateTimeField(
# default=timezone.now,
# verbose_name=_("played at"),
# help_text=_("Time when the game was played")
# )
#
# table = models.ForeignKey(Table, blank=True, null=True, related_name="games", verbose_name=_("table"))
#
# class Meta:
# ordering = ['-played_at']
#
# def __str__(self):
# return " - ".join(map(str, self.teams.all()))
#
# class Team(models.Model):
# UNKNOWN = 0
# RED = 1
# BLUE = 2
# SIDE_CHOICES = (
# (UNKNOWN, _("Unknown")),
# (RED, _("Red")),
# (BLUE, _("Blue")),
# )
# side = models.IntegerField(db_index=True, choices=SIDE_CHOICES, default=UNKNOWN, verbose_name=_("side"))
#
# game = models.ForeignKey(Game, related_name="teams", on_delete=models.CASCADE)
# score = models.PositiveSmallIntegerField(
# verbose_name=_("score"),
# help_text=_("Team's score in the game"),
# validators=[MaxValueValidator(limit_value=10)]
# )
# players = models.ManyToManyField(User)
#
# def __str__(self):
# return "%s (%s)" % (
# self.score,
# ", ".join(map(str, self.players.all()))
# )
#
# class Player(models.Model):
# user = models.OneToOneField(User)
# singles_wins = models.PositiveIntegerField(
# verbose_name=_("wins - singles"),
# help_text=_("Wins in a single player team"),
# default=0
# )
# singles_win_percentage = models.DecimalField(
# verbose_name=_("win percentage - singles"),
# help_text=_("Win percentage for single player team games"),
# default=0,
# max_digits=5, decimal_places=2,
# validators=[MinValueValidator(limit_value=0), MaxValueValidator(limit_value=100)]
# )
# doubles_wins = models.PositiveIntegerField(
# verbose_name=_("wins - doubles"),
# help_text=_("Wins in a two player team"),
# default=0
# )
# doubles_win_percentage = models.DecimalField(
# verbose_name=_("win percentage - doubles"),
# help_text=_("Win percentage in two player team games"),
# default=0,
# max_digits=5, decimal_places=2,
# validators=[MinValueValidator(limit_value=0), MaxValueValidator(limit_value=100)]
# )
# total_played = models.PositiveIntegerField(
# verbose_name=_("total played"),
# help_text=_("Total games played in"),
# default=0
# )
# singles_played = models.PositiveIntegerField(
# verbose_name=_("singles played"),
# help_text=_("Total games played as a single player team"),
# default=0
# )
# doubles_played = models.PositiveIntegerField(
# verbose_name=_("doubles played"),
# help_text=_("Total games played in a two player team"),
# default=0
# )
# colour = models.CharField(
# verbose_name=_("colour code"),
# help_text=_("Player colour as a hex colour code"),
# max_length=7, null=True
# )
#
# def __str__(self):
# return "Player %s" % self.user.name if self.user.name else self.user.username
#
# def save(self, *args, **kwargs):
# """
# Init some data for the player.
# """
# if not self.pk or not self.colour:
# self.colour = random_colour()
# return super(Player, self).save(*args, **kwargs)
, which may include functions, classes, or code. Output only the next line. | player, _created = Player.objects.get_or_create(user=user) |
Based on the snippet: <|code_start|> model = Team
def has_changed(self):
# force Teams to be saved also when they aren't modified,
# prevents Games with less than two Teams
return True
class TeamInlineFormSet(forms.models.BaseInlineFormSet):
def clean(self):
clean_team_forms(self.forms[0], self.forms[1])
class TeamInline(admin.TabularInline):
model = Team
form = TeamForm
formset = TeamInlineFormSet
extra = 2
max_num = 2
class Media:
css = {
'all': ('css/admin_hide_team_str.css',)
}
def has_delete_permission(self, request, obj=None):
# a Game should always have both teams
return False
<|code_end|>
, predict the immediate next line with the help of imports:
from django import forms
from django.contrib import admin
from .models import Game, Team, Table
from .utils import clean_team_forms
and context (classes, functions, sometimes code) from other files:
# Path: foosball/games/models.py
# class Game(TimeStampedModel):
# created_by = models.ForeignKey(
# User, related_name="games_created", editable=False, null=True, verbose_name=_("created by")
# )
# modified_by = models.ForeignKey(
# User, related_name="games_modified", editable=False, null=True, verbose_name=_("modified by")
# )
#
# played_at = models.DateTimeField(
# default=timezone.now,
# verbose_name=_("played at"),
# help_text=_("Time when the game was played")
# )
#
# table = models.ForeignKey(Table, blank=True, null=True, related_name="games", verbose_name=_("table"))
#
# class Meta:
# ordering = ['-played_at']
#
# def __str__(self):
# return " - ".join(map(str, self.teams.all()))
#
# class Team(models.Model):
# UNKNOWN = 0
# RED = 1
# BLUE = 2
# SIDE_CHOICES = (
# (UNKNOWN, _("Unknown")),
# (RED, _("Red")),
# (BLUE, _("Blue")),
# )
# side = models.IntegerField(db_index=True, choices=SIDE_CHOICES, default=UNKNOWN, verbose_name=_("side"))
#
# game = models.ForeignKey(Game, related_name="teams", on_delete=models.CASCADE)
# score = models.PositiveSmallIntegerField(
# verbose_name=_("score"),
# help_text=_("Team's score in the game"),
# validators=[MaxValueValidator(limit_value=10)]
# )
# players = models.ManyToManyField(User)
#
# def __str__(self):
# return "%s (%s)" % (
# self.score,
# ", ".join(map(str, self.players.all()))
# )
#
# class Table(models.Model):
# name = models.CharField(unique=True, max_length=255, verbose_name=_("name"))
# description = models.TextField(blank=True, verbose_name=_("description"))
#
# def __str__(self):
# return self.name
#
# Path: foosball/games/utils.py
# def clean_team_forms(team_form_1, team_form_2):
# """
# Extra validation for Team forms.
#
# Checks max number of players and that a player can only play in one team.
# Adds error messages to the forms. Returns info whether all the extra
# validations are valid.
#
# :type team_form_1: TeamModelForm
# :type team_form_2: TeamModelForm
# :rtype: bool
# """
# teams = [list(), list()]
# valid = True
#
# for i, form in enumerate((team_form_1, team_form_2)):
# players = form.cleaned_data.get('players')
# if not players:
# continue # 'This field is required' error is shown here
# if players.count() > 2:
# form.add_error('players', _('Maximum number of players is two.'))
# valid = False
# teams[i] = list(players.all())
#
# if len(set(teams[0]).union(teams[1])) != len(teams[0] + teams[1]):
# for form in (team_form_1, team_form_2):
# form.add_error('players', _('Teams contain same players.'))
# valid = False
#
# return valid
. Output only the next line. | @admin.register(Game) |
Given the following code snippet before the placeholder: <|code_start|>class TeamInline(admin.TabularInline):
model = Team
form = TeamForm
formset = TeamInlineFormSet
extra = 2
max_num = 2
class Media:
css = {
'all': ('css/admin_hide_team_str.css',)
}
def has_delete_permission(self, request, obj=None):
# a Game should always have both teams
return False
@admin.register(Game)
class GameAdmin(admin.ModelAdmin):
list_display = ('__str__', 'played_at', 'table', 'created_by', 'modified_by', 'created', 'modified')
list_filter = ('table',)
inlines = (TeamInline,)
def save_model(self, request, obj, form, change):
if not change:
obj.created_by = request.user
obj.modified_by = request.user
obj.save()
<|code_end|>
, predict the next line using imports from the current file:
from django import forms
from django.contrib import admin
from .models import Game, Team, Table
from .utils import clean_team_forms
and context including class names, function names, and sometimes code from other files:
# Path: foosball/games/models.py
# class Game(TimeStampedModel):
# created_by = models.ForeignKey(
# User, related_name="games_created", editable=False, null=True, verbose_name=_("created by")
# )
# modified_by = models.ForeignKey(
# User, related_name="games_modified", editable=False, null=True, verbose_name=_("modified by")
# )
#
# played_at = models.DateTimeField(
# default=timezone.now,
# verbose_name=_("played at"),
# help_text=_("Time when the game was played")
# )
#
# table = models.ForeignKey(Table, blank=True, null=True, related_name="games", verbose_name=_("table"))
#
# class Meta:
# ordering = ['-played_at']
#
# def __str__(self):
# return " - ".join(map(str, self.teams.all()))
#
# class Team(models.Model):
# UNKNOWN = 0
# RED = 1
# BLUE = 2
# SIDE_CHOICES = (
# (UNKNOWN, _("Unknown")),
# (RED, _("Red")),
# (BLUE, _("Blue")),
# )
# side = models.IntegerField(db_index=True, choices=SIDE_CHOICES, default=UNKNOWN, verbose_name=_("side"))
#
# game = models.ForeignKey(Game, related_name="teams", on_delete=models.CASCADE)
# score = models.PositiveSmallIntegerField(
# verbose_name=_("score"),
# help_text=_("Team's score in the game"),
# validators=[MaxValueValidator(limit_value=10)]
# )
# players = models.ManyToManyField(User)
#
# def __str__(self):
# return "%s (%s)" % (
# self.score,
# ", ".join(map(str, self.players.all()))
# )
#
# class Table(models.Model):
# name = models.CharField(unique=True, max_length=255, verbose_name=_("name"))
# description = models.TextField(blank=True, verbose_name=_("description"))
#
# def __str__(self):
# return self.name
#
# Path: foosball/games/utils.py
# def clean_team_forms(team_form_1, team_form_2):
# """
# Extra validation for Team forms.
#
# Checks max number of players and that a player can only play in one team.
# Adds error messages to the forms. Returns info whether all the extra
# validations are valid.
#
# :type team_form_1: TeamModelForm
# :type team_form_2: TeamModelForm
# :rtype: bool
# """
# teams = [list(), list()]
# valid = True
#
# for i, form in enumerate((team_form_1, team_form_2)):
# players = form.cleaned_data.get('players')
# if not players:
# continue # 'This field is required' error is shown here
# if players.count() > 2:
# form.add_error('players', _('Maximum number of players is two.'))
# valid = False
# teams[i] = list(players.all())
#
# if len(set(teams[0]).union(teams[1])) != len(teams[0] + teams[1]):
# for form in (team_form_1, team_form_2):
# form.add_error('players', _('Teams contain same players.'))
# valid = False
#
# return valid
. Output only the next line. | @admin.register(Table) |
Predict the next line after this snippet: <|code_start|>
class TeamForm(forms.ModelForm):
model = Team
def has_changed(self):
# force Teams to be saved also when they aren't modified,
# prevents Games with less than two Teams
return True
class TeamInlineFormSet(forms.models.BaseInlineFormSet):
def clean(self):
<|code_end|>
using the current file's imports:
from django import forms
from django.contrib import admin
from .models import Game, Team, Table
from .utils import clean_team_forms
and any relevant context from other files:
# Path: foosball/games/models.py
# class Game(TimeStampedModel):
# created_by = models.ForeignKey(
# User, related_name="games_created", editable=False, null=True, verbose_name=_("created by")
# )
# modified_by = models.ForeignKey(
# User, related_name="games_modified", editable=False, null=True, verbose_name=_("modified by")
# )
#
# played_at = models.DateTimeField(
# default=timezone.now,
# verbose_name=_("played at"),
# help_text=_("Time when the game was played")
# )
#
# table = models.ForeignKey(Table, blank=True, null=True, related_name="games", verbose_name=_("table"))
#
# class Meta:
# ordering = ['-played_at']
#
# def __str__(self):
# return " - ".join(map(str, self.teams.all()))
#
# class Team(models.Model):
# UNKNOWN = 0
# RED = 1
# BLUE = 2
# SIDE_CHOICES = (
# (UNKNOWN, _("Unknown")),
# (RED, _("Red")),
# (BLUE, _("Blue")),
# )
# side = models.IntegerField(db_index=True, choices=SIDE_CHOICES, default=UNKNOWN, verbose_name=_("side"))
#
# game = models.ForeignKey(Game, related_name="teams", on_delete=models.CASCADE)
# score = models.PositiveSmallIntegerField(
# verbose_name=_("score"),
# help_text=_("Team's score in the game"),
# validators=[MaxValueValidator(limit_value=10)]
# )
# players = models.ManyToManyField(User)
#
# def __str__(self):
# return "%s (%s)" % (
# self.score,
# ", ".join(map(str, self.players.all()))
# )
#
# class Table(models.Model):
# name = models.CharField(unique=True, max_length=255, verbose_name=_("name"))
# description = models.TextField(blank=True, verbose_name=_("description"))
#
# def __str__(self):
# return self.name
#
# Path: foosball/games/utils.py
# def clean_team_forms(team_form_1, team_form_2):
# """
# Extra validation for Team forms.
#
# Checks max number of players and that a player can only play in one team.
# Adds error messages to the forms. Returns info whether all the extra
# validations are valid.
#
# :type team_form_1: TeamModelForm
# :type team_form_2: TeamModelForm
# :rtype: bool
# """
# teams = [list(), list()]
# valid = True
#
# for i, form in enumerate((team_form_1, team_form_2)):
# players = form.cleaned_data.get('players')
# if not players:
# continue # 'This field is required' error is shown here
# if players.count() > 2:
# form.add_error('players', _('Maximum number of players is two.'))
# valid = False
# teams[i] = list(players.all())
#
# if len(set(teams[0]).union(teams[1])) != len(teams[0] + teams[1]):
# for form in (team_form_1, team_form_2):
# form.add_error('players', _('Teams contain same players.'))
# valid = False
#
# return valid
. Output only the next line. | clean_team_forms(self.forms[0], self.forms[1]) |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
@pytest.fixture
def four_users(user_factory):
return user_factory.create_batch(4)
@pytest.fixture
def game_form_data():
return {
'form-game-played_at': '2016-03-03 12:00:00',
'form-team1-players': [1, 2],
'form-team2-players': [3, 4],
'form-team1-score': 10,
'form-team2-score': 0,
}
@pytest.mark.django_db
def test_game_form_smoke_test(game_form_data, four_users):
<|code_end|>
, determine the next line of code. You have imports:
import pytest
from django.utils.translation import ugettext_lazy as _
from foosball.games.forms import GameForm
and context (class names, function names, or code) available:
# Path: foosball/games/forms.py
# class GameForm(SuperForm):
# game = ModelFormField(GameModelForm)
# team1 = ModelFormField(TeamModelForm)
# team2 = ModelFormField(TeamModelForm)
#
# def is_valid(self):
# return super().is_valid() & clean_team_forms(self.forms['team1'], self.forms['team2'])
. Output only the next line. | form = GameForm(data=game_form_data) |
Using the snippet: <|code_start|>
def handle_login(client):
"""
Create user and log the user in.
"""
user = UserFactory(username="foobar")
client.force_login(user)
def create_game(winner_loser=("RED", "BLUE"), players=(None, None)):
"""
Create a game and teams.
Optionally with given winner/loser sides and players passed in as tuples.
"""
<|code_end|>
, determine the next line of code. You have imports:
from foosball.games.models import Game, Team
from foosball.games.stats import update_player_stats
from foosball.games.tests.factories import TeamFactory
from foosball.users.tests.factories import UserFactory
and context (class names, function names, or code) available:
# Path: foosball/games/models.py
# class Game(TimeStampedModel):
# created_by = models.ForeignKey(
# User, related_name="games_created", editable=False, null=True, verbose_name=_("created by")
# )
# modified_by = models.ForeignKey(
# User, related_name="games_modified", editable=False, null=True, verbose_name=_("modified by")
# )
#
# played_at = models.DateTimeField(
# default=timezone.now,
# verbose_name=_("played at"),
# help_text=_("Time when the game was played")
# )
#
# table = models.ForeignKey(Table, blank=True, null=True, related_name="games", verbose_name=_("table"))
#
# class Meta:
# ordering = ['-played_at']
#
# def __str__(self):
# return " - ".join(map(str, self.teams.all()))
#
# class Team(models.Model):
# UNKNOWN = 0
# RED = 1
# BLUE = 2
# SIDE_CHOICES = (
# (UNKNOWN, _("Unknown")),
# (RED, _("Red")),
# (BLUE, _("Blue")),
# )
# side = models.IntegerField(db_index=True, choices=SIDE_CHOICES, default=UNKNOWN, verbose_name=_("side"))
#
# game = models.ForeignKey(Game, related_name="teams", on_delete=models.CASCADE)
# score = models.PositiveSmallIntegerField(
# verbose_name=_("score"),
# help_text=_("Team's score in the game"),
# validators=[MaxValueValidator(limit_value=10)]
# )
# players = models.ManyToManyField(User)
#
# def __str__(self):
# return "%s (%s)" % (
# self.score,
# ", ".join(map(str, self.players.all()))
# )
#
# Path: foosball/games/stats.py
# def update_player_stats(instance):
# """
# Update player win and played counts for players of a Team.
#
# :param instance: Team that will be used to update players.
# :type instance: Team
# """
# for user in instance.players.all():
# totals = {1: 0, 2: 0}
# wins = {1: 0, 2: 0}
# teams = Team.objects.filter(players__id=user.id).prefetch_related("players")
# for team in teams:
# player_count = len(team.players.all())
# totals[player_count] += 1
# if team.score == 10:
# wins[player_count] += 1
# player, _created = Player.objects.get_or_create(user=user)
# player.singles_wins = wins[1]
# player.doubles_wins = wins[2]
# player.singles_played = totals[1]
# player.doubles_played = totals[2]
# if totals[1]:
# player.singles_win_percentage = round((wins[1]/totals[1])*100, 2)
# else:
# player.singles_win_percentage = 0
# if totals[2]:
# player.doubles_win_percentage = round((wins[2] / totals[2])*100, 2)
# else:
# player.doubles_win_percentage = 0
# player.total_played = totals[1] + totals[2]
# player.save()
#
# Path: foosball/games/tests/factories.py
# class TeamFactory(factory.django.DjangoModelFactory):
# score = factory.fuzzy.FuzzyInteger(10)
#
# @factory.post_generation
# def players(self, create, extracted, **kwargs):
# if not create:
# # Simple build, do nothing.
# return
#
# if extracted:
# # A list of players was passed in, use them
# for player in extracted:
# self.players.add(player)
# return
#
# self.players.add(UserFactory())
# self.players.add(UserFactory())
#
# class Meta:
# model = 'games.Team'
. Output only the next line. | game = Game.objects.create() |
Using the snippet: <|code_start|>
def handle_login(client):
"""
Create user and log the user in.
"""
user = UserFactory(username="foobar")
client.force_login(user)
def create_game(winner_loser=("RED", "BLUE"), players=(None, None)):
"""
Create a game and teams.
Optionally with given winner/loser sides and players passed in as tuples.
"""
game = Game.objects.create()
<|code_end|>
, determine the next line of code. You have imports:
from foosball.games.models import Game, Team
from foosball.games.stats import update_player_stats
from foosball.games.tests.factories import TeamFactory
from foosball.users.tests.factories import UserFactory
and context (class names, function names, or code) available:
# Path: foosball/games/models.py
# class Game(TimeStampedModel):
# created_by = models.ForeignKey(
# User, related_name="games_created", editable=False, null=True, verbose_name=_("created by")
# )
# modified_by = models.ForeignKey(
# User, related_name="games_modified", editable=False, null=True, verbose_name=_("modified by")
# )
#
# played_at = models.DateTimeField(
# default=timezone.now,
# verbose_name=_("played at"),
# help_text=_("Time when the game was played")
# )
#
# table = models.ForeignKey(Table, blank=True, null=True, related_name="games", verbose_name=_("table"))
#
# class Meta:
# ordering = ['-played_at']
#
# def __str__(self):
# return " - ".join(map(str, self.teams.all()))
#
# class Team(models.Model):
# UNKNOWN = 0
# RED = 1
# BLUE = 2
# SIDE_CHOICES = (
# (UNKNOWN, _("Unknown")),
# (RED, _("Red")),
# (BLUE, _("Blue")),
# )
# side = models.IntegerField(db_index=True, choices=SIDE_CHOICES, default=UNKNOWN, verbose_name=_("side"))
#
# game = models.ForeignKey(Game, related_name="teams", on_delete=models.CASCADE)
# score = models.PositiveSmallIntegerField(
# verbose_name=_("score"),
# help_text=_("Team's score in the game"),
# validators=[MaxValueValidator(limit_value=10)]
# )
# players = models.ManyToManyField(User)
#
# def __str__(self):
# return "%s (%s)" % (
# self.score,
# ", ".join(map(str, self.players.all()))
# )
#
# Path: foosball/games/stats.py
# def update_player_stats(instance):
# """
# Update player win and played counts for players of a Team.
#
# :param instance: Team that will be used to update players.
# :type instance: Team
# """
# for user in instance.players.all():
# totals = {1: 0, 2: 0}
# wins = {1: 0, 2: 0}
# teams = Team.objects.filter(players__id=user.id).prefetch_related("players")
# for team in teams:
# player_count = len(team.players.all())
# totals[player_count] += 1
# if team.score == 10:
# wins[player_count] += 1
# player, _created = Player.objects.get_or_create(user=user)
# player.singles_wins = wins[1]
# player.doubles_wins = wins[2]
# player.singles_played = totals[1]
# player.doubles_played = totals[2]
# if totals[1]:
# player.singles_win_percentage = round((wins[1]/totals[1])*100, 2)
# else:
# player.singles_win_percentage = 0
# if totals[2]:
# player.doubles_win_percentage = round((wins[2] / totals[2])*100, 2)
# else:
# player.doubles_win_percentage = 0
# player.total_played = totals[1] + totals[2]
# player.save()
#
# Path: foosball/games/tests/factories.py
# class TeamFactory(factory.django.DjangoModelFactory):
# score = factory.fuzzy.FuzzyInteger(10)
#
# @factory.post_generation
# def players(self, create, extracted, **kwargs):
# if not create:
# # Simple build, do nothing.
# return
#
# if extracted:
# # A list of players was passed in, use them
# for player in extracted:
# self.players.add(player)
# return
#
# self.players.add(UserFactory())
# self.players.add(UserFactory())
#
# class Meta:
# model = 'games.Team'
. Output only the next line. | winners = TeamFactory(score=10, game=game, side=getattr(Team, winner_loser[0]), players=players[0]) |
Based on the snippet: <|code_start|>
def handle_login(client):
"""
Create user and log the user in.
"""
user = UserFactory(username="foobar")
client.force_login(user)
def create_game(winner_loser=("RED", "BLUE"), players=(None, None)):
"""
Create a game and teams.
Optionally with given winner/loser sides and players passed in as tuples.
"""
game = Game.objects.create()
winners = TeamFactory(score=10, game=game, side=getattr(Team, winner_loser[0]), players=players[0])
<|code_end|>
, predict the immediate next line with the help of imports:
from foosball.games.models import Game, Team
from foosball.games.stats import update_player_stats
from foosball.games.tests.factories import TeamFactory
from foosball.users.tests.factories import UserFactory
and context (classes, functions, sometimes code) from other files:
# Path: foosball/games/models.py
# class Game(TimeStampedModel):
# created_by = models.ForeignKey(
# User, related_name="games_created", editable=False, null=True, verbose_name=_("created by")
# )
# modified_by = models.ForeignKey(
# User, related_name="games_modified", editable=False, null=True, verbose_name=_("modified by")
# )
#
# played_at = models.DateTimeField(
# default=timezone.now,
# verbose_name=_("played at"),
# help_text=_("Time when the game was played")
# )
#
# table = models.ForeignKey(Table, blank=True, null=True, related_name="games", verbose_name=_("table"))
#
# class Meta:
# ordering = ['-played_at']
#
# def __str__(self):
# return " - ".join(map(str, self.teams.all()))
#
# class Team(models.Model):
# UNKNOWN = 0
# RED = 1
# BLUE = 2
# SIDE_CHOICES = (
# (UNKNOWN, _("Unknown")),
# (RED, _("Red")),
# (BLUE, _("Blue")),
# )
# side = models.IntegerField(db_index=True, choices=SIDE_CHOICES, default=UNKNOWN, verbose_name=_("side"))
#
# game = models.ForeignKey(Game, related_name="teams", on_delete=models.CASCADE)
# score = models.PositiveSmallIntegerField(
# verbose_name=_("score"),
# help_text=_("Team's score in the game"),
# validators=[MaxValueValidator(limit_value=10)]
# )
# players = models.ManyToManyField(User)
#
# def __str__(self):
# return "%s (%s)" % (
# self.score,
# ", ".join(map(str, self.players.all()))
# )
#
# Path: foosball/games/stats.py
# def update_player_stats(instance):
# """
# Update player win and played counts for players of a Team.
#
# :param instance: Team that will be used to update players.
# :type instance: Team
# """
# for user in instance.players.all():
# totals = {1: 0, 2: 0}
# wins = {1: 0, 2: 0}
# teams = Team.objects.filter(players__id=user.id).prefetch_related("players")
# for team in teams:
# player_count = len(team.players.all())
# totals[player_count] += 1
# if team.score == 10:
# wins[player_count] += 1
# player, _created = Player.objects.get_or_create(user=user)
# player.singles_wins = wins[1]
# player.doubles_wins = wins[2]
# player.singles_played = totals[1]
# player.doubles_played = totals[2]
# if totals[1]:
# player.singles_win_percentage = round((wins[1]/totals[1])*100, 2)
# else:
# player.singles_win_percentage = 0
# if totals[2]:
# player.doubles_win_percentage = round((wins[2] / totals[2])*100, 2)
# else:
# player.doubles_win_percentage = 0
# player.total_played = totals[1] + totals[2]
# player.save()
#
# Path: foosball/games/tests/factories.py
# class TeamFactory(factory.django.DjangoModelFactory):
# score = factory.fuzzy.FuzzyInteger(10)
#
# @factory.post_generation
# def players(self, create, extracted, **kwargs):
# if not create:
# # Simple build, do nothing.
# return
#
# if extracted:
# # A list of players was passed in, use them
# for player in extracted:
# self.players.add(player)
# return
#
# self.players.add(UserFactory())
# self.players.add(UserFactory())
#
# class Meta:
# model = 'games.Team'
. Output only the next line. | update_player_stats(winners) |
Continue the code snippet: <|code_start|>
def handle_login(client):
"""
Create user and log the user in.
"""
user = UserFactory(username="foobar")
client.force_login(user)
def create_game(winner_loser=("RED", "BLUE"), players=(None, None)):
"""
Create a game and teams.
Optionally with given winner/loser sides and players passed in as tuples.
"""
game = Game.objects.create()
<|code_end|>
. Use current file imports:
from foosball.games.models import Game, Team
from foosball.games.stats import update_player_stats
from foosball.games.tests.factories import TeamFactory
from foosball.users.tests.factories import UserFactory
and context (classes, functions, or code) from other files:
# Path: foosball/games/models.py
# class Game(TimeStampedModel):
# created_by = models.ForeignKey(
# User, related_name="games_created", editable=False, null=True, verbose_name=_("created by")
# )
# modified_by = models.ForeignKey(
# User, related_name="games_modified", editable=False, null=True, verbose_name=_("modified by")
# )
#
# played_at = models.DateTimeField(
# default=timezone.now,
# verbose_name=_("played at"),
# help_text=_("Time when the game was played")
# )
#
# table = models.ForeignKey(Table, blank=True, null=True, related_name="games", verbose_name=_("table"))
#
# class Meta:
# ordering = ['-played_at']
#
# def __str__(self):
# return " - ".join(map(str, self.teams.all()))
#
# class Team(models.Model):
# UNKNOWN = 0
# RED = 1
# BLUE = 2
# SIDE_CHOICES = (
# (UNKNOWN, _("Unknown")),
# (RED, _("Red")),
# (BLUE, _("Blue")),
# )
# side = models.IntegerField(db_index=True, choices=SIDE_CHOICES, default=UNKNOWN, verbose_name=_("side"))
#
# game = models.ForeignKey(Game, related_name="teams", on_delete=models.CASCADE)
# score = models.PositiveSmallIntegerField(
# verbose_name=_("score"),
# help_text=_("Team's score in the game"),
# validators=[MaxValueValidator(limit_value=10)]
# )
# players = models.ManyToManyField(User)
#
# def __str__(self):
# return "%s (%s)" % (
# self.score,
# ", ".join(map(str, self.players.all()))
# )
#
# Path: foosball/games/stats.py
# def update_player_stats(instance):
# """
# Update player win and played counts for players of a Team.
#
# :param instance: Team that will be used to update players.
# :type instance: Team
# """
# for user in instance.players.all():
# totals = {1: 0, 2: 0}
# wins = {1: 0, 2: 0}
# teams = Team.objects.filter(players__id=user.id).prefetch_related("players")
# for team in teams:
# player_count = len(team.players.all())
# totals[player_count] += 1
# if team.score == 10:
# wins[player_count] += 1
# player, _created = Player.objects.get_or_create(user=user)
# player.singles_wins = wins[1]
# player.doubles_wins = wins[2]
# player.singles_played = totals[1]
# player.doubles_played = totals[2]
# if totals[1]:
# player.singles_win_percentage = round((wins[1]/totals[1])*100, 2)
# else:
# player.singles_win_percentage = 0
# if totals[2]:
# player.doubles_win_percentage = round((wins[2] / totals[2])*100, 2)
# else:
# player.doubles_win_percentage = 0
# player.total_played = totals[1] + totals[2]
# player.save()
#
# Path: foosball/games/tests/factories.py
# class TeamFactory(factory.django.DjangoModelFactory):
# score = factory.fuzzy.FuzzyInteger(10)
#
# @factory.post_generation
# def players(self, create, extracted, **kwargs):
# if not create:
# # Simple build, do nothing.
# return
#
# if extracted:
# # A list of players was passed in, use them
# for player in extracted:
# self.players.add(player)
# return
#
# self.players.add(UserFactory())
# self.players.add(UserFactory())
#
# class Meta:
# model = 'games.Team'
. Output only the next line. | winners = TeamFactory(score=10, game=game, side=getattr(Team, winner_loser[0]), players=players[0]) |
Using the snippet: <|code_start|>
@pytest.mark.django_db
def test_stats_red_or_blue():
for i in range(3):
create_game()
create_game(("BLUE", "RED"))
<|code_end|>
, determine the next line of code. You have imports:
from decimal import Decimal
from foosball.games.stats import stats_red_or_blue, stats_players
from foosball.games.tests.utils import create_game
from foosball.users.tests.factories import UserFactory
import pytest
and context (class names, function names, or code) available:
# Path: foosball/games/stats.py
# def stats_red_or_blue(params):
# """
# Return statistics on the most important question.
# """
# red_wins = Game.objects.filter(teams__side=Team.RED, teams__score=10).count()
# blue_wins = Game.objects.filter(teams__side=Team.BLUE, teams__score=10).count()
# return {
# "type": "pie",
# "data": {
# "labels": [
# "Red",
# "Blue",
# ],
# "datasets": [
# {
# "data": [red_wins, blue_wins],
# "backgroundColor": [
# "#FF6384",
# "#36A2EB",
# ],
# }]
# },
# "options": {}
# }
#
# def stats_players(params):
# """
# Return statistics on player singles and doubles win percentages.
# """
# players = Player.objects.filter(total_played__gt=5).order_by("user__username").values_list(
# "user__username", "singles_win_percentage", "doubles_win_percentage"
# )
# if players:
# usernames, singles_win_percentages, doubles_win_percentages = zip(*players)
# else:
# usernames = singles_win_percentages = doubles_win_percentages = []
# return {
# "type": "bar",
# "data": {
# "labels": usernames,
# "datasets": [
# {
# "label": "Win % - singles",
# "data": singles_win_percentages,
# "backgroundColor": "#2E5168",
# },
# {
# "label": "Win % - doubles",
# "data": doubles_win_percentages,
# "backgroundColor": "#65923B",
# },
# ]
# },
# "options": {}
# }
#
# Path: foosball/games/tests/utils.py
# def create_game(winner_loser=("RED", "BLUE"), players=(None, None)):
# """
# Create a game and teams.
#
# Optionally with given winner/loser sides and players passed in as tuples.
# """
# game = Game.objects.create()
# winners = TeamFactory(score=10, game=game, side=getattr(Team, winner_loser[0]), players=players[0])
# update_player_stats(winners)
# losers = TeamFactory(score=5, game=game, side=getattr(Team, winner_loser[1]), players=players[1])
# update_player_stats(losers)
# return game, winners, losers
. Output only the next line. | stats = stats_red_or_blue(None) |
Next line prediction: <|code_start|>
@pytest.mark.django_db
def test_stats_red_or_blue():
for i in range(3):
create_game()
create_game(("BLUE", "RED"))
stats = stats_red_or_blue(None)
assert stats["data"]["datasets"][0]["data"] == [3, 1]
@pytest.mark.django_db
def test_stats_players():
p4 = UserFactory(username="p4")
p1 = UserFactory(username="p1")
p3 = UserFactory(username="p3")
p2 = UserFactory(username="p2")
for i in range(4):
create_game(players=([p1, p2], [p3, p4]))
for i in range(2):
create_game(players=([p2], [p4]))
create_game(players=([p3], [p1]))
<|code_end|>
. Use current file imports:
(from decimal import Decimal
from foosball.games.stats import stats_red_or_blue, stats_players
from foosball.games.tests.utils import create_game
from foosball.users.tests.factories import UserFactory
import pytest)
and context including class names, function names, or small code snippets from other files:
# Path: foosball/games/stats.py
# def stats_red_or_blue(params):
# """
# Return statistics on the most important question.
# """
# red_wins = Game.objects.filter(teams__side=Team.RED, teams__score=10).count()
# blue_wins = Game.objects.filter(teams__side=Team.BLUE, teams__score=10).count()
# return {
# "type": "pie",
# "data": {
# "labels": [
# "Red",
# "Blue",
# ],
# "datasets": [
# {
# "data": [red_wins, blue_wins],
# "backgroundColor": [
# "#FF6384",
# "#36A2EB",
# ],
# }]
# },
# "options": {}
# }
#
# def stats_players(params):
# """
# Return statistics on player singles and doubles win percentages.
# """
# players = Player.objects.filter(total_played__gt=5).order_by("user__username").values_list(
# "user__username", "singles_win_percentage", "doubles_win_percentage"
# )
# if players:
# usernames, singles_win_percentages, doubles_win_percentages = zip(*players)
# else:
# usernames = singles_win_percentages = doubles_win_percentages = []
# return {
# "type": "bar",
# "data": {
# "labels": usernames,
# "datasets": [
# {
# "label": "Win % - singles",
# "data": singles_win_percentages,
# "backgroundColor": "#2E5168",
# },
# {
# "label": "Win % - doubles",
# "data": doubles_win_percentages,
# "backgroundColor": "#65923B",
# },
# ]
# },
# "options": {}
# }
#
# Path: foosball/games/tests/utils.py
# def create_game(winner_loser=("RED", "BLUE"), players=(None, None)):
# """
# Create a game and teams.
#
# Optionally with given winner/loser sides and players passed in as tuples.
# """
# game = Game.objects.create()
# winners = TeamFactory(score=10, game=game, side=getattr(Team, winner_loser[0]), players=players[0])
# update_player_stats(winners)
# losers = TeamFactory(score=5, game=game, side=getattr(Team, winner_loser[1]), players=players[1])
# update_player_stats(losers)
# return game, winners, losers
. Output only the next line. | stats = stats_players(None) |
Using the snippet: <|code_start|>
@pytest.mark.django_db
def test_stats_red_or_blue():
for i in range(3):
<|code_end|>
, determine the next line of code. You have imports:
from decimal import Decimal
from foosball.games.stats import stats_red_or_blue, stats_players
from foosball.games.tests.utils import create_game
from foosball.users.tests.factories import UserFactory
import pytest
and context (class names, function names, or code) available:
# Path: foosball/games/stats.py
# def stats_red_or_blue(params):
# """
# Return statistics on the most important question.
# """
# red_wins = Game.objects.filter(teams__side=Team.RED, teams__score=10).count()
# blue_wins = Game.objects.filter(teams__side=Team.BLUE, teams__score=10).count()
# return {
# "type": "pie",
# "data": {
# "labels": [
# "Red",
# "Blue",
# ],
# "datasets": [
# {
# "data": [red_wins, blue_wins],
# "backgroundColor": [
# "#FF6384",
# "#36A2EB",
# ],
# }]
# },
# "options": {}
# }
#
# def stats_players(params):
# """
# Return statistics on player singles and doubles win percentages.
# """
# players = Player.objects.filter(total_played__gt=5).order_by("user__username").values_list(
# "user__username", "singles_win_percentage", "doubles_win_percentage"
# )
# if players:
# usernames, singles_win_percentages, doubles_win_percentages = zip(*players)
# else:
# usernames = singles_win_percentages = doubles_win_percentages = []
# return {
# "type": "bar",
# "data": {
# "labels": usernames,
# "datasets": [
# {
# "label": "Win % - singles",
# "data": singles_win_percentages,
# "backgroundColor": "#2E5168",
# },
# {
# "label": "Win % - doubles",
# "data": doubles_win_percentages,
# "backgroundColor": "#65923B",
# },
# ]
# },
# "options": {}
# }
#
# Path: foosball/games/tests/utils.py
# def create_game(winner_loser=("RED", "BLUE"), players=(None, None)):
# """
# Create a game and teams.
#
# Optionally with given winner/loser sides and players passed in as tuples.
# """
# game = Game.objects.create()
# winners = TeamFactory(score=10, game=game, side=getattr(Team, winner_loser[0]), players=players[0])
# update_player_stats(winners)
# losers = TeamFactory(score=5, game=game, side=getattr(Team, winner_loser[1]), players=players[1])
# update_player_stats(losers)
# return game, winners, losers
. Output only the next line. | create_game() |
Given the following code snippet before the placeholder: <|code_start|>
@pytest.mark.django_db
@pytest.mark.client
def test_game_list_view_renders(client):
handle_login(client)
response = client.get(reverse("games:index"))
assert response.status_code == 200
@pytest.mark.django_db
@pytest.mark.client
def test_game_detail_view_renders(client):
handle_login(client)
<|code_end|>
, predict the next line using imports from the current file:
import pytest
from django.core.urlresolvers import reverse
from foosball.games.tests.factories import GameFactory
from foosball.games.tests.utils import handle_login
and context including class names, function names, and sometimes code from other files:
# Path: foosball/games/tests/factories.py
# class GameFactory(factory.django.DjangoModelFactory):
# played_at = factory.fuzzy.FuzzyDateTime(
# datetime.datetime.utcnow().replace(tzinfo=pytz.utc) - datetime.timedelta(weeks=8))
#
# membership1 = factory.RelatedFactory(TeamFactory, 'game')
# membership2 = factory.RelatedFactory(TeamFactory, 'game')
#
# class Meta:
# model = 'games.Game'
#
# Path: foosball/games/tests/utils.py
# def handle_login(client):
# """
# Create user and log the user in.
# """
# user = UserFactory(username="foobar")
# client.force_login(user)
. Output only the next line. | game = GameFactory() |
Predict the next line after this snippet: <|code_start|>
@pytest.mark.django_db
@pytest.mark.client
def test_game_list_view_renders(client):
<|code_end|>
using the current file's imports:
import pytest
from django.core.urlresolvers import reverse
from foosball.games.tests.factories import GameFactory
from foosball.games.tests.utils import handle_login
and any relevant context from other files:
# Path: foosball/games/tests/factories.py
# class GameFactory(factory.django.DjangoModelFactory):
# played_at = factory.fuzzy.FuzzyDateTime(
# datetime.datetime.utcnow().replace(tzinfo=pytz.utc) - datetime.timedelta(weeks=8))
#
# membership1 = factory.RelatedFactory(TeamFactory, 'game')
# membership2 = factory.RelatedFactory(TeamFactory, 'game')
#
# class Meta:
# model = 'games.Game'
#
# Path: foosball/games/tests/utils.py
# def handle_login(client):
# """
# Create user and log the user in.
# """
# user = UserFactory(username="foobar")
# client.force_login(user)
. Output only the next line. | handle_login(client) |
Continue the code snippet: <|code_start|> )
total_played = models.PositiveIntegerField(
verbose_name=_("total played"),
help_text=_("Total games played in"),
default=0
)
singles_played = models.PositiveIntegerField(
verbose_name=_("singles played"),
help_text=_("Total games played as a single player team"),
default=0
)
doubles_played = models.PositiveIntegerField(
verbose_name=_("doubles played"),
help_text=_("Total games played in a two player team"),
default=0
)
colour = models.CharField(
verbose_name=_("colour code"),
help_text=_("Player colour as a hex colour code"),
max_length=7, null=True
)
def __str__(self):
return "Player %s" % self.user.name if self.user.name else self.user.username
def save(self, *args, **kwargs):
"""
Init some data for the player.
"""
if not self.pk or not self.colour:
<|code_end|>
. Use current file imports:
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from model_utils.models import TimeStampedModel
from foosball.games.utils import random_colour
from foosball.users.models import User
and context (classes, functions, or code) from other files:
# Path: foosball/games/utils.py
# def random_colour():
# """Generate random colour.
#
# Thanks: http://stackoverflow.com/a/14019260/1489738
# """
# r = lambda: random.randint(0, 255)
# return '#%02X%02X%02X' % (r(), r(), r())
. Output only the next line. | self.colour = random_colour() |
Predict the next line after this snippet: <|code_start|>
class MultiPlayerWidget(ModelSelect2MultipleWidget):
model = User
search_fields = [
'username__icontains',
'first_name__icontains',
'last_name__icontains',
'email__icontains',
]
def build_attrs(self, extra_attrs=None, **kwargs):
attrs = super().build_attrs(extra_attrs=extra_attrs, **kwargs)
attrs['data-maximum-selection-length'] = 2
return attrs
def label_from_instance(self, obj):
return " - ".join(filter(None, [obj.username, obj.name]))
class TeamModelForm(forms.ModelForm):
class Meta:
<|code_end|>
using the current file's imports:
from django import forms
from django.utils.translation import ugettext_lazy as _
from django_select2.forms import ModelSelect2MultipleWidget
from django_superform import ModelFormField, SuperForm
from foosball.users.models import User
from .models import Team, Game
from .utils import clean_team_forms
and any relevant context from other files:
# Path: foosball/games/models.py
# class Team(models.Model):
# UNKNOWN = 0
# RED = 1
# BLUE = 2
# SIDE_CHOICES = (
# (UNKNOWN, _("Unknown")),
# (RED, _("Red")),
# (BLUE, _("Blue")),
# )
# side = models.IntegerField(db_index=True, choices=SIDE_CHOICES, default=UNKNOWN, verbose_name=_("side"))
#
# game = models.ForeignKey(Game, related_name="teams", on_delete=models.CASCADE)
# score = models.PositiveSmallIntegerField(
# verbose_name=_("score"),
# help_text=_("Team's score in the game"),
# validators=[MaxValueValidator(limit_value=10)]
# )
# players = models.ManyToManyField(User)
#
# def __str__(self):
# return "%s (%s)" % (
# self.score,
# ", ".join(map(str, self.players.all()))
# )
#
# class Game(TimeStampedModel):
# created_by = models.ForeignKey(
# User, related_name="games_created", editable=False, null=True, verbose_name=_("created by")
# )
# modified_by = models.ForeignKey(
# User, related_name="games_modified", editable=False, null=True, verbose_name=_("modified by")
# )
#
# played_at = models.DateTimeField(
# default=timezone.now,
# verbose_name=_("played at"),
# help_text=_("Time when the game was played")
# )
#
# table = models.ForeignKey(Table, blank=True, null=True, related_name="games", verbose_name=_("table"))
#
# class Meta:
# ordering = ['-played_at']
#
# def __str__(self):
# return " - ".join(map(str, self.teams.all()))
#
# Path: foosball/games/utils.py
# def clean_team_forms(team_form_1, team_form_2):
# """
# Extra validation for Team forms.
#
# Checks max number of players and that a player can only play in one team.
# Adds error messages to the forms. Returns info whether all the extra
# validations are valid.
#
# :type team_form_1: TeamModelForm
# :type team_form_2: TeamModelForm
# :rtype: bool
# """
# teams = [list(), list()]
# valid = True
#
# for i, form in enumerate((team_form_1, team_form_2)):
# players = form.cleaned_data.get('players')
# if not players:
# continue # 'This field is required' error is shown here
# if players.count() > 2:
# form.add_error('players', _('Maximum number of players is two.'))
# valid = False
# teams[i] = list(players.all())
#
# if len(set(teams[0]).union(teams[1])) != len(teams[0] + teams[1]):
# for form in (team_form_1, team_form_2):
# form.add_error('players', _('Teams contain same players.'))
# valid = False
#
# return valid
. Output only the next line. | model = Team |
Predict the next line after this snippet: <|code_start|> 'last_name__icontains',
'email__icontains',
]
def build_attrs(self, extra_attrs=None, **kwargs):
attrs = super().build_attrs(extra_attrs=extra_attrs, **kwargs)
attrs['data-maximum-selection-length'] = 2
return attrs
def label_from_instance(self, obj):
return " - ".join(filter(None, [obj.username, obj.name]))
class TeamModelForm(forms.ModelForm):
class Meta:
model = Team
fields = ('score', 'players')
widgets = {
'players': MultiPlayerWidget,
'score': forms.Select(choices=((i, i) for i in range(11)))
}
labels = {
"score": _("Score"),
"players": _("Players")
}
class GameModelForm(forms.ModelForm):
class Meta:
<|code_end|>
using the current file's imports:
from django import forms
from django.utils.translation import ugettext_lazy as _
from django_select2.forms import ModelSelect2MultipleWidget
from django_superform import ModelFormField, SuperForm
from foosball.users.models import User
from .models import Team, Game
from .utils import clean_team_forms
and any relevant context from other files:
# Path: foosball/games/models.py
# class Team(models.Model):
# UNKNOWN = 0
# RED = 1
# BLUE = 2
# SIDE_CHOICES = (
# (UNKNOWN, _("Unknown")),
# (RED, _("Red")),
# (BLUE, _("Blue")),
# )
# side = models.IntegerField(db_index=True, choices=SIDE_CHOICES, default=UNKNOWN, verbose_name=_("side"))
#
# game = models.ForeignKey(Game, related_name="teams", on_delete=models.CASCADE)
# score = models.PositiveSmallIntegerField(
# verbose_name=_("score"),
# help_text=_("Team's score in the game"),
# validators=[MaxValueValidator(limit_value=10)]
# )
# players = models.ManyToManyField(User)
#
# def __str__(self):
# return "%s (%s)" % (
# self.score,
# ", ".join(map(str, self.players.all()))
# )
#
# class Game(TimeStampedModel):
# created_by = models.ForeignKey(
# User, related_name="games_created", editable=False, null=True, verbose_name=_("created by")
# )
# modified_by = models.ForeignKey(
# User, related_name="games_modified", editable=False, null=True, verbose_name=_("modified by")
# )
#
# played_at = models.DateTimeField(
# default=timezone.now,
# verbose_name=_("played at"),
# help_text=_("Time when the game was played")
# )
#
# table = models.ForeignKey(Table, blank=True, null=True, related_name="games", verbose_name=_("table"))
#
# class Meta:
# ordering = ['-played_at']
#
# def __str__(self):
# return " - ".join(map(str, self.teams.all()))
#
# Path: foosball/games/utils.py
# def clean_team_forms(team_form_1, team_form_2):
# """
# Extra validation for Team forms.
#
# Checks max number of players and that a player can only play in one team.
# Adds error messages to the forms. Returns info whether all the extra
# validations are valid.
#
# :type team_form_1: TeamModelForm
# :type team_form_2: TeamModelForm
# :rtype: bool
# """
# teams = [list(), list()]
# valid = True
#
# for i, form in enumerate((team_form_1, team_form_2)):
# players = form.cleaned_data.get('players')
# if not players:
# continue # 'This field is required' error is shown here
# if players.count() > 2:
# form.add_error('players', _('Maximum number of players is two.'))
# valid = False
# teams[i] = list(players.all())
#
# if len(set(teams[0]).union(teams[1])) != len(teams[0] + teams[1]):
# for form in (team_form_1, team_form_2):
# form.add_error('players', _('Teams contain same players.'))
# valid = False
#
# return valid
. Output only the next line. | model = Game |
Continue the code snippet: <|code_start|> return " - ".join(filter(None, [obj.username, obj.name]))
class TeamModelForm(forms.ModelForm):
class Meta:
model = Team
fields = ('score', 'players')
widgets = {
'players': MultiPlayerWidget,
'score': forms.Select(choices=((i, i) for i in range(11)))
}
labels = {
"score": _("Score"),
"players": _("Players")
}
class GameModelForm(forms.ModelForm):
class Meta:
model = Game
fields = ('played_at', 'table')
class GameForm(SuperForm):
game = ModelFormField(GameModelForm)
team1 = ModelFormField(TeamModelForm)
team2 = ModelFormField(TeamModelForm)
def is_valid(self):
<|code_end|>
. Use current file imports:
from django import forms
from django.utils.translation import ugettext_lazy as _
from django_select2.forms import ModelSelect2MultipleWidget
from django_superform import ModelFormField, SuperForm
from foosball.users.models import User
from .models import Team, Game
from .utils import clean_team_forms
and context (classes, functions, or code) from other files:
# Path: foosball/games/models.py
# class Team(models.Model):
# UNKNOWN = 0
# RED = 1
# BLUE = 2
# SIDE_CHOICES = (
# (UNKNOWN, _("Unknown")),
# (RED, _("Red")),
# (BLUE, _("Blue")),
# )
# side = models.IntegerField(db_index=True, choices=SIDE_CHOICES, default=UNKNOWN, verbose_name=_("side"))
#
# game = models.ForeignKey(Game, related_name="teams", on_delete=models.CASCADE)
# score = models.PositiveSmallIntegerField(
# verbose_name=_("score"),
# help_text=_("Team's score in the game"),
# validators=[MaxValueValidator(limit_value=10)]
# )
# players = models.ManyToManyField(User)
#
# def __str__(self):
# return "%s (%s)" % (
# self.score,
# ", ".join(map(str, self.players.all()))
# )
#
# class Game(TimeStampedModel):
# created_by = models.ForeignKey(
# User, related_name="games_created", editable=False, null=True, verbose_name=_("created by")
# )
# modified_by = models.ForeignKey(
# User, related_name="games_modified", editable=False, null=True, verbose_name=_("modified by")
# )
#
# played_at = models.DateTimeField(
# default=timezone.now,
# verbose_name=_("played at"),
# help_text=_("Time when the game was played")
# )
#
# table = models.ForeignKey(Table, blank=True, null=True, related_name="games", verbose_name=_("table"))
#
# class Meta:
# ordering = ['-played_at']
#
# def __str__(self):
# return " - ".join(map(str, self.teams.all()))
#
# Path: foosball/games/utils.py
# def clean_team_forms(team_form_1, team_form_2):
# """
# Extra validation for Team forms.
#
# Checks max number of players and that a player can only play in one team.
# Adds error messages to the forms. Returns info whether all the extra
# validations are valid.
#
# :type team_form_1: TeamModelForm
# :type team_form_2: TeamModelForm
# :rtype: bool
# """
# teams = [list(), list()]
# valid = True
#
# for i, form in enumerate((team_form_1, team_form_2)):
# players = form.cleaned_data.get('players')
# if not players:
# continue # 'This field is required' error is shown here
# if players.count() > 2:
# form.add_error('players', _('Maximum number of players is two.'))
# valid = False
# teams[i] = list(players.all())
#
# if len(set(teams[0]).union(teams[1])) != len(teams[0] + teams[1]):
# for form in (team_form_1, team_form_2):
# form.add_error('players', _('Teams contain same players.'))
# valid = False
#
# return valid
. Output only the next line. | return super().is_valid() & clean_team_forms(self.forms['team1'], self.forms['team2']) |
Predict the next line after this snippet: <|code_start|>
def build_deployment_from_config(config_txt):
config = json.loads(config_txt)
if not 'metroId' in config:
return "no metroId provided"
if 'metro' in config:
metro_name = config['metro']
else:
metro_name = "N/A"
response = 'Metro #%s (%s) ' % (config['metroId'], metro_name)
source = 'metro-%s' % config['metroId']
osm_key = None
try:
<|code_end|>
using the current file's imports:
from otpsetup.client.models import ManagedDeployment, DeploymentHost, DeploymentGroup, GraphBuild
from kombu import Exchange
from otpsetup.shortcuts import DjangoBrokerConnection
import sys, urllib2, json
and any relevant context from other files:
# Path: otpsetup/client/models.py
# class ManagedDeployment(models.Model):
# source = models.CharField(max_length=15)
# description = models.CharField(max_length=200, null=True, blank=True)
# group = models.ForeignKey(DeploymentGroup, null=True, blank=True)
# last_osm_key = models.CharField(max_length=200, null=True, blank=True)
#
# def __str__(self):
# return "[%s] %s (%s)" % (self.id, self.source, self.description)
#
# class DeploymentHost(models.Model):
# name = models.CharField(max_length=50, blank=True)
# instance_id = models.CharField(max_length=20)
# host_ip = models.CharField(max_length=20)
# otp_version = models.CharField(max_length=20)
# auth_password = models.CharField(max_length=20)
# total_memory = models.BigIntegerField()
# free_memory = models.BigIntegerField()
# group = models.ForeignKey(DeploymentGroup, null=True, blank=True)
#
# def __str__(self):
# return "(%s) %s" % (self.id, self.name)
#
# class DeploymentGroup(models.Model):
# name = models.CharField(max_length=20)
# description = models.TextField(max_length=1000, null=True, blank=True)
#
# def __str__(self):
# return self.name
#
# class GraphBuild(models.Model):
# deployment = models.ForeignKey(ManagedDeployment)
# creation_date = models.DateTimeField(default=datetime.now)
# completion_date = models.DateTimeField(null=True)
# config = models.TextField(max_length=10000, null=True, blank=True)
# osm_key = models.CharField(max_length=200, null=True, blank=True)
# graph_key = models.CharField(max_length=200, null=True, blank=True)
# graph_size = models.BigIntegerField(null=True)
# output_key = models.CharField(max_length=200, null=True, blank=True)
# success = models.BooleanField(default=False)
# otp_version = models.CharField(max_length=20, null=True, blank=True)
#
# def gtfs_count(self):
# return len(self.gtfsbuildmapping_set.all())
#
# def host_count(self):
# return len(self.buildhostmapping_set.all())
#
# def link(self):
# return "<a href='/admin/client/graphbuild/%s'>[<b>%s</b>]</a>" % (self.id, self.id)
# link.allow_tags = True
#
# def __str__(self):
# return "Build #%s / Deployment %s" % (self.id, self.deployment)
. Output only the next line. | man_dep = ManagedDeployment.objects.get(source=source) |
Predict the next line after this snippet: <|code_start|> #html = html + 'published build_managed message<br>'
return response
def deploy_build_to_host(build, host):
exchange = Exchange("amq.direct", type="direct", durable=True)
conn = DjangoBrokerConnection()
publisher = conn.Producer(routing_key="deploy_graph_multi", exchange=exchange)
publisher.publish({"request_id" : build.id, "instance_id" : host.instance_id, "graph_key" : build.graph_key})
def update_memory(host):
try:
response = urllib2.urlopen('http://%s:8080/memcheck/total' % host.host_ip)
host.total_memory = int(response.read().strip())
response = urllib2.urlopen('http://%s:8080/memcheck/free' % host.host_ip)
host.free_memory = int(response.read().strip())
host.save()
except:
sys.stderr.write("warning: memory utilization for deployment host % could not be accessed" % host.id)
def deploy_once(build):
group = build.deployment.group
# check for existing instance
<|code_end|>
using the current file's imports:
from otpsetup.client.models import ManagedDeployment, DeploymentHost, DeploymentGroup, GraphBuild
from kombu import Exchange
from otpsetup.shortcuts import DjangoBrokerConnection
import sys, urllib2, json
and any relevant context from other files:
# Path: otpsetup/client/models.py
# class ManagedDeployment(models.Model):
# source = models.CharField(max_length=15)
# description = models.CharField(max_length=200, null=True, blank=True)
# group = models.ForeignKey(DeploymentGroup, null=True, blank=True)
# last_osm_key = models.CharField(max_length=200, null=True, blank=True)
#
# def __str__(self):
# return "[%s] %s (%s)" % (self.id, self.source, self.description)
#
# class DeploymentHost(models.Model):
# name = models.CharField(max_length=50, blank=True)
# instance_id = models.CharField(max_length=20)
# host_ip = models.CharField(max_length=20)
# otp_version = models.CharField(max_length=20)
# auth_password = models.CharField(max_length=20)
# total_memory = models.BigIntegerField()
# free_memory = models.BigIntegerField()
# group = models.ForeignKey(DeploymentGroup, null=True, blank=True)
#
# def __str__(self):
# return "(%s) %s" % (self.id, self.name)
#
# class DeploymentGroup(models.Model):
# name = models.CharField(max_length=20)
# description = models.TextField(max_length=1000, null=True, blank=True)
#
# def __str__(self):
# return self.name
#
# class GraphBuild(models.Model):
# deployment = models.ForeignKey(ManagedDeployment)
# creation_date = models.DateTimeField(default=datetime.now)
# completion_date = models.DateTimeField(null=True)
# config = models.TextField(max_length=10000, null=True, blank=True)
# osm_key = models.CharField(max_length=200, null=True, blank=True)
# graph_key = models.CharField(max_length=200, null=True, blank=True)
# graph_size = models.BigIntegerField(null=True)
# output_key = models.CharField(max_length=200, null=True, blank=True)
# success = models.BooleanField(default=False)
# otp_version = models.CharField(max_length=20, null=True, blank=True)
#
# def gtfs_count(self):
# return len(self.gtfsbuildmapping_set.all())
#
# def host_count(self):
# return len(self.buildhostmapping_set.all())
#
# def link(self):
# return "<a href='/admin/client/graphbuild/%s'>[<b>%s</b>]</a>" % (self.id, self.id)
# link.allow_tags = True
#
# def __str__(self):
# return "Build #%s / Deployment %s" % (self.id, self.deployment)
. Output only the next line. | for host in DeploymentHost.objects.all(): |
Using the snippet: <|code_start|>
def build_deployment_from_config(config_txt):
config = json.loads(config_txt)
if not 'metroId' in config:
return "no metroId provided"
if 'metro' in config:
metro_name = config['metro']
else:
metro_name = "N/A"
response = 'Metro #%s (%s) ' % (config['metroId'], metro_name)
source = 'metro-%s' % config['metroId']
osm_key = None
try:
man_dep = ManagedDeployment.objects.get(source=source)
response += " has existing record."
except ManagedDeployment.DoesNotExist:
<|code_end|>
, determine the next line of code. You have imports:
from otpsetup.client.models import ManagedDeployment, DeploymentHost, DeploymentGroup, GraphBuild
from kombu import Exchange
from otpsetup.shortcuts import DjangoBrokerConnection
import sys, urllib2, json
and context (class names, function names, or code) available:
# Path: otpsetup/client/models.py
# class ManagedDeployment(models.Model):
# source = models.CharField(max_length=15)
# description = models.CharField(max_length=200, null=True, blank=True)
# group = models.ForeignKey(DeploymentGroup, null=True, blank=True)
# last_osm_key = models.CharField(max_length=200, null=True, blank=True)
#
# def __str__(self):
# return "[%s] %s (%s)" % (self.id, self.source, self.description)
#
# class DeploymentHost(models.Model):
# name = models.CharField(max_length=50, blank=True)
# instance_id = models.CharField(max_length=20)
# host_ip = models.CharField(max_length=20)
# otp_version = models.CharField(max_length=20)
# auth_password = models.CharField(max_length=20)
# total_memory = models.BigIntegerField()
# free_memory = models.BigIntegerField()
# group = models.ForeignKey(DeploymentGroup, null=True, blank=True)
#
# def __str__(self):
# return "(%s) %s" % (self.id, self.name)
#
# class DeploymentGroup(models.Model):
# name = models.CharField(max_length=20)
# description = models.TextField(max_length=1000, null=True, blank=True)
#
# def __str__(self):
# return self.name
#
# class GraphBuild(models.Model):
# deployment = models.ForeignKey(ManagedDeployment)
# creation_date = models.DateTimeField(default=datetime.now)
# completion_date = models.DateTimeField(null=True)
# config = models.TextField(max_length=10000, null=True, blank=True)
# osm_key = models.CharField(max_length=200, null=True, blank=True)
# graph_key = models.CharField(max_length=200, null=True, blank=True)
# graph_size = models.BigIntegerField(null=True)
# output_key = models.CharField(max_length=200, null=True, blank=True)
# success = models.BooleanField(default=False)
# otp_version = models.CharField(max_length=20, null=True, blank=True)
#
# def gtfs_count(self):
# return len(self.gtfsbuildmapping_set.all())
#
# def host_count(self):
# return len(self.buildhostmapping_set.all())
#
# def link(self):
# return "<a href='/admin/client/graphbuild/%s'>[<b>%s</b>]</a>" % (self.id, self.id)
# link.allow_tags = True
#
# def __str__(self):
# return "Build #%s / Deployment %s" % (self.id, self.deployment)
. Output only the next line. | group = DeploymentGroup.objects.get(name="otpna") |
Given snippet: <|code_start|>
def build_deployment_from_config(config_txt):
config = json.loads(config_txt)
if not 'metroId' in config:
return "no metroId provided"
if 'metro' in config:
metro_name = config['metro']
else:
metro_name = "N/A"
response = 'Metro #%s (%s) ' % (config['metroId'], metro_name)
source = 'metro-%s' % config['metroId']
osm_key = None
try:
man_dep = ManagedDeployment.objects.get(source=source)
response += " has existing record."
except ManagedDeployment.DoesNotExist:
group = DeploymentGroup.objects.get(name="otpna")
man_dep = ManagedDeployment(source=source, group=group)
response += " has no record; created."
man_dep.description = metro_name
man_dep.save()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from otpsetup.client.models import ManagedDeployment, DeploymentHost, DeploymentGroup, GraphBuild
from kombu import Exchange
from otpsetup.shortcuts import DjangoBrokerConnection
import sys, urllib2, json
and context:
# Path: otpsetup/client/models.py
# class ManagedDeployment(models.Model):
# source = models.CharField(max_length=15)
# description = models.CharField(max_length=200, null=True, blank=True)
# group = models.ForeignKey(DeploymentGroup, null=True, blank=True)
# last_osm_key = models.CharField(max_length=200, null=True, blank=True)
#
# def __str__(self):
# return "[%s] %s (%s)" % (self.id, self.source, self.description)
#
# class DeploymentHost(models.Model):
# name = models.CharField(max_length=50, blank=True)
# instance_id = models.CharField(max_length=20)
# host_ip = models.CharField(max_length=20)
# otp_version = models.CharField(max_length=20)
# auth_password = models.CharField(max_length=20)
# total_memory = models.BigIntegerField()
# free_memory = models.BigIntegerField()
# group = models.ForeignKey(DeploymentGroup, null=True, blank=True)
#
# def __str__(self):
# return "(%s) %s" % (self.id, self.name)
#
# class DeploymentGroup(models.Model):
# name = models.CharField(max_length=20)
# description = models.TextField(max_length=1000, null=True, blank=True)
#
# def __str__(self):
# return self.name
#
# class GraphBuild(models.Model):
# deployment = models.ForeignKey(ManagedDeployment)
# creation_date = models.DateTimeField(default=datetime.now)
# completion_date = models.DateTimeField(null=True)
# config = models.TextField(max_length=10000, null=True, blank=True)
# osm_key = models.CharField(max_length=200, null=True, blank=True)
# graph_key = models.CharField(max_length=200, null=True, blank=True)
# graph_size = models.BigIntegerField(null=True)
# output_key = models.CharField(max_length=200, null=True, blank=True)
# success = models.BooleanField(default=False)
# otp_version = models.CharField(max_length=20, null=True, blank=True)
#
# def gtfs_count(self):
# return len(self.gtfsbuildmapping_set.all())
#
# def host_count(self):
# return len(self.buildhostmapping_set.all())
#
# def link(self):
# return "<a href='/admin/client/graphbuild/%s'>[<b>%s</b>]</a>" % (self.id, self.id)
# link.allow_tags = True
#
# def __str__(self):
# return "Build #%s / Deployment %s" % (self.id, self.deployment)
which might include code, classes, or functions. Output only the next line. | build = GraphBuild(deployment=man_dep, osm_key=man_dep.last_osm_key, config=config_txt) |
Predict the next line for this snippet: <|code_start|>
@permission_required('admin')
def index(request):
conn = connect_ec2(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_KEY)
reservations = conn.get_all_instances()
running_instances = []
for reservation in reservations:
for instance in reservation.instances:
<|code_end|>
with the help of current file imports:
from boto import connect_s3, connect_ec2
from otpsetup.client.models import AmazonMachineImage, InstanceRequestForm, InstanceRequest, GtfsFile
from datetime import datetime, timedelta
from django.conf import settings
from django.contrib.auth.decorators import permission_required
from django.shortcuts import redirect
from json import dumps
from otpsetup.shortcuts import render_to_response
from otpsetup.shortcuts import DjangoBrokerConnection
import base64
import hmac, sha
and context from other files:
# Path: otpsetup/client/models.py
# class AmazonMachineImage(models.Model):
# ami_id = models.CharField(max_length=200)
# machine_type = models.CharField(max_length=20, choices=MACHINE_TYPES)
# version = models.CharField(max_length=20)
# default_for_new_instances = models.BooleanField(max_length=20, default=True)
# def save(self, force_insert=False, force_update=False):
# if self.default_for_new_instances:
# AmazonMachineImage.objects.filter(~Q(id = self.id) & Q(machine_type = self.machine_type)).update(default_for_new_instances=False)
# super(Test, self).save(force_insert, force_update)
#
# class InstanceRequestForm(ModelForm):
# fare_factory = RegexField(label="Fare model", max_length=200,
# regex=r'^[\w.]+')
#
# class Meta:
# model = InstanceRequest
# fields = ('comments', 'agency', 'fare_factory')
#
# class InstanceRequest(models.Model):
# state = models.CharField(max_length=15, default='building', choices = STATES)
# submit_date = models.DateTimeField('date submitted', default=datetime.now)
# decision_date = models.DateTimeField('date decided', null=True)
#
# user = models.ForeignKey(User)
# agency = models.CharField(max_length=40, blank=True)
# comments = models.TextField(max_length=20000, null=True, blank=True)
# fare_factory = models.CharField(max_length=200)
# deployment_hostname = models.CharField(max_length=30, null=True, blank=True)
# admin_password = models.CharField(max_length=15, null=True, blank=True)
# public_url = models.CharField(max_length=60, null=True, blank=True)
# graph_key = models.CharField(max_length=60, null=True, blank=True)
# data_key = models.CharField(max_length=60, null=True, blank=True)
# graph_url = models.CharField(max_length=150, null=True, blank=True)
# ip = models.CharField(max_length=15)
# deployment_host = models.ForeignKey(DeploymentHost, null=True, blank=True)
# otp_version = models.CharField(max_length=20, null=True, blank=True)
#
# __original_dephost = None
#
# def __init__(self, *args, **kwargs):
# super(InstanceRequest, self).__init__(*args, **kwargs)
# self.__original_dephost = self.deployment_host
#
# def save(self, force_insert=False, force_update=False):
# if self.deployment_host != self.__original_dephost and self.deployment_host is not None:
# # dephost changed - publish deployer message
# exchange = Exchange("amq.direct", type="direct", durable=True)
# conn = DjangoBrokerConnection()
# publisher = conn.Producer(routing_key="deploy_graph_multi", exchange=exchange)
# publisher.publish({"request_id" : self.id, "instance_id" : self.deployment_host.instance_id, "graph_key" : self.graph_key})
#
#
# super(InstanceRequest, self).save(force_insert, force_update)
# self.__original_dephost = self.deployment_host
#
# class GtfsFile(models.Model):
# instance_request = models.ForeignKey(InstanceRequest)
# s3_key = models.CharField(max_length=200, null=True, db_index=True)
# transload_url = models.CharField(max_length=200, null=True)
# validation_output = models.TextField(max_length=20000, null=True, blank=True)
# extra_properties = models.TextField(max_length=2000, null=True, blank=True)
#
# def validation_output_str(self):
# if(self.validation_output == None):
# return "(None)"
# return "<textarea rows=8 cols=85>%s</textarea>" % self.validation_output
# validation_output_str.allow_tags = True
, which may contain function names, class names, or code. Output only the next line. | image = AmazonMachineImage.objects.get(ami_id=instance.image_id) |
Continue the code snippet: <|code_start|>
## Global register for db commands that must be performed if
## processes are aborted
class database(sqlite3.Connection):
db_name = None
json_data = None
_mem_db = False
_db_com_register = {}
_lock = th.Lock()
@classmethod
def setup(cls, json_data):
cls.json_data = json_data
config = cls.json_data.config
cls.db_name = config['DEFAULT'].get('gembs_dbfile', 'file:gemBS?mode=memory&cache=shared')
cls._mem_db = (cls.db_name.startswith('file:'))
@classmethod
def mem_db(cls):
return cls._mem_db
@classmethod
def reg_db_com(cls, key, com, rm_list):
cls._lock.acquire()
if key in cls._db_com_register:
<|code_end|>
. Use current file imports:
import os
import sqlite3
import re
import fnmatch
import logging
import json
import threading as th
from .utils import CommandException
and context (classes, functions, or code) from other files:
# Path: gemBS/utils.py
# class CommandException(Exception):
# """Exception thrown by gemtools commands"""
# pass
. Output only the next line. | raise CommandException("Can not register duplicate key") |
Here is a snippet: <|code_start|> if ack:
six.print_('Successful', typstr, 'open of',
lockopt['option'] +
'-locked concatenated tables',
tabname, ':', self.ncols(), 'columns,',
self.nrows(), 'rows')
else:
# Concatenate already open tables.
Table.__init__(self, tabname, concatsubtables, 0, 0, 0)
if ack:
six.print_('Successful virtual concatenation of',
len(tabname), 'tables:', self.ncols(),
'columns,', self.nrows(), 'rows')
# Create a row object for this table.
self._makerow()
def __enter__(self):
"""Function to enter a with block."""
return self
def __exit__(self, type, value, traceback):
"""Function to exit a with block which closes the table object."""
self.close()
def _makerow(self):
"""Internal method to make its tablerow object."""
self._row = _tablerow(self, [])
def __str__(self):
"""Return the table name and the basic statistics"""
<|code_end|>
. Write the next line using the current file imports:
from six import string_types
from ._tables import (Table,
_default_ms,
_default_ms_subtable,
_required_ms_desc,
_complete_ms_desc)
from .tablehelper import (_add_prefix, _remove_prefix, _do_remove_prefix,
_format_row)
from .tablerow import _tablerow
from .tablecolumn import tablecolumn
from .tablerow import tablerow
from .tableiter import tableiter
from .tableindex import tableindex
from casacore.tables import tabledelete
from wxPython.wx import wxPySimpleApp
from wxtablebrowser import CasaTestFrame
from casacore.tables import tabledelete
import six
import casacore.util
import casacore.tables.tableutil as pt
import casacore.tables.tableutil as pt
import os
import wxPython
import sys
import os
and context from other files:
# Path: casacore/tables/tablehelper.py
# def _add_prefix(name):
# """Add the prefix 'Table: ' to a table name to get a specific keyword value."""
# return 'Table: ' + name
#
# def _remove_prefix(name):
# """Strip the possible prefix 'Table: ' from one or more table names."""
# if isinstance(name, string_types):
# return _do_remove_prefix(name)
# return [_do_remove_prefix(nm) for nm in name]
#
# def _do_remove_prefix(name):
# """Strip the possible prefix 'Table: ' from a table name."""
# res = name
# if isinstance(res, string_types):
# if res.find('Table: ') == 0:
# res = res.replace('Table: ', '', 1)
# return res
#
# def _format_row(row, colnames, tab):
# """
# Helper function for _repr_html. Formats one row.
# :param row: row of this table
# :param colnames: vector of column names
# :param tab: table, used to get the column keywords
# :return: html-formatted row
# """
# out = ""
#
# out += "\n<tr>"
# for colname in colnames:
# out += "<td style='vertical-align:top; white-space:pre'>"
# out += _format_cell(row[colname], tab.getcolkeywords(colname))
# out += "</td>\n"
# out += "</tr>\n"
# return out
, which may include functions, classes, or code. Output only the next line. | return (_add_prefix(self.name()) + "\n%d rows" % self.nrows() + |
Continue the code snippet: <|code_start|> in use in another process
`permanentwait`
as above, but wait until the lock is acquired.
`default`
this is the default option.
If the given table is already open, the locking option
in use is not changed. Otherwise it reverts to `auto`.
If auto locking is used, it is possible to give a record containing
the fields option, interval, and/or maxwait (see :func:`lockoptions`
for their meaning). In this way advanced users can have full control
over the locking process. In practice this is hardly ever needed.
For example::
t = table('3c343.ms') # open table readonly
t = table('3c343.ms', readonly=False) # open table read/write
t1= table('new.tab', t.getdesc()) # create table
t = table([t1,t2,t3,t4]) # concatenate 4 tables
"""
def __init__(self, tablename, tabledesc=False, nrow=0, readonly=True,
lockoptions='default', ack=True, dminfo={}, endian='aipsrc',
memorytable=False, concatsubtables=[],
_columnnames=[], _datatypes=[],
_oper=0, _delete=False):
"""Open or create a table."""
if _oper == 1:
# This is the readascii constructor.
<|code_end|>
. Use current file imports:
from six import string_types
from ._tables import (Table,
_default_ms,
_default_ms_subtable,
_required_ms_desc,
_complete_ms_desc)
from .tablehelper import (_add_prefix, _remove_prefix, _do_remove_prefix,
_format_row)
from .tablerow import _tablerow
from .tablecolumn import tablecolumn
from .tablerow import tablerow
from .tableiter import tableiter
from .tableindex import tableindex
from casacore.tables import tabledelete
from wxPython.wx import wxPySimpleApp
from wxtablebrowser import CasaTestFrame
from casacore.tables import tabledelete
import six
import casacore.util
import casacore.tables.tableutil as pt
import casacore.tables.tableutil as pt
import os
import wxPython
import sys
import os
and context (classes, functions, or code) from other files:
# Path: casacore/tables/tablehelper.py
# def _add_prefix(name):
# """Add the prefix 'Table: ' to a table name to get a specific keyword value."""
# return 'Table: ' + name
#
# def _remove_prefix(name):
# """Strip the possible prefix 'Table: ' from one or more table names."""
# if isinstance(name, string_types):
# return _do_remove_prefix(name)
# return [_do_remove_prefix(nm) for nm in name]
#
# def _do_remove_prefix(name):
# """Strip the possible prefix 'Table: ' from a table name."""
# res = name
# if isinstance(res, string_types):
# if res.find('Table: ') == 0:
# res = res.replace('Table: ', '', 1)
# return res
#
# def _format_row(row, colnames, tab):
# """
# Helper function for _repr_html. Formats one row.
# :param row: row of this table
# :param colnames: vector of column names
# :param tab: table, used to get the column keywords
# :return: html-formatted row
# """
# out = ""
#
# out += "\n<tr>"
# for colname in colnames:
# out += "<td style='vertical-align:top; white-space:pre'>"
# out += _format_cell(row[colname], tab.getcolkeywords(colname))
# out += "</td>\n"
# out += "</tr>\n"
# return out
. Output only the next line. | tabname = _remove_prefix(tablename) |
Using the snippet: <|code_start|> return int(self._nrows())
def __getattr__(self, name):
"""Get the tablecolumn object or keyword value.
| A tablecolumn object is returned if it names a column.
| The value of a keyword is returned if it names a keyword.
If the keyword is a subtable, it opens the table and returns a
table object.
| The values of all keywords is returned if name equals _ or keys.
An AttributeError is raised if the name is column nor keyword.
For example::
print t.DATA[i] # print row i of column DATA
print t.MS_VERSION # print the MS version
print t.keys # print values of all keywords
subtab = t.FEED # open the FEED subtable
"""
# First try if it is a column.
try:
return self.col(name)
except Exception:
pass
# Now try if it is a keyword.
try:
val = self.getkeyword(name)
# See if the keyword represents a subtable and try to open it.
<|code_end|>
, determine the next line of code. You have imports:
from six import string_types
from ._tables import (Table,
_default_ms,
_default_ms_subtable,
_required_ms_desc,
_complete_ms_desc)
from .tablehelper import (_add_prefix, _remove_prefix, _do_remove_prefix,
_format_row)
from .tablerow import _tablerow
from .tablecolumn import tablecolumn
from .tablerow import tablerow
from .tableiter import tableiter
from .tableindex import tableindex
from casacore.tables import tabledelete
from wxPython.wx import wxPySimpleApp
from wxtablebrowser import CasaTestFrame
from casacore.tables import tabledelete
import six
import casacore.util
import casacore.tables.tableutil as pt
import casacore.tables.tableutil as pt
import os
import wxPython
import sys
import os
and context (class names, function names, or code) available:
# Path: casacore/tables/tablehelper.py
# def _add_prefix(name):
# """Add the prefix 'Table: ' to a table name to get a specific keyword value."""
# return 'Table: ' + name
#
# def _remove_prefix(name):
# """Strip the possible prefix 'Table: ' from one or more table names."""
# if isinstance(name, string_types):
# return _do_remove_prefix(name)
# return [_do_remove_prefix(nm) for nm in name]
#
# def _do_remove_prefix(name):
# """Strip the possible prefix 'Table: ' from a table name."""
# res = name
# if isinstance(res, string_types):
# if res.find('Table: ') == 0:
# res = res.replace('Table: ', '', 1)
# return res
#
# def _format_row(row, colnames, tab):
# """
# Helper function for _repr_html. Formats one row.
# :param row: row of this table
# :param colnames: vector of column names
# :param tab: table, used to get the column keywords
# :return: html-formatted row
# """
# out = ""
#
# out += "\n<tr>"
# for colname in colnames:
# out += "<td style='vertical-align:top; white-space:pre'>"
# out += _format_cell(row[colname], tab.getcolkeywords(colname))
# out += "</td>\n"
# out += "</tr>\n"
# return out
. Output only the next line. | if val != _do_remove_prefix(val): |
Predict the next line after this snippet: <|code_start|> if wait:
six.print_(" finished viewing")
tabledelete(tempname)
else:
six.print_(" after viewing use tabledelete('" +
tempname + "') to delete the copy")
else:
six.print_("Cannot browse because the table is " +
"in memory only.")
six.print_("You can browse a (shallow) persistent " +
"copy of the table like:")
six.print_(" t.view(True, '/tmp/tab1')")
# Could not view the table, so browse it.
if not viewed:
self.browse(wait, tempname)
def _repr_html_(self):
"""Give a nice representation of tables in notebooks."""
out = "<table class='taqltable' style='overflow-x:auto'>\n"
# Print column names (not if they are all auto-generated)
if not(all([colname[:4] == "Col_" for colname in self.colnames()])):
out += "<tr>"
for colname in self.colnames():
out += "<th><b>"+colname+"</b></th>"
out += "</tr>"
cropped = False
rowcount = 0
for row in self:
<|code_end|>
using the current file's imports:
from six import string_types
from ._tables import (Table,
_default_ms,
_default_ms_subtable,
_required_ms_desc,
_complete_ms_desc)
from .tablehelper import (_add_prefix, _remove_prefix, _do_remove_prefix,
_format_row)
from .tablerow import _tablerow
from .tablecolumn import tablecolumn
from .tablerow import tablerow
from .tableiter import tableiter
from .tableindex import tableindex
from casacore.tables import tabledelete
from wxPython.wx import wxPySimpleApp
from wxtablebrowser import CasaTestFrame
from casacore.tables import tabledelete
import six
import casacore.util
import casacore.tables.tableutil as pt
import casacore.tables.tableutil as pt
import os
import wxPython
import sys
import os
and any relevant context from other files:
# Path: casacore/tables/tablehelper.py
# def _add_prefix(name):
# """Add the prefix 'Table: ' to a table name to get a specific keyword value."""
# return 'Table: ' + name
#
# def _remove_prefix(name):
# """Strip the possible prefix 'Table: ' from one or more table names."""
# if isinstance(name, string_types):
# return _do_remove_prefix(name)
# return [_do_remove_prefix(nm) for nm in name]
#
# def _do_remove_prefix(name):
# """Strip the possible prefix 'Table: ' from a table name."""
# res = name
# if isinstance(res, string_types):
# if res.find('Table: ') == 0:
# res = res.replace('Table: ', '', 1)
# return res
#
# def _format_row(row, colnames, tab):
# """
# Helper function for _repr_html. Formats one row.
# :param row: row of this table
# :param colnames: vector of column names
# :param tab: table, used to get the column keywords
# :return: html-formatted row
# """
# out = ""
#
# out += "\n<tr>"
# for colname in colnames:
# out += "<td style='vertical-align:top; white-space:pre'>"
# out += _format_cell(row[colname], tab.getcolkeywords(colname))
# out += "</td>\n"
# out += "</tr>\n"
# return out
. Output only the next line. | rowout = _format_row(row, self.colnames(), self) |
Based on the snippet: <|code_start|># However, a mutual dependency is created when doing that for the tablerow
# object inside the table object.
# Therefore an intermediate _tablerow exists to be used in class table.
class _tablerow(TableRow):
def __init__(self, table, columnnames, exclude=False):
TableRow.__init__(self, table, columnnames, exclude)
def iswritable(self):
"""Tell if all columns in the row object are writable."""
return self._iswritable()
def get(self, rownr):
"""Get the contents of the given row."""
return self._get(rownr)
def put(self, rownr, value, matchingfields=True):
"""Put the values into the given row.
The value should be a dict (as returned by method :func:`get`.
The names of the fields in the dict should match the names of the
columns used in the `tablerow` object.
`matchingfields=True` means that the value may contain more fields
and only fields matching a column name will be used.
"""
self._put(rownr, value, matchingfields)
def _getitem(self, key, nrows):
<|code_end|>
, predict the immediate next line with the help of imports:
from ._tables import TableRow
from .tablehelper import _check_key_slice
and context (classes, functions, sometimes code) from other files:
# Path: casacore/tables/tablehelper.py
# def _check_key_slice(key, nrows, name):
# if not isinstance(key, slice):
# inx = _check_index(key, name)
# # A single index (possibly negative, thus from the end).
# if inx < 0:
# inx += nrows
# if inx < 0 or inx >= nrows:
# raise IndexError(name + " index out of range")
# return [inx]
# # Given as start:stop:step where each part is optional and can
# # be negative.
# incr = 1
# if key.step is not None:
# incr = _check_index(key.step, name)
# if incr == 0:
# raise RuntimeError(name + " slice step cannot be zero")
# strow = 0
# endrow = nrows
# if incr < 0:
# strow = nrows - 1
# endrow = -1
# if key.start is not None:
# strow = _check_index(key.start, name)
# if strow < 0:
# strow += nrows
# strow = min(max(strow, 0), nrows - 1)
# if key.stop is not None:
# endrow = _check_index(key.stop, name)
# if endrow < 0:
# endrow += nrows
# endrow = min(max(endrow, -1), nrows)
# if incr > 0:
# nrow = int((endrow - strow + incr - 1) / incr)
# else:
# nrow = int((strow - endrow - incr - 1) / -incr)
# nrow = max(0, nrow)
# return [strow, nrow, incr]
. Output only the next line. | sei = _check_key_slice(key, nrows, 'tablerow') |
Next line prediction: <|code_start|>
| See `func:`tables.table.haslock` for more information.
| Locks are only used for images in casacore format. For other formats
(un)locking is a no-op, so this method always returns True.
"""
return self._unlock()
def subimage(self, blc=(), trc=(), inc=(), dropdegenerate=True):
"""Form a subimage.
An image object containing a subset of an image is returned.
The arguments blc (bottom left corner), trc (top right corner),
and inc (stride) define the subset. Not all axes need to be specified.
Missing values default to begin, end, and 1.
By default axes with length 1 are left out.
A subimage is a so-called virtual image. It is not stored, but only
references the original image. It can be made persistent using the
:func:`saveas` method.
"""
return image(self._subimage(self._adjustBlc(blc),
self._adjustTrc(trc),
self._adjustInc(inc),
dropdegenerate))
def coordinates(self):
"""Get the :class:`coordinatesystem` of the image."""
<|code_end|>
. Use current file imports:
(from six import string_types, integer_types
from ._images import Image
from casacore.images.coordinates import coordinatesystem
import numpy
import numpy.ma as nma
import six
import casacore.util as cu
import os)
and context including class names, function names, or small code snippets from other files:
# Path: casacore/images/coordinates.py
# class coordinatesystem(object):
# """
# A thin wrapper for casacore coordinate systems. It dissects the
# coordinatesystem record returned from casacore images.
# This only handles one instance of each coordinate type.
# The possible types are ''direction'', ''spectral'', ''stokes'',
# ''linear'' and ''tabular''.
# The first, second, trird and fourth axis are respectively,
# 'Right Ascension','Declination','Stokes' and 'Frequency'.
# To make a coordinate object, these things should be taken care
# of.Like to make a spectral coordinate, a 4D image should be used
# as the 4th axis is 'Frequency' and so on.
#
# It uses reference semantics for the individual coordinates,
# e.g. the following will work::
#
# cs = im.coordinates()
# cs["direction"].set_referencepixel([0.0,0.0])
# # or equivalent
# cs.get_coordinates("direction").set_referencepixel([0.0,0.0])
#
# """
#
# def __init__(self, rec):
# self._csys = rec
# self._names = []
# self._get_coordinatenames()
#
# def __str__(self):
# out = ""
# for coord in self:
# out += str(coord)
# return out
#
# def dict(self):
# return self._csys
#
# def summary(self):
# six.print_(str(self))
#
# def _get_coordinatenames(self):
# """Create ordered list of coordinate names
# """
# validnames = ("direction", "spectral", "linear", "stokes", "tabular")
# self._names = [""] * len(validnames)
# n = 0
# for key in self._csys.keys():
# for name in validnames:
# if key.startswith(name):
# idx = int(key[len(name):])
# self._names[idx] = name
# n += 1
# # reverse as we are c order in python
# self._names = self._names[:n][::-1]
#
# if len(self._names) == 0:
# raise LookupError("Coordinate record doesn't contain valid coordinates")
#
# def get_names(self):
# """Get the coordinate names
# """
# return self._names
#
# def __getitem__(self, name):
# # reverse index back to fortran order as the record is using this
# i = self._names[::-1].index(name)
# return eval("%scoordinate(self._csys['%s'])" % (name, name + str(i)))
#
# # alias
# get_coordinate = __getitem__
#
# def __setitem__(self, name, val):
# # reverse index back to fortran order as the record is using this
# i = self._names[::-1].index(name)
# assert isinstance(val, eval("%scoordinate" % name))
# self._csys[name + str(i)] = val._coord
#
# # alias
# set_coordinate = __setitem__
#
# def __iter__(self):
# for name in self._names:
# yield self.get_coordinate(name)
#
# def get_obsdate(self):
# return self._csys.get("obsdate", None)
#
# def get_observer(self):
# return self._csys.get("observer", None)
#
# def get_telescope(self):
# return self._csys.get("telescope", None)
#
# def get_referencepixel(self):
# return [coord.get_referencepixel() for coord in self]
#
# def set_referencepixel(self, values):
# for i, coord in enumerate(self):
# coord.set_referencepixel(values[i])
#
# def get_referencevalue(self):
# return [coord.get_referencevalue() for coord in self]
#
# def set_referencevalue(self, values):
# for i, coord in enumerate(self):
# coord.set_referencevalue(values[i])
#
# def get_increment(self):
# return [coord.get_increment() for coord in self]
#
# def set_increment(self, values):
# for i, coord in enumerate(self):
# coord.set_increment(values[i])
#
# def get_unit(self):
# return [coord.get_unit() for coord in self]
#
# def get_axes(self):
# return [coord.get_axes() for coord in self]
. Output only the next line. | return coordinatesystem(self._coordinates()) |
Given the following code snippet before the placeholder: <|code_start|># Convert Python value type to a glish-like type string
# as expected by the table code.
def _value_type_name(value):
if isinstance(value, bool):
return 'boolean'
if isinstance(value, integer_types):
return 'integer'
if isinstance(value, float):
return 'double'
if isinstance(value, complex):
return 'dcomplex'
if isinstance(value, string_types):
return 'string'
if isinstance(value, dict):
return 'record'
return 'unknown'
def _format_date(val, unit):
"""
Format dates.
:param val: Value (just the value, not a quantity)
:param unit: Unit. Should be 'rad' or 's'
:return: A string representation of this date.
>>> _format_date(4914741782.503475, 's')
"14-Aug-2014/14:03:03"
"""
if val == numpy.floor(val) and unit == 'd':
# Do not show time part if 0
<|code_end|>
, predict the next line using imports from the current file:
from six import string_types, integer_types
from ..quanta import quantity
import numpy
import re
and context including class names, function names, and sometimes code from other files:
# Path: casacore/quanta/quantity.py
# def quantity(*args):
# """Create a quantity. This can be from a scalar or vector.
#
# Example::
#
# q1 = quantity(1.0, "km/s")
# q2 = quantity("1km/s")
# q1 = quantity([1.0,2.0], "km/s")
#
# """
# if len(args) == 1:
# if isinstance(args[0], string_types):
# # use copy constructor to create quantity from string
# return Quantity(from_string(args[0]))
# elif isinstance(args[0], dict):
# if hasattr(args[0]["value"], "__len__"):
# return QuantVec(from_dict_v(args[0]))
# else:
# return Quantity(from_dict(args[0]))
# elif isinstance(args[0], Quantity) or isinstance(args[0], QuantVec):
# return args[0]
# else:
# raise TypeError("Invalid argument type for")
# else:
# if hasattr(args[0], "__len__"):
# return QuantVec(*args)
# else:
# return Quantity(*args)
. Output only the next line. | return quantity(val, unit).formatted('YMD_ONLY') |
Continue the code snippet: <|code_start|>
class ClusterKeysCommandMixin(KeysCommandMixin):
NODES_FLAGS = dict_merge(
{
'MOVE': NodeFlag.BLOCKED,
'RANDOMKEY': NodeFlag.RANDOM,
'SCAN': NodeFlag.ALL_MASTERS,
},
list_keys_to_dict(
['KEYS'],
NodeFlag.ALL_NODES
)
)
RESULT_CALLBACKS = {
'KEYS': merge_result,
'RANDOMKEY': first_key,
'SCAN': lambda res: res
}
async def rename(self, src, dst):
"""
Rename key ``src`` to ``dst``
Cluster impl:
This operation is no longer atomic because each key must be querried
then set in separate calls because they maybe will change cluster node
"""
if src == dst:
<|code_end|>
. Use current file imports:
import datetime
import time as mod_time
from aredis.exceptions import (ResponseError,
RedisError,
DataError)
from aredis.utils import (merge_result,
NodeFlag,
first_key,
b, dict_merge,
int_or_none,
bool_ok,
string_keys_to_dict,
list_keys_to_dict)
and context (classes, functions, or code) from other files:
# Path: aredis/exceptions.py
# class ResponseError(RedisError):
# pass
#
# class RedisError(Exception):
# pass
#
# class DataError(RedisError):
# pass
#
# Path: aredis/utils.py
# def merge_result(res):
# """
# Merges all items in `res` into a list.
#
# This command is used when sending a command to multiple nodes
# and they result from each node should be merged into a single list.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# result = set([])
#
# for _, v in res.items():
# for value in v:
# result.add(value)
#
# return list(result)
#
# class NodeFlag:
# BLOCKED = 'blocked'
# ALL_NODES = 'all-nodes'
# ALL_MASTERS = 'all-masters'
# RANDOM = 'random'
# SLOT_ID = 'slot-id'
#
# def first_key(res):
# """
# Returns the first result for the given command.
#
# If more then 1 result is returned then a `RedisClusterException` is raised.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# if len(res.keys()) != 1:
# raise RedisClusterException("More then 1 result from command")
#
# return list(res.values())[0]
#
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def int_or_none(response):
# if response is None:
# return None
# return int(response)
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
#
# def list_keys_to_dict(key_list, callback):
# return dict.fromkeys(key_list, callback)
. Output only the next line. | raise ResponseError("source and destination objects are the same") |
Using the snippet: <|code_start|> return await self.execute_command('RESTORE', *params)
async def sort(self, name, start=None, num=None, by=None, get=None,
desc=False, alpha=False, store=None, groups=False):
"""
Sorts and returns a list, set or sorted set at ``name``.
``start`` and ``num`` are for paginating sorted data
``by`` allows using an external key to weight and sort the items.
Use an "*" to indicate where in the key the item value is located
``get`` is for returning items from external keys rather than the
sorted data itself. Use an "*" to indicate where int he key
the item value is located
``desc`` is for reversing the sort
``alpha`` is for sorting lexicographically rather than numerically
``store`` is for storing the result of the sort into
the key ``store``
``groups`` if set to True and if ``get`` contains at least two
elements, sort will return a list of tuples, each containing the
values fetched from the arguments to ``get``.
"""
if (start is not None and num is None) or \
(num is not None and start is None):
<|code_end|>
, determine the next line of code. You have imports:
import datetime
import time as mod_time
from aredis.exceptions import (ResponseError,
RedisError,
DataError)
from aredis.utils import (merge_result,
NodeFlag,
first_key,
b, dict_merge,
int_or_none,
bool_ok,
string_keys_to_dict,
list_keys_to_dict)
and context (class names, function names, or code) available:
# Path: aredis/exceptions.py
# class ResponseError(RedisError):
# pass
#
# class RedisError(Exception):
# pass
#
# class DataError(RedisError):
# pass
#
# Path: aredis/utils.py
# def merge_result(res):
# """
# Merges all items in `res` into a list.
#
# This command is used when sending a command to multiple nodes
# and they result from each node should be merged into a single list.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# result = set([])
#
# for _, v in res.items():
# for value in v:
# result.add(value)
#
# return list(result)
#
# class NodeFlag:
# BLOCKED = 'blocked'
# ALL_NODES = 'all-nodes'
# ALL_MASTERS = 'all-masters'
# RANDOM = 'random'
# SLOT_ID = 'slot-id'
#
# def first_key(res):
# """
# Returns the first result for the given command.
#
# If more then 1 result is returned then a `RedisClusterException` is raised.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# if len(res.keys()) != 1:
# raise RedisClusterException("More then 1 result from command")
#
# return list(res.values())[0]
#
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def int_or_none(response):
# if response is None:
# return None
# return int(response)
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
#
# def list_keys_to_dict(key_list, callback):
# return dict.fromkeys(key_list, callback)
. Output only the next line. | raise RedisError("``start`` and ``num`` must both be specified") |
Predict the next line after this snippet: <|code_start|> pieces = [name]
if by is not None:
pieces.append(b('BY'))
pieces.append(by)
if start is not None and num is not None:
pieces.append(b('LIMIT'))
pieces.append(start)
pieces.append(num)
if get is not None:
# If get is a string assume we want to get a single value.
# Otherwise assume it's an interable and we want to get multiple
# values. We can't just iterate blindly because strings are
# iterable.
if isinstance(get, str):
pieces.append(b('GET'))
pieces.append(get)
else:
for g in get:
pieces.append(b('GET'))
pieces.append(g)
if desc:
pieces.append(b('DESC'))
if alpha:
pieces.append(b('ALPHA'))
if store is not None:
pieces.append(b('STORE'))
pieces.append(store)
if groups:
if not get or isinstance(get, str) or len(get) < 2:
<|code_end|>
using the current file's imports:
import datetime
import time as mod_time
from aredis.exceptions import (ResponseError,
RedisError,
DataError)
from aredis.utils import (merge_result,
NodeFlag,
first_key,
b, dict_merge,
int_or_none,
bool_ok,
string_keys_to_dict,
list_keys_to_dict)
and any relevant context from other files:
# Path: aredis/exceptions.py
# class ResponseError(RedisError):
# pass
#
# class RedisError(Exception):
# pass
#
# class DataError(RedisError):
# pass
#
# Path: aredis/utils.py
# def merge_result(res):
# """
# Merges all items in `res` into a list.
#
# This command is used when sending a command to multiple nodes
# and they result from each node should be merged into a single list.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# result = set([])
#
# for _, v in res.items():
# for value in v:
# result.add(value)
#
# return list(result)
#
# class NodeFlag:
# BLOCKED = 'blocked'
# ALL_NODES = 'all-nodes'
# ALL_MASTERS = 'all-masters'
# RANDOM = 'random'
# SLOT_ID = 'slot-id'
#
# def first_key(res):
# """
# Returns the first result for the given command.
#
# If more then 1 result is returned then a `RedisClusterException` is raised.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# if len(res.keys()) != 1:
# raise RedisClusterException("More then 1 result from command")
#
# return list(res.values())[0]
#
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def int_or_none(response):
# if response is None:
# return None
# return int(response)
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
#
# def list_keys_to_dict(key_list, callback):
# return dict.fromkeys(key_list, callback)
. Output only the next line. | raise DataError('when using "groups" the "get" argument ' |
Predict the next line for this snippet: <|code_start|> Incrementally return lists of key names. Also return a cursor
indicating the scan position.
``match`` allows for filtering the keys by pattern
``count`` allows for hint the minimum number of returns
"""
pieces = [cursor]
if match is not None:
pieces.extend([b('MATCH'), match])
if count is not None:
pieces.extend([b('COUNT'), count])
return await self.execute_command('SCAN', *pieces)
class ClusterKeysCommandMixin(KeysCommandMixin):
NODES_FLAGS = dict_merge(
{
'MOVE': NodeFlag.BLOCKED,
'RANDOMKEY': NodeFlag.RANDOM,
'SCAN': NodeFlag.ALL_MASTERS,
},
list_keys_to_dict(
['KEYS'],
NodeFlag.ALL_NODES
)
)
RESULT_CALLBACKS = {
<|code_end|>
with the help of current file imports:
import datetime
import time as mod_time
from aredis.exceptions import (ResponseError,
RedisError,
DataError)
from aredis.utils import (merge_result,
NodeFlag,
first_key,
b, dict_merge,
int_or_none,
bool_ok,
string_keys_to_dict,
list_keys_to_dict)
and context from other files:
# Path: aredis/exceptions.py
# class ResponseError(RedisError):
# pass
#
# class RedisError(Exception):
# pass
#
# class DataError(RedisError):
# pass
#
# Path: aredis/utils.py
# def merge_result(res):
# """
# Merges all items in `res` into a list.
#
# This command is used when sending a command to multiple nodes
# and they result from each node should be merged into a single list.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# result = set([])
#
# for _, v in res.items():
# for value in v:
# result.add(value)
#
# return list(result)
#
# class NodeFlag:
# BLOCKED = 'blocked'
# ALL_NODES = 'all-nodes'
# ALL_MASTERS = 'all-masters'
# RANDOM = 'random'
# SLOT_ID = 'slot-id'
#
# def first_key(res):
# """
# Returns the first result for the given command.
#
# If more then 1 result is returned then a `RedisClusterException` is raised.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# if len(res.keys()) != 1:
# raise RedisClusterException("More then 1 result from command")
#
# return list(res.values())[0]
#
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def int_or_none(response):
# if response is None:
# return None
# return int(response)
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
#
# def list_keys_to_dict(key_list, callback):
# return dict.fromkeys(key_list, callback)
, which may contain function names, class names, or code. Output only the next line. | 'KEYS': merge_result, |
Given the following code snippet before the placeholder: <|code_start|> async def wait(self, num_replicas, timeout):
"""
Redis synchronous replication
That returns the number of replicas that processed the query when
we finally have at least ``num_replicas``, or when the ``timeout`` was
reached.
"""
return await self.execute_command('WAIT', num_replicas, timeout)
async def scan(self, cursor=0, match=None, count=None):
"""
Incrementally return lists of key names. Also return a cursor
indicating the scan position.
``match`` allows for filtering the keys by pattern
``count`` allows for hint the minimum number of returns
"""
pieces = [cursor]
if match is not None:
pieces.extend([b('MATCH'), match])
if count is not None:
pieces.extend([b('COUNT'), count])
return await self.execute_command('SCAN', *pieces)
class ClusterKeysCommandMixin(KeysCommandMixin):
NODES_FLAGS = dict_merge(
{
<|code_end|>
, predict the next line using imports from the current file:
import datetime
import time as mod_time
from aredis.exceptions import (ResponseError,
RedisError,
DataError)
from aredis.utils import (merge_result,
NodeFlag,
first_key,
b, dict_merge,
int_or_none,
bool_ok,
string_keys_to_dict,
list_keys_to_dict)
and context including class names, function names, and sometimes code from other files:
# Path: aredis/exceptions.py
# class ResponseError(RedisError):
# pass
#
# class RedisError(Exception):
# pass
#
# class DataError(RedisError):
# pass
#
# Path: aredis/utils.py
# def merge_result(res):
# """
# Merges all items in `res` into a list.
#
# This command is used when sending a command to multiple nodes
# and they result from each node should be merged into a single list.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# result = set([])
#
# for _, v in res.items():
# for value in v:
# result.add(value)
#
# return list(result)
#
# class NodeFlag:
# BLOCKED = 'blocked'
# ALL_NODES = 'all-nodes'
# ALL_MASTERS = 'all-masters'
# RANDOM = 'random'
# SLOT_ID = 'slot-id'
#
# def first_key(res):
# """
# Returns the first result for the given command.
#
# If more then 1 result is returned then a `RedisClusterException` is raised.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# if len(res.keys()) != 1:
# raise RedisClusterException("More then 1 result from command")
#
# return list(res.values())[0]
#
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def int_or_none(response):
# if response is None:
# return None
# return int(response)
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
#
# def list_keys_to_dict(key_list, callback):
# return dict.fromkeys(key_list, callback)
. Output only the next line. | 'MOVE': NodeFlag.BLOCKED, |
Next line prediction: <|code_start|> indicating the scan position.
``match`` allows for filtering the keys by pattern
``count`` allows for hint the minimum number of returns
"""
pieces = [cursor]
if match is not None:
pieces.extend([b('MATCH'), match])
if count is not None:
pieces.extend([b('COUNT'), count])
return await self.execute_command('SCAN', *pieces)
class ClusterKeysCommandMixin(KeysCommandMixin):
NODES_FLAGS = dict_merge(
{
'MOVE': NodeFlag.BLOCKED,
'RANDOMKEY': NodeFlag.RANDOM,
'SCAN': NodeFlag.ALL_MASTERS,
},
list_keys_to_dict(
['KEYS'],
NodeFlag.ALL_NODES
)
)
RESULT_CALLBACKS = {
'KEYS': merge_result,
<|code_end|>
. Use current file imports:
(import datetime
import time as mod_time
from aredis.exceptions import (ResponseError,
RedisError,
DataError)
from aredis.utils import (merge_result,
NodeFlag,
first_key,
b, dict_merge,
int_or_none,
bool_ok,
string_keys_to_dict,
list_keys_to_dict))
and context including class names, function names, or small code snippets from other files:
# Path: aredis/exceptions.py
# class ResponseError(RedisError):
# pass
#
# class RedisError(Exception):
# pass
#
# class DataError(RedisError):
# pass
#
# Path: aredis/utils.py
# def merge_result(res):
# """
# Merges all items in `res` into a list.
#
# This command is used when sending a command to multiple nodes
# and they result from each node should be merged into a single list.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# result = set([])
#
# for _, v in res.items():
# for value in v:
# result.add(value)
#
# return list(result)
#
# class NodeFlag:
# BLOCKED = 'blocked'
# ALL_NODES = 'all-nodes'
# ALL_MASTERS = 'all-masters'
# RANDOM = 'random'
# SLOT_ID = 'slot-id'
#
# def first_key(res):
# """
# Returns the first result for the given command.
#
# If more then 1 result is returned then a `RedisClusterException` is raised.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# if len(res.keys()) != 1:
# raise RedisClusterException("More then 1 result from command")
#
# return list(res.values())[0]
#
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def int_or_none(response):
# if response is None:
# return None
# return int(response)
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
#
# def list_keys_to_dict(key_list, callback):
# return dict.fromkeys(key_list, callback)
. Output only the next line. | 'RANDOMKEY': first_key, |
Based on the snippet: <|code_start|> """
Sorts and returns a list, set or sorted set at ``name``.
``start`` and ``num`` are for paginating sorted data
``by`` allows using an external key to weight and sort the items.
Use an "*" to indicate where in the key the item value is located
``get`` is for returning items from external keys rather than the
sorted data itself. Use an "*" to indicate where int he key
the item value is located
``desc`` is for reversing the sort
``alpha`` is for sorting lexicographically rather than numerically
``store`` is for storing the result of the sort into
the key ``store``
``groups`` if set to True and if ``get`` contains at least two
elements, sort will return a list of tuples, each containing the
values fetched from the arguments to ``get``.
"""
if (start is not None and num is None) or \
(num is not None and start is None):
raise RedisError("``start`` and ``num`` must both be specified")
pieces = [name]
if by is not None:
<|code_end|>
, predict the immediate next line with the help of imports:
import datetime
import time as mod_time
from aredis.exceptions import (ResponseError,
RedisError,
DataError)
from aredis.utils import (merge_result,
NodeFlag,
first_key,
b, dict_merge,
int_or_none,
bool_ok,
string_keys_to_dict,
list_keys_to_dict)
and context (classes, functions, sometimes code) from other files:
# Path: aredis/exceptions.py
# class ResponseError(RedisError):
# pass
#
# class RedisError(Exception):
# pass
#
# class DataError(RedisError):
# pass
#
# Path: aredis/utils.py
# def merge_result(res):
# """
# Merges all items in `res` into a list.
#
# This command is used when sending a command to multiple nodes
# and they result from each node should be merged into a single list.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# result = set([])
#
# for _, v in res.items():
# for value in v:
# result.add(value)
#
# return list(result)
#
# class NodeFlag:
# BLOCKED = 'blocked'
# ALL_NODES = 'all-nodes'
# ALL_MASTERS = 'all-masters'
# RANDOM = 'random'
# SLOT_ID = 'slot-id'
#
# def first_key(res):
# """
# Returns the first result for the given command.
#
# If more then 1 result is returned then a `RedisClusterException` is raised.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# if len(res.keys()) != 1:
# raise RedisClusterException("More then 1 result from command")
#
# return list(res.values())[0]
#
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def int_or_none(response):
# if response is None:
# return None
# return int(response)
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
#
# def list_keys_to_dict(key_list, callback):
# return dict.fromkeys(key_list, callback)
. Output only the next line. | pieces.append(b('BY')) |
Continue the code snippet: <|code_start|>
def sort_return_tuples(response, **options):
"""
If ``groups`` is specified, return the response as a list of
n-element tuples with n being the value found in options['groups']
"""
if not response or not options['groups']:
return response
n = options['groups']
return list(zip(*[response[i::n] for i in range(n)]))
def parse_object(response, infotype):
"""Parse the results of an OBJECT command"""
if infotype in ('idletime', 'refcount'):
return int_or_none(response)
return response
def parse_scan(response, **options):
cursor, r = response
return int(cursor), r
class KeysCommandMixin:
<|code_end|>
. Use current file imports:
import datetime
import time as mod_time
from aredis.exceptions import (ResponseError,
RedisError,
DataError)
from aredis.utils import (merge_result,
NodeFlag,
first_key,
b, dict_merge,
int_or_none,
bool_ok,
string_keys_to_dict,
list_keys_to_dict)
and context (classes, functions, or code) from other files:
# Path: aredis/exceptions.py
# class ResponseError(RedisError):
# pass
#
# class RedisError(Exception):
# pass
#
# class DataError(RedisError):
# pass
#
# Path: aredis/utils.py
# def merge_result(res):
# """
# Merges all items in `res` into a list.
#
# This command is used when sending a command to multiple nodes
# and they result from each node should be merged into a single list.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# result = set([])
#
# for _, v in res.items():
# for value in v:
# result.add(value)
#
# return list(result)
#
# class NodeFlag:
# BLOCKED = 'blocked'
# ALL_NODES = 'all-nodes'
# ALL_MASTERS = 'all-masters'
# RANDOM = 'random'
# SLOT_ID = 'slot-id'
#
# def first_key(res):
# """
# Returns the first result for the given command.
#
# If more then 1 result is returned then a `RedisClusterException` is raised.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# if len(res.keys()) != 1:
# raise RedisClusterException("More then 1 result from command")
#
# return list(res.values())[0]
#
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def int_or_none(response):
# if response is None:
# return None
# return int(response)
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
#
# def list_keys_to_dict(key_list, callback):
# return dict.fromkeys(key_list, callback)
. Output only the next line. | RESPONSE_CALLBACKS = dict_merge( |
Predict the next line after this snippet: <|code_start|>
def sort_return_tuples(response, **options):
"""
If ``groups`` is specified, return the response as a list of
n-element tuples with n being the value found in options['groups']
"""
if not response or not options['groups']:
return response
n = options['groups']
return list(zip(*[response[i::n] for i in range(n)]))
def parse_object(response, infotype):
"""Parse the results of an OBJECT command"""
if infotype in ('idletime', 'refcount'):
<|code_end|>
using the current file's imports:
import datetime
import time as mod_time
from aredis.exceptions import (ResponseError,
RedisError,
DataError)
from aredis.utils import (merge_result,
NodeFlag,
first_key,
b, dict_merge,
int_or_none,
bool_ok,
string_keys_to_dict,
list_keys_to_dict)
and any relevant context from other files:
# Path: aredis/exceptions.py
# class ResponseError(RedisError):
# pass
#
# class RedisError(Exception):
# pass
#
# class DataError(RedisError):
# pass
#
# Path: aredis/utils.py
# def merge_result(res):
# """
# Merges all items in `res` into a list.
#
# This command is used when sending a command to multiple nodes
# and they result from each node should be merged into a single list.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# result = set([])
#
# for _, v in res.items():
# for value in v:
# result.add(value)
#
# return list(result)
#
# class NodeFlag:
# BLOCKED = 'blocked'
# ALL_NODES = 'all-nodes'
# ALL_MASTERS = 'all-masters'
# RANDOM = 'random'
# SLOT_ID = 'slot-id'
#
# def first_key(res):
# """
# Returns the first result for the given command.
#
# If more then 1 result is returned then a `RedisClusterException` is raised.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# if len(res.keys()) != 1:
# raise RedisClusterException("More then 1 result from command")
#
# return list(res.values())[0]
#
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def int_or_none(response):
# if response is None:
# return None
# return int(response)
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
#
# def list_keys_to_dict(key_list, callback):
# return dict.fromkeys(key_list, callback)
. Output only the next line. | return int_or_none(response) |
Using the snippet: <|code_start|> return response
n = options['groups']
return list(zip(*[response[i::n] for i in range(n)]))
def parse_object(response, infotype):
"""Parse the results of an OBJECT command"""
if infotype in ('idletime', 'refcount'):
return int_or_none(response)
return response
def parse_scan(response, **options):
cursor, r = response
return int(cursor), r
class KeysCommandMixin:
RESPONSE_CALLBACKS = dict_merge(
string_keys_to_dict(
'EXISTS EXPIRE EXPIREAT '
'MOVE PERSIST RENAMENX', bool
),
{
'DEL': int,
'SORT': sort_return_tuples,
'OBJECT': parse_object,
'RANDOMKEY': lambda r: r and r or None,
'SCAN': parse_scan,
<|code_end|>
, determine the next line of code. You have imports:
import datetime
import time as mod_time
from aredis.exceptions import (ResponseError,
RedisError,
DataError)
from aredis.utils import (merge_result,
NodeFlag,
first_key,
b, dict_merge,
int_or_none,
bool_ok,
string_keys_to_dict,
list_keys_to_dict)
and context (class names, function names, or code) available:
# Path: aredis/exceptions.py
# class ResponseError(RedisError):
# pass
#
# class RedisError(Exception):
# pass
#
# class DataError(RedisError):
# pass
#
# Path: aredis/utils.py
# def merge_result(res):
# """
# Merges all items in `res` into a list.
#
# This command is used when sending a command to multiple nodes
# and they result from each node should be merged into a single list.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# result = set([])
#
# for _, v in res.items():
# for value in v:
# result.add(value)
#
# return list(result)
#
# class NodeFlag:
# BLOCKED = 'blocked'
# ALL_NODES = 'all-nodes'
# ALL_MASTERS = 'all-masters'
# RANDOM = 'random'
# SLOT_ID = 'slot-id'
#
# def first_key(res):
# """
# Returns the first result for the given command.
#
# If more then 1 result is returned then a `RedisClusterException` is raised.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# if len(res.keys()) != 1:
# raise RedisClusterException("More then 1 result from command")
#
# return list(res.values())[0]
#
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def int_or_none(response):
# if response is None:
# return None
# return int(response)
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
#
# def list_keys_to_dict(key_list, callback):
# return dict.fromkeys(key_list, callback)
. Output only the next line. | 'RENAME': bool_ok, |
Using the snippet: <|code_start|>
def sort_return_tuples(response, **options):
"""
If ``groups`` is specified, return the response as a list of
n-element tuples with n being the value found in options['groups']
"""
if not response or not options['groups']:
return response
n = options['groups']
return list(zip(*[response[i::n] for i in range(n)]))
def parse_object(response, infotype):
"""Parse the results of an OBJECT command"""
if infotype in ('idletime', 'refcount'):
return int_or_none(response)
return response
def parse_scan(response, **options):
cursor, r = response
return int(cursor), r
class KeysCommandMixin:
RESPONSE_CALLBACKS = dict_merge(
<|code_end|>
, determine the next line of code. You have imports:
import datetime
import time as mod_time
from aredis.exceptions import (ResponseError,
RedisError,
DataError)
from aredis.utils import (merge_result,
NodeFlag,
first_key,
b, dict_merge,
int_or_none,
bool_ok,
string_keys_to_dict,
list_keys_to_dict)
and context (class names, function names, or code) available:
# Path: aredis/exceptions.py
# class ResponseError(RedisError):
# pass
#
# class RedisError(Exception):
# pass
#
# class DataError(RedisError):
# pass
#
# Path: aredis/utils.py
# def merge_result(res):
# """
# Merges all items in `res` into a list.
#
# This command is used when sending a command to multiple nodes
# and they result from each node should be merged into a single list.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# result = set([])
#
# for _, v in res.items():
# for value in v:
# result.add(value)
#
# return list(result)
#
# class NodeFlag:
# BLOCKED = 'blocked'
# ALL_NODES = 'all-nodes'
# ALL_MASTERS = 'all-masters'
# RANDOM = 'random'
# SLOT_ID = 'slot-id'
#
# def first_key(res):
# """
# Returns the first result for the given command.
#
# If more then 1 result is returned then a `RedisClusterException` is raised.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# if len(res.keys()) != 1:
# raise RedisClusterException("More then 1 result from command")
#
# return list(res.values())[0]
#
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def int_or_none(response):
# if response is None:
# return None
# return int(response)
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
#
# def list_keys_to_dict(key_list, callback):
# return dict.fromkeys(key_list, callback)
. Output only the next line. | string_keys_to_dict( |
Given snippet: <|code_start|> we finally have at least ``num_replicas``, or when the ``timeout`` was
reached.
"""
return await self.execute_command('WAIT', num_replicas, timeout)
async def scan(self, cursor=0, match=None, count=None):
"""
Incrementally return lists of key names. Also return a cursor
indicating the scan position.
``match`` allows for filtering the keys by pattern
``count`` allows for hint the minimum number of returns
"""
pieces = [cursor]
if match is not None:
pieces.extend([b('MATCH'), match])
if count is not None:
pieces.extend([b('COUNT'), count])
return await self.execute_command('SCAN', *pieces)
class ClusterKeysCommandMixin(KeysCommandMixin):
NODES_FLAGS = dict_merge(
{
'MOVE': NodeFlag.BLOCKED,
'RANDOMKEY': NodeFlag.RANDOM,
'SCAN': NodeFlag.ALL_MASTERS,
},
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import datetime
import time as mod_time
from aredis.exceptions import (ResponseError,
RedisError,
DataError)
from aredis.utils import (merge_result,
NodeFlag,
first_key,
b, dict_merge,
int_or_none,
bool_ok,
string_keys_to_dict,
list_keys_to_dict)
and context:
# Path: aredis/exceptions.py
# class ResponseError(RedisError):
# pass
#
# class RedisError(Exception):
# pass
#
# class DataError(RedisError):
# pass
#
# Path: aredis/utils.py
# def merge_result(res):
# """
# Merges all items in `res` into a list.
#
# This command is used when sending a command to multiple nodes
# and they result from each node should be merged into a single list.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# result = set([])
#
# for _, v in res.items():
# for value in v:
# result.add(value)
#
# return list(result)
#
# class NodeFlag:
# BLOCKED = 'blocked'
# ALL_NODES = 'all-nodes'
# ALL_MASTERS = 'all-masters'
# RANDOM = 'random'
# SLOT_ID = 'slot-id'
#
# def first_key(res):
# """
# Returns the first result for the given command.
#
# If more then 1 result is returned then a `RedisClusterException` is raised.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# if len(res.keys()) != 1:
# raise RedisClusterException("More then 1 result from command")
#
# return list(res.values())[0]
#
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def int_or_none(response):
# if response is None:
# return None
# return int(response)
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
#
# def list_keys_to_dict(key_list, callback):
# return dict.fromkeys(key_list, callback)
which might include code, classes, or functions. Output only the next line. | list_keys_to_dict( |
Continue the code snippet: <|code_start|> # the properly native Python value.
f = [nativestr]
f += [cast[o] for o in ['withdist', 'withhash', 'withcoord'] if options[o]]
return [
list(map(lambda fv: fv[0](fv[1]), zip(f, r))) for r in response_list
]
class GeoCommandMixin:
RESPONSE_CALLBACKS = {
'GEOPOS': lambda r: list(map(lambda ll: (float(ll[0]),
float(ll[1]))
if ll is not None else None, r)),
'GEOHASH': lambda r: list(r),
'GEORADIUS': parse_georadius_generic,
'GEORADIUSBYMEMBER': parse_georadius_generic,
'GEODIST': float,
'GEOADD': int
}
# GEO COMMANDS
async def geoadd(self, name, *values):
"""
Add the specified geospatial items to the specified key identified
by the ``name`` argument. The Geospatial items are given as ordered
members of the ``values`` argument, each item or place is formed by
the triad latitude, longitude and name.
"""
if len(values) % 3 != 0:
<|code_end|>
. Use current file imports:
from aredis.exceptions import RedisError
from aredis.utils import b, nativestr
and context (classes, functions, or code) from other files:
# Path: aredis/exceptions.py
# class RedisError(Exception):
# pass
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
. Output only the next line. | raise RedisError("GEOADD requires places with lon, lat and name" |
Predict the next line after this snippet: <|code_start|> count=count, sort=sort, store=store,
store_dist=store_dist)
async def georadiusbymember(self, name, member, radius, unit=None,
withdist=False, withcoord=False, withhash=False,
count=None, sort=None, store=None, store_dist=None):
"""
This command is exactly like ``georadius`` with the sole difference
that instead of taking, as the center of the area to query, a longitude
and latitude value, it takes the name of a member already existing
inside the geospatial index represented by the sorted set.
"""
return await self._georadiusgeneric('GEORADIUSBYMEMBER',
name, member, radius, unit=unit,
withdist=withdist, withcoord=withcoord,
withhash=withhash, count=count,
sort=sort, store=store,
store_dist=store_dist)
async def _georadiusgeneric(self, command, *args, **kwargs):
pieces = list(args)
if kwargs['unit'] and kwargs['unit'] not in ('m', 'km', 'mi', 'ft'):
raise RedisError("GEORADIUS invalid unit")
elif kwargs['unit']:
pieces.append(kwargs['unit'])
else:
pieces.append('m', )
for token in ('withdist', 'withcoord', 'withhash'):
if kwargs[token]:
<|code_end|>
using the current file's imports:
from aredis.exceptions import RedisError
from aredis.utils import b, nativestr
and any relevant context from other files:
# Path: aredis/exceptions.py
# class RedisError(Exception):
# pass
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
. Output only the next line. | pieces.append(b(token.upper())) |
Given the code snippet: <|code_start|>
def parse_georadius_generic(response, **options):
if options['store'] or options['store_dist']:
# `store` and `store_diff` cant be combined
# with other command arguments.
return response
if type(response) != list:
response_list = [response]
else:
response_list = response
if not options['withdist'] and not options['withcoord']\
and not options['withhash']:
# just a bunch of places
<|code_end|>
, generate the next line using the imports in this file:
from aredis.exceptions import RedisError
from aredis.utils import b, nativestr
and context (functions, classes, or occasionally code) from other files:
# Path: aredis/exceptions.py
# class RedisError(Exception):
# pass
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
. Output only the next line. | return [nativestr(r) for r in response_list] |
Predict the next line after this snippet: <|code_start|> return await self.execute_command('HINCRBYFLOAT', name, key, amount)
async def hkeys(self, name):
"""Returns the list of keys within hash ``name``"""
return await self.execute_command('HKEYS', name)
async def hlen(self, name):
"""Returns the number of elements in hash ``name``"""
return await self.execute_command('HLEN', name)
async def hset(self, name, key, value):
"""
Sets ``key`` to ``value`` within hash ``name``
Returns 1 if HSET created a new field, otherwise 0
"""
return await self.execute_command('HSET', name, key, value)
async def hsetnx(self, name, key, value):
"""
Sets ``key`` to ``value`` within hash ``name`` if ``key`` does not
exist. Returns 1 if HSETNX created a field, otherwise 0.
"""
return await self.execute_command('HSETNX', name, key, value)
async def hmset(self, name, mapping):
"""
Sets key to value within hash ``name`` for each corresponding
key and value from the ``mapping`` dict.
"""
if not mapping:
<|code_end|>
using the current file's imports:
from aredis.exceptions import DataError
from aredis.utils import (b, dict_merge,
iteritems,
first_key,
string_keys_to_dict,
list_or_args,
pairs_to_dict)
and any relevant context from other files:
# Path: aredis/exceptions.py
# class DataError(RedisError):
# pass
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def iteritems(x):
# return iter(x.items())
#
# def first_key(res):
# """
# Returns the first result for the given command.
#
# If more then 1 result is returned then a `RedisClusterException` is raised.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# if len(res.keys()) != 1:
# raise RedisClusterException("More then 1 result from command")
#
# return list(res.values())[0]
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
#
# def list_or_args(keys, args):
# # returns a single list combining keys and args
# try:
# iter(keys)
# # a string or bytes instance can be iterated, but indicates
# # keys wasn't passed as a list
# if isinstance(keys, (str, bytes)):
# keys = [keys]
# except TypeError:
# keys = [keys]
# if args:
# keys.extend(args)
# return keys
#
# def pairs_to_dict(response):
# """Creates a dict given a list of key/value pairs"""
# it = iter(response)
# return dict(zip(it, it))
. Output only the next line. | raise DataError("'hmset' with 'mapping' of length 0") |
Predict the next line after this snippet: <|code_start|> Sets key to value within hash ``name`` for each corresponding
key and value from the ``mapping`` dict.
"""
if not mapping:
raise DataError("'hmset' with 'mapping' of length 0")
items = []
for pair in iteritems(mapping):
items.extend(pair)
return await self.execute_command('HMSET', name, *items)
async def hmget(self, name, keys, *args):
"""Returns a list of values ordered identically to ``keys``"""
args = list_or_args(keys, args)
return await self.execute_command('HMGET', name, *args)
async def hvals(self, name):
"""Returns the list of values within hash ``name``"""
return await self.execute_command('HVALS', name)
async def hscan(self, name, cursor=0, match=None, count=None):
"""
Incrementallys return key/value slices in a hash. Also returns a
cursor pointing to the scan position.
``match`` allows for filtering the keys by pattern
``count`` allows for hint the minimum number of returns
"""
pieces = [name, cursor]
if match is not None:
<|code_end|>
using the current file's imports:
from aredis.exceptions import DataError
from aredis.utils import (b, dict_merge,
iteritems,
first_key,
string_keys_to_dict,
list_or_args,
pairs_to_dict)
and any relevant context from other files:
# Path: aredis/exceptions.py
# class DataError(RedisError):
# pass
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def iteritems(x):
# return iter(x.items())
#
# def first_key(res):
# """
# Returns the first result for the given command.
#
# If more then 1 result is returned then a `RedisClusterException` is raised.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# if len(res.keys()) != 1:
# raise RedisClusterException("More then 1 result from command")
#
# return list(res.values())[0]
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
#
# def list_or_args(keys, args):
# # returns a single list combining keys and args
# try:
# iter(keys)
# # a string or bytes instance can be iterated, but indicates
# # keys wasn't passed as a list
# if isinstance(keys, (str, bytes)):
# keys = [keys]
# except TypeError:
# keys = [keys]
# if args:
# keys.extend(args)
# return keys
#
# def pairs_to_dict(response):
# """Creates a dict given a list of key/value pairs"""
# it = iter(response)
# return dict(zip(it, it))
. Output only the next line. | pieces.extend([b('MATCH'), match]) |
Based on the snippet: <|code_start|>
def parse_hscan(response, **options):
cursor, r = response
return int(cursor), r and pairs_to_dict(r) or {}
class HashCommandMixin:
<|code_end|>
, predict the immediate next line with the help of imports:
from aredis.exceptions import DataError
from aredis.utils import (b, dict_merge,
iteritems,
first_key,
string_keys_to_dict,
list_or_args,
pairs_to_dict)
and context (classes, functions, sometimes code) from other files:
# Path: aredis/exceptions.py
# class DataError(RedisError):
# pass
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def iteritems(x):
# return iter(x.items())
#
# def first_key(res):
# """
# Returns the first result for the given command.
#
# If more then 1 result is returned then a `RedisClusterException` is raised.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# if len(res.keys()) != 1:
# raise RedisClusterException("More then 1 result from command")
#
# return list(res.values())[0]
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
#
# def list_or_args(keys, args):
# # returns a single list combining keys and args
# try:
# iter(keys)
# # a string or bytes instance can be iterated, but indicates
# # keys wasn't passed as a list
# if isinstance(keys, (str, bytes)):
# keys = [keys]
# except TypeError:
# keys = [keys]
# if args:
# keys.extend(args)
# return keys
#
# def pairs_to_dict(response):
# """Creates a dict given a list of key/value pairs"""
# it = iter(response)
# return dict(zip(it, it))
. Output only the next line. | RESPONSE_CALLBACKS = dict_merge( |
Continue the code snippet: <|code_start|> async def hkeys(self, name):
"""Returns the list of keys within hash ``name``"""
return await self.execute_command('HKEYS', name)
async def hlen(self, name):
"""Returns the number of elements in hash ``name``"""
return await self.execute_command('HLEN', name)
async def hset(self, name, key, value):
"""
Sets ``key`` to ``value`` within hash ``name``
Returns 1 if HSET created a new field, otherwise 0
"""
return await self.execute_command('HSET', name, key, value)
async def hsetnx(self, name, key, value):
"""
Sets ``key`` to ``value`` within hash ``name`` if ``key`` does not
exist. Returns 1 if HSETNX created a field, otherwise 0.
"""
return await self.execute_command('HSETNX', name, key, value)
async def hmset(self, name, mapping):
"""
Sets key to value within hash ``name`` for each corresponding
key and value from the ``mapping`` dict.
"""
if not mapping:
raise DataError("'hmset' with 'mapping' of length 0")
items = []
<|code_end|>
. Use current file imports:
from aredis.exceptions import DataError
from aredis.utils import (b, dict_merge,
iteritems,
first_key,
string_keys_to_dict,
list_or_args,
pairs_to_dict)
and context (classes, functions, or code) from other files:
# Path: aredis/exceptions.py
# class DataError(RedisError):
# pass
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def iteritems(x):
# return iter(x.items())
#
# def first_key(res):
# """
# Returns the first result for the given command.
#
# If more then 1 result is returned then a `RedisClusterException` is raised.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# if len(res.keys()) != 1:
# raise RedisClusterException("More then 1 result from command")
#
# return list(res.values())[0]
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
#
# def list_or_args(keys, args):
# # returns a single list combining keys and args
# try:
# iter(keys)
# # a string or bytes instance can be iterated, but indicates
# # keys wasn't passed as a list
# if isinstance(keys, (str, bytes)):
# keys = [keys]
# except TypeError:
# keys = [keys]
# if args:
# keys.extend(args)
# return keys
#
# def pairs_to_dict(response):
# """Creates a dict given a list of key/value pairs"""
# it = iter(response)
# return dict(zip(it, it))
. Output only the next line. | for pair in iteritems(mapping): |
Next line prediction: <|code_start|> return await self.execute_command('HVALS', name)
async def hscan(self, name, cursor=0, match=None, count=None):
"""
Incrementallys return key/value slices in a hash. Also returns a
cursor pointing to the scan position.
``match`` allows for filtering the keys by pattern
``count`` allows for hint the minimum number of returns
"""
pieces = [name, cursor]
if match is not None:
pieces.extend([b('MATCH'), match])
if count is not None:
pieces.extend([b('COUNT'), count])
return await self.execute_command('HSCAN', *pieces)
async def hstrlen(self, name, key):
"""
Returns the string length of the value associated
with field in the hash stored at key.
If the key or the field do not exist, 0 is returned.
"""
return await self.execute_command('HSTRLEN', name, key)
class ClusterHashCommandMixin(HashCommandMixin):
RESULT_CALLBACKS = {
<|code_end|>
. Use current file imports:
(from aredis.exceptions import DataError
from aredis.utils import (b, dict_merge,
iteritems,
first_key,
string_keys_to_dict,
list_or_args,
pairs_to_dict))
and context including class names, function names, or small code snippets from other files:
# Path: aredis/exceptions.py
# class DataError(RedisError):
# pass
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def iteritems(x):
# return iter(x.items())
#
# def first_key(res):
# """
# Returns the first result for the given command.
#
# If more then 1 result is returned then a `RedisClusterException` is raised.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# if len(res.keys()) != 1:
# raise RedisClusterException("More then 1 result from command")
#
# return list(res.values())[0]
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
#
# def list_or_args(keys, args):
# # returns a single list combining keys and args
# try:
# iter(keys)
# # a string or bytes instance can be iterated, but indicates
# # keys wasn't passed as a list
# if isinstance(keys, (str, bytes)):
# keys = [keys]
# except TypeError:
# keys = [keys]
# if args:
# keys.extend(args)
# return keys
#
# def pairs_to_dict(response):
# """Creates a dict given a list of key/value pairs"""
# it = iter(response)
# return dict(zip(it, it))
. Output only the next line. | 'HSCAN': first_key |
Predict the next line after this snippet: <|code_start|>
def parse_hscan(response, **options):
cursor, r = response
return int(cursor), r and pairs_to_dict(r) or {}
class HashCommandMixin:
RESPONSE_CALLBACKS = dict_merge(
<|code_end|>
using the current file's imports:
from aredis.exceptions import DataError
from aredis.utils import (b, dict_merge,
iteritems,
first_key,
string_keys_to_dict,
list_or_args,
pairs_to_dict)
and any relevant context from other files:
# Path: aredis/exceptions.py
# class DataError(RedisError):
# pass
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def iteritems(x):
# return iter(x.items())
#
# def first_key(res):
# """
# Returns the first result for the given command.
#
# If more then 1 result is returned then a `RedisClusterException` is raised.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# if len(res.keys()) != 1:
# raise RedisClusterException("More then 1 result from command")
#
# return list(res.values())[0]
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
#
# def list_or_args(keys, args):
# # returns a single list combining keys and args
# try:
# iter(keys)
# # a string or bytes instance can be iterated, but indicates
# # keys wasn't passed as a list
# if isinstance(keys, (str, bytes)):
# keys = [keys]
# except TypeError:
# keys = [keys]
# if args:
# keys.extend(args)
# return keys
#
# def pairs_to_dict(response):
# """Creates a dict given a list of key/value pairs"""
# it = iter(response)
# return dict(zip(it, it))
. Output only the next line. | string_keys_to_dict('HDEL HLEN', int), |
Here is a snippet: <|code_start|> return await self.execute_command('HLEN', name)
async def hset(self, name, key, value):
"""
Sets ``key`` to ``value`` within hash ``name``
Returns 1 if HSET created a new field, otherwise 0
"""
return await self.execute_command('HSET', name, key, value)
async def hsetnx(self, name, key, value):
"""
Sets ``key`` to ``value`` within hash ``name`` if ``key`` does not
exist. Returns 1 if HSETNX created a field, otherwise 0.
"""
return await self.execute_command('HSETNX', name, key, value)
async def hmset(self, name, mapping):
"""
Sets key to value within hash ``name`` for each corresponding
key and value from the ``mapping`` dict.
"""
if not mapping:
raise DataError("'hmset' with 'mapping' of length 0")
items = []
for pair in iteritems(mapping):
items.extend(pair)
return await self.execute_command('HMSET', name, *items)
async def hmget(self, name, keys, *args):
"""Returns a list of values ordered identically to ``keys``"""
<|code_end|>
. Write the next line using the current file imports:
from aredis.exceptions import DataError
from aredis.utils import (b, dict_merge,
iteritems,
first_key,
string_keys_to_dict,
list_or_args,
pairs_to_dict)
and context from other files:
# Path: aredis/exceptions.py
# class DataError(RedisError):
# pass
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def iteritems(x):
# return iter(x.items())
#
# def first_key(res):
# """
# Returns the first result for the given command.
#
# If more then 1 result is returned then a `RedisClusterException` is raised.
# """
# if not isinstance(res, dict):
# raise ValueError('Value should be of dict type')
#
# if len(res.keys()) != 1:
# raise RedisClusterException("More then 1 result from command")
#
# return list(res.values())[0]
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
#
# def list_or_args(keys, args):
# # returns a single list combining keys and args
# try:
# iter(keys)
# # a string or bytes instance can be iterated, but indicates
# # keys wasn't passed as a list
# if isinstance(keys, (str, bytes)):
# keys = [keys]
# except TypeError:
# keys = [keys]
# if args:
# keys.extend(args)
# return keys
#
# def pairs_to_dict(response):
# """Creates a dict given a list of key/value pairs"""
# it = iter(response)
# return dict(zip(it, it))
, which may include functions, classes, or code. Output only the next line. | args = list_or_args(keys, args) |
Predict the next line after this snippet: <|code_start|> await lock.release()
@pytest.mark.asyncio()
async def test_float_timeout(self, r):
lock = self.get_lock(r, 'foo', timeout=9.5)
assert await lock.acquire(blocking=False)
assert 8 < await r.pttl('foo') <= 9500
await lock.release()
@pytest.mark.asyncio()
async def test_blocking_timeout(self, r):
lock1 = self.get_lock(r, 'foo', timeout=3)
assert await lock1.acquire(blocking=False)
lock2 = self.get_lock(r, 'foo', timeout=3, blocking_timeout=0.2)
start = time.time()
assert not await lock2.acquire()
assert (time.time() - start) > 0.2
await lock1.release()
@pytest.mark.asyncio()
async def test_context_manager(self, r):
# blocking_timeout prevents a deadlock if the lock can't be acquired
# for some reason
async with self.get_lock(r, 'foo', timeout=3, blocking_timeout=0.2) as lock:
assert await r.get('foo') == lock.local.get()
assert await r.get('foo') is None
@pytest.mark.asyncio()
async def test_high_sleep_raises_error(self, r):
"If sleep is higher than timeout, it should raise an error"
<|code_end|>
using the current file's imports:
import pytest
import time
from aredis.exceptions import LockError
from aredis.lock import ClusterLock
and any relevant context from other files:
# Path: aredis/exceptions.py
# class LockError(RedisError, ValueError):
# """Errors acquiring or releasing a lock"""
# # NOTE: For backwards compatability, this class derives from ValueError.
# # This was originally chosen to behave like threading.Lock.
# pass
#
# Path: aredis/lock.py
# class ClusterLock(LuaLock):
# """
# Cluster lock is supposed to solve lock problem in redis cluster.
# Since high availability is provided by redis cluster using master-slave model,
# the kind of lock aims to solve the fail-over problem referred in distributed lock
# post given by redis official.
#
# Why not use Redlock algorithm provided by official directly?
# It is impossible to make a key hashed to different nodes
# in a redis cluster and hard to generate keys
# in a specific rule and make sure they do not migrated in cluster.
# In the worst situation, all key slots may exists in one node.
# Then the availability will be the same as one key in one node.
# For more discussion please see:
# https://github.com/NoneGG/aredis/issues/55
#
# My solution is to take advantage of `READONLY` mode of slaves to ensure
# the lock key is synced from master to N/2 + 1 of its slaves to avoid the fail-over problem.
# Since it is a single-key solution, the migration problem also do no matter.
#
# Please read these article below before using this cluster lock in your app.
# https://redis.io/topics/distlock
# http://martin.kleppmann.com/2016/02/08/how-to-do-distributed-locking.html
# http://antirez.com/news/101
# """
#
# def __init__(self, *args, **kwargs):
# super(ClusterLock, self).__init__(*args, **kwargs)
# if not self.timeout:
# raise LockError('timeout must be provided for cluster lock')
#
# async def check_lock_in_slaves(self, token):
# node_manager = self.redis.connection_pool.nodes
# slot = node_manager.keyslot(self.name)
# master_node_id = node_manager.node_from_slot(slot)['node_id']
# slave_nodes = await self.redis.cluster_slaves(master_node_id)
# count, quorum = 0, (len(slave_nodes) // 2) + 1
# conn_kwargs = self.redis.connection_pool.connection_kwargs
# conn_kwargs['readonly'] = True
# for node in slave_nodes:
# try:
# # todo: a little bit dirty here, try to reuse StrictRedis later
# # todo: it may be optimized by using a new connection pool
# conn = ClusterConnection(host=node['host'], port=node['port'], **conn_kwargs)
# await conn.send_command('get', self.name)
# res = await conn.read_response()
# if res == token:
# count += 1
# if count >= quorum:
# return True
# except Exception as exc:
# warnings.warn('error {} during check lock {} status in slave nodes'.format(exc, self.name))
# return False
#
# async def acquire(self, blocking=None, blocking_timeout=None):
# """
# Use Redis to hold a shared, distributed lock named ``name``.
# Returns True once the lock is acquired.
#
# If ``blocking`` is False, always return immediately. If the lock
# was acquired, return True, otherwise return False.
#
# ``blocking_timeout`` specifies the maximum number of seconds to
# wait trying to acquire the lock. It should not be greater than
# expire time of the lock
# """
# sleep = self.sleep
# token = b(uuid.uuid1().hex)
# if blocking is None:
# blocking = self.blocking
# if blocking_timeout is None:
# blocking_timeout = self.blocking_timeout
# blocking_timeout = blocking_timeout or self.timeout
# stop_trying_at = mod_time.time() + min(blocking_timeout, self.timeout)
#
# while True:
# if await self.do_acquire(token):
# lock_acquired_at = mod_time.time()
# if await self.check_lock_in_slaves(token):
# check_finished_at = mod_time.time()
# # if time expends on acquiring lock is greater than given time
# # the lock should be released manually
# if check_finished_at > stop_trying_at:
# await self.do_release(token)
# return False
# self.local.set(token)
# # validity time is considered to be the
# # initial validity time minus the time elapsed during check
# await self.do_extend(lock_acquired_at - check_finished_at)
# return True
# else:
# await self.do_release(token)
# return False
# if not blocking or mod_time.time() > stop_trying_at:
# return False
# await asyncio.sleep(sleep, loop=self.redis.connection_pool.loop)
#
# async def do_release(self, expected_token):
# await super(ClusterLock, self).do_release(expected_token)
# if await self.check_lock_in_slaves(expected_token):
# raise LockError('Lock is released in master but not in slave yet')
. Output only the next line. | with pytest.raises(LockError): |
Predict the next line for this snippet: <|code_start|>
class TransactionCommandMixin:
RESPONSE_CALLBACKS = string_keys_to_dict(
'WATCH UNWATCH',
bool_ok
)
async def transaction(self, func, *watches, **kwargs):
"""
Convenience method for executing the callable `func` as a transaction
while watching all keys specified in `watches`. The 'func' callable
should expect a single argument which is a Pipeline object.
"""
shard_hint = kwargs.pop('shard_hint', None)
value_from_callable = kwargs.pop('value_from_callable', False)
watch_delay = kwargs.pop('watch_delay', None)
async with await self.pipeline(True, shard_hint) as pipe:
while True:
try:
if watches:
await pipe.watch(*watches)
func_value = await func(pipe)
exec_value = await pipe.execute()
return func_value if value_from_callable else exec_value
<|code_end|>
with the help of current file imports:
import asyncio
import warnings
from aredis.exceptions import (RedisClusterException,
WatchError)
from aredis.utils import (string_keys_to_dict,
bool_ok)
and context from other files:
# Path: aredis/exceptions.py
# class RedisClusterException(Exception):
# pass
#
# class WatchError(RedisError):
# pass
#
# Path: aredis/utils.py
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
, which may contain function names, class names, or code. Output only the next line. | except WatchError: |
Predict the next line after this snippet: <|code_start|>
class TransactionCommandMixin:
RESPONSE_CALLBACKS = string_keys_to_dict(
'WATCH UNWATCH',
<|code_end|>
using the current file's imports:
import asyncio
import warnings
from aredis.exceptions import (RedisClusterException,
WatchError)
from aredis.utils import (string_keys_to_dict,
bool_ok)
and any relevant context from other files:
# Path: aredis/exceptions.py
# class RedisClusterException(Exception):
# pass
#
# class WatchError(RedisError):
# pass
#
# Path: aredis/utils.py
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
. Output only the next line. | bool_ok |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/python
# -*- coding: utf-8 -*-
class TestStreams:
@skip_if_server_version_lt('4.9.103')
@pytest.mark.asyncio(forbid_global_loop=True)
async def test_xadd_with_wrong_id(self, r):
<|code_end|>
with the help of current file imports:
import pytest
import aredis
from aredis.exceptions import RedisError, ResponseError
from tests.client.conftest import skip_if_server_version_lt
and context from other files:
# Path: aredis/exceptions.py
# class RedisError(Exception):
# pass
#
# class ResponseError(RedisError):
# pass
#
# Path: tests/client/conftest.py
# def skip_if_server_version_lt(min_version):
# loop = asyncio.get_event_loop()
# version = StrictVersion(loop.run_until_complete(get_version()))
# check = version < StrictVersion(min_version)
# return pytest.mark.skipif(check, reason="")
, which may contain function names, class names, or code. Output only the next line. | with pytest.raises(RedisError): |
Continue the code snippet: <|code_start|> await r.xadd('test_stream', {'k1': 'v1', 'k2': 1}, stream_id=idx,
max_len=10, approximate=False)
entries = await r.xrevrange('test_stream', count=5)
assert len(entries) == 5 and isinstance(entries, list) and isinstance(entries[0], tuple)
entries = await r.xrevrange('test_stream', start='2', end='3', count=3)
assert len(entries) == 0
entries = await r.xrevrange('test_stream', start='3', end='2', count=3)
assert len(entries) == 2 and entries[0][0] == b'3-0'
@skip_if_server_version_lt('4.9.103')
@pytest.mark.asyncio(forbid_global_loop=True)
async def test_xread(self, r):
await r.flushdb()
for idx in range(1, 10):
await r.xadd('test_stream', {'k1': 'v1', 'k2': 1}, stream_id=idx)
entries = await r.xread(count=5, block=10, test_stream='0')
assert len(entries[b'test_stream']) == 5
entries = await r.xread(count=10, block=10, test_stream='$')
assert not entries
entries = await r.xread(count=10, block=10, test_stream='2')
assert entries and len(entries[b'test_stream']) == 7
assert entries[b'test_stream'][0] == (b'3-0', {b'k1': b'v1', b'k2': b'1'})
@skip_if_server_version_lt('4.9.103')
@pytest.mark.asyncio(forbid_global_loop=True)
async def test_xreadgroup(self, r):
await r.flushdb()
for idx in range(1, 10):
await r.xadd('test_stream', {'k1': 'v1', 'k2': 1}, stream_id=idx)
# read from group does not exist
<|code_end|>
. Use current file imports:
import pytest
import aredis
from aredis.exceptions import RedisError, ResponseError
from tests.client.conftest import skip_if_server_version_lt
and context (classes, functions, or code) from other files:
# Path: aredis/exceptions.py
# class RedisError(Exception):
# pass
#
# class ResponseError(RedisError):
# pass
#
# Path: tests/client/conftest.py
# def skip_if_server_version_lt(min_version):
# loop = asyncio.get_event_loop()
# version = StrictVersion(loop.run_until_complete(get_version()))
# check = version < StrictVersion(min_version)
# return pytest.mark.skipif(check, reason="")
. Output only the next line. | with pytest.raises(ResponseError) as exc: |
Given the following code snippet before the placeholder: <|code_start|>
The section option is not supported by older versions of Redis Server,
and will generate ResponseError
"""
if section is None:
return await self.execute_command('INFO')
else:
return await self.execute_command('INFO', section)
async def lastsave(self):
"""
Returns a Python datetime object representing the last time the
Redis database was saved to disk
"""
return await self.execute_command('LASTSAVE')
async def save(self):
"""
Tells the Redis server to save its data to disk,
blocking until the save is complete
"""
return await self.execute_command('SAVE')
async def shutdown(self):
"""Stops Redis server"""
try:
await self.execute_command('SHUTDOWN')
except ConnectionError:
# a ConnectionError here is expected
return
<|code_end|>
, predict the next line using imports from the current file:
import datetime
from aredis.exceptions import RedisError
from aredis.utils import (b, bool_ok,
nativestr, dict_merge,
string_keys_to_dict,
list_keys_to_dict,
pairs_to_dict,
NodeFlag)
and context including class names, function names, and sometimes code from other files:
# Path: aredis/exceptions.py
# class RedisError(Exception):
# pass
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
#
# def list_keys_to_dict(key_list, callback):
# return dict.fromkeys(key_list, callback)
#
# def pairs_to_dict(response):
# """Creates a dict given a list of key/value pairs"""
# it = iter(response)
# return dict(zip(it, it))
#
# class NodeFlag:
# BLOCKED = 'blocked'
# ALL_NODES = 'all-nodes'
# ALL_MASTERS = 'all-masters'
# RANDOM = 'random'
# SLOT_ID = 'slot-id'
. Output only the next line. | raise RedisError("SHUTDOWN seems to have failed.") |
Here is a snippet: <|code_start|>
def parse_slowlog_get(response, **options):
return [{
'id': item[0],
'start_time': int(item[1]),
'duration': int(item[2]),
<|code_end|>
. Write the next line using the current file imports:
import datetime
from aredis.exceptions import RedisError
from aredis.utils import (b, bool_ok,
nativestr, dict_merge,
string_keys_to_dict,
list_keys_to_dict,
pairs_to_dict,
NodeFlag)
and context from other files:
# Path: aredis/exceptions.py
# class RedisError(Exception):
# pass
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
#
# def list_keys_to_dict(key_list, callback):
# return dict.fromkeys(key_list, callback)
#
# def pairs_to_dict(response):
# """Creates a dict given a list of key/value pairs"""
# it = iter(response)
# return dict(zip(it, it))
#
# class NodeFlag:
# BLOCKED = 'blocked'
# ALL_NODES = 'all-nodes'
# ALL_MASTERS = 'all-masters'
# RANDOM = 'random'
# SLOT_ID = 'slot-id'
, which may include functions, classes, or code. Output only the next line. | 'command': b(' ').join(item[3]) |
Next line prediction: <|code_start|> return res
def _parse_slave(response):
host, port, status, offset = response[1:]
return {
'role': role,
'host': host,
'port': port,
'status': status,
'offset': offset
}
def _parse_sentinel(response):
return {
'role': role,
'masters': response[1:]
}
parser = {
'master': _parse_master,
'slave': _parse_slave,
'sentinel': _parse_sentinel
}[role]
return parser(response)
class ServerCommandMixin:
RESPONSE_CALLBACKS = dict_merge(
string_keys_to_dict('BGREWRITEAOF BGSAVE', lambda r: True),
string_keys_to_dict(
'FLUSHALL FLUSHDB SAVE '
<|code_end|>
. Use current file imports:
(import datetime
from aredis.exceptions import RedisError
from aredis.utils import (b, bool_ok,
nativestr, dict_merge,
string_keys_to_dict,
list_keys_to_dict,
pairs_to_dict,
NodeFlag))
and context including class names, function names, or small code snippets from other files:
# Path: aredis/exceptions.py
# class RedisError(Exception):
# pass
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
#
# def list_keys_to_dict(key_list, callback):
# return dict.fromkeys(key_list, callback)
#
# def pairs_to_dict(response):
# """Creates a dict given a list of key/value pairs"""
# it = iter(response)
# return dict(zip(it, it))
#
# class NodeFlag:
# BLOCKED = 'blocked'
# ALL_NODES = 'all-nodes'
# ALL_MASTERS = 'all-masters'
# RANDOM = 'random'
# SLOT_ID = 'slot-id'
. Output only the next line. | 'SHUTDOWN SLAVEOF', bool_ok |
Given the code snippet: <|code_start|>
def parse_slowlog_get(response, **options):
return [{
'id': item[0],
'start_time': int(item[1]),
'duration': int(item[2]),
'command': b(' ').join(item[3])
} for item in response]
def parse_client_list(response, **options):
clients = []
<|code_end|>
, generate the next line using the imports in this file:
import datetime
from aredis.exceptions import RedisError
from aredis.utils import (b, bool_ok,
nativestr, dict_merge,
string_keys_to_dict,
list_keys_to_dict,
pairs_to_dict,
NodeFlag)
and context (functions, classes, or occasionally code) from other files:
# Path: aredis/exceptions.py
# class RedisError(Exception):
# pass
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
#
# def list_keys_to_dict(key_list, callback):
# return dict.fromkeys(key_list, callback)
#
# def pairs_to_dict(response):
# """Creates a dict given a list of key/value pairs"""
# it = iter(response)
# return dict(zip(it, it))
#
# class NodeFlag:
# BLOCKED = 'blocked'
# ALL_NODES = 'all-nodes'
# ALL_MASTERS = 'all-masters'
# RANDOM = 'random'
# SLOT_ID = 'slot-id'
. Output only the next line. | for c in nativestr(response).splitlines(): |
Here is a snippet: <|code_start|> 'host': host,
'port': int(port),
'offset': int(offset)
})
return res
def _parse_slave(response):
host, port, status, offset = response[1:]
return {
'role': role,
'host': host,
'port': port,
'status': status,
'offset': offset
}
def _parse_sentinel(response):
return {
'role': role,
'masters': response[1:]
}
parser = {
'master': _parse_master,
'slave': _parse_slave,
'sentinel': _parse_sentinel
}[role]
return parser(response)
class ServerCommandMixin:
<|code_end|>
. Write the next line using the current file imports:
import datetime
from aredis.exceptions import RedisError
from aredis.utils import (b, bool_ok,
nativestr, dict_merge,
string_keys_to_dict,
list_keys_to_dict,
pairs_to_dict,
NodeFlag)
and context from other files:
# Path: aredis/exceptions.py
# class RedisError(Exception):
# pass
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
#
# def list_keys_to_dict(key_list, callback):
# return dict.fromkeys(key_list, callback)
#
# def pairs_to_dict(response):
# """Creates a dict given a list of key/value pairs"""
# it = iter(response)
# return dict(zip(it, it))
#
# class NodeFlag:
# BLOCKED = 'blocked'
# ALL_NODES = 'all-nodes'
# ALL_MASTERS = 'all-masters'
# RANDOM = 'random'
# SLOT_ID = 'slot-id'
, which may include functions, classes, or code. Output only the next line. | RESPONSE_CALLBACKS = dict_merge( |
Predict the next line after this snippet: <|code_start|> 'port': int(port),
'offset': int(offset)
})
return res
def _parse_slave(response):
host, port, status, offset = response[1:]
return {
'role': role,
'host': host,
'port': port,
'status': status,
'offset': offset
}
def _parse_sentinel(response):
return {
'role': role,
'masters': response[1:]
}
parser = {
'master': _parse_master,
'slave': _parse_slave,
'sentinel': _parse_sentinel
}[role]
return parser(response)
class ServerCommandMixin:
RESPONSE_CALLBACKS = dict_merge(
<|code_end|>
using the current file's imports:
import datetime
from aredis.exceptions import RedisError
from aredis.utils import (b, bool_ok,
nativestr, dict_merge,
string_keys_to_dict,
list_keys_to_dict,
pairs_to_dict,
NodeFlag)
and any relevant context from other files:
# Path: aredis/exceptions.py
# class RedisError(Exception):
# pass
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
#
# def list_keys_to_dict(key_list, callback):
# return dict.fromkeys(key_list, callback)
#
# def pairs_to_dict(response):
# """Creates a dict given a list of key/value pairs"""
# it = iter(response)
# return dict(zip(it, it))
#
# class NodeFlag:
# BLOCKED = 'blocked'
# ALL_NODES = 'all-nodes'
# ALL_MASTERS = 'all-masters'
# RANDOM = 'random'
# SLOT_ID = 'slot-id'
. Output only the next line. | string_keys_to_dict('BGREWRITEAOF BGSAVE', lambda r: True), |
Given snippet: <|code_start|>
async def slowlog_len(self):
"""Gets the number of items in the slowlog"""
return await self.execute_command('SLOWLOG LEN')
async def slowlog_reset(self):
"""Removes all items in the slowlog"""
return await self.execute_command('SLOWLOG RESET')
async def time(self):
"""
Returns the server time as a 2-item tuple of ints:
(seconds since epoch, microseconds into this second).
"""
return await self.execute_command('TIME')
async def role(self):
"""
Provides information on the role of a Redis instance in the context of replication,
by returning if the instance is currently a master, slave, or sentinel.
The command also returns additional information about the state of the replication
(if the role is master or slave)
or the list of monitored master names (if the role is sentinel).
:return:
"""
return await self.execute_command('ROLE')
class ClusterServerCommandMixin(ServerCommandMixin):
NODES_FLAGS = dict_merge(
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import datetime
from aredis.exceptions import RedisError
from aredis.utils import (b, bool_ok,
nativestr, dict_merge,
string_keys_to_dict,
list_keys_to_dict,
pairs_to_dict,
NodeFlag)
and context:
# Path: aredis/exceptions.py
# class RedisError(Exception):
# pass
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
#
# def list_keys_to_dict(key_list, callback):
# return dict.fromkeys(key_list, callback)
#
# def pairs_to_dict(response):
# """Creates a dict given a list of key/value pairs"""
# it = iter(response)
# return dict(zip(it, it))
#
# class NodeFlag:
# BLOCKED = 'blocked'
# ALL_NODES = 'all-nodes'
# ALL_MASTERS = 'all-masters'
# RANDOM = 'random'
# SLOT_ID = 'slot-id'
which might include code, classes, or functions. Output only the next line. | list_keys_to_dict( |
Based on the snippet: <|code_start|>
def parse_slowlog_get(response, **options):
return [{
'id': item[0],
'start_time': int(item[1]),
'duration': int(item[2]),
'command': b(' ').join(item[3])
} for item in response]
def parse_client_list(response, **options):
clients = []
for c in nativestr(response).splitlines():
# Values might contain '='
clients.append(dict([pair.split('=', 1) for pair in c.split(' ')]))
return clients
def parse_config_get(response, **options):
response = [nativestr(i) if i is not None else None for i in response]
<|code_end|>
, predict the immediate next line with the help of imports:
import datetime
from aredis.exceptions import RedisError
from aredis.utils import (b, bool_ok,
nativestr, dict_merge,
string_keys_to_dict,
list_keys_to_dict,
pairs_to_dict,
NodeFlag)
and context (classes, functions, sometimes code) from other files:
# Path: aredis/exceptions.py
# class RedisError(Exception):
# pass
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
#
# def list_keys_to_dict(key_list, callback):
# return dict.fromkeys(key_list, callback)
#
# def pairs_to_dict(response):
# """Creates a dict given a list of key/value pairs"""
# it = iter(response)
# return dict(zip(it, it))
#
# class NodeFlag:
# BLOCKED = 'blocked'
# ALL_NODES = 'all-nodes'
# ALL_MASTERS = 'all-masters'
# RANDOM = 'random'
# SLOT_ID = 'slot-id'
. Output only the next line. | return response and pairs_to_dict(response) or {} |
Next line prediction: <|code_start|> """Gets the number of items in the slowlog"""
return await self.execute_command('SLOWLOG LEN')
async def slowlog_reset(self):
"""Removes all items in the slowlog"""
return await self.execute_command('SLOWLOG RESET')
async def time(self):
"""
Returns the server time as a 2-item tuple of ints:
(seconds since epoch, microseconds into this second).
"""
return await self.execute_command('TIME')
async def role(self):
"""
Provides information on the role of a Redis instance in the context of replication,
by returning if the instance is currently a master, slave, or sentinel.
The command also returns additional information about the state of the replication
(if the role is master or slave)
or the list of monitored master names (if the role is sentinel).
:return:
"""
return await self.execute_command('ROLE')
class ClusterServerCommandMixin(ServerCommandMixin):
NODES_FLAGS = dict_merge(
list_keys_to_dict(
['SHUTDOWN', 'SLAVEOF', 'CLIENT SETNAME'],
<|code_end|>
. Use current file imports:
(import datetime
from aredis.exceptions import RedisError
from aredis.utils import (b, bool_ok,
nativestr, dict_merge,
string_keys_to_dict,
list_keys_to_dict,
pairs_to_dict,
NodeFlag))
and context including class names, function names, or small code snippets from other files:
# Path: aredis/exceptions.py
# class RedisError(Exception):
# pass
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
#
# def list_keys_to_dict(key_list, callback):
# return dict.fromkeys(key_list, callback)
#
# def pairs_to_dict(response):
# """Creates a dict given a list of key/value pairs"""
# it = iter(response)
# return dict(zip(it, it))
#
# class NodeFlag:
# BLOCKED = 'blocked'
# ALL_NODES = 'all-nodes'
# ALL_MASTERS = 'all-masters'
# RANDOM = 'random'
# SLOT_ID = 'slot-id'
. Output only the next line. | NodeFlag.BLOCKED |
Given snippet: <|code_start|> assert await r.zrevrangebylex('a', '(c', '-') == [b('b'), b('a')]
assert await r.zrevrangebylex('a', '(g', '[aaa') == \
[b('f'), b('e'), b('d'), b('c'), b('b')]
assert await r.zrevrangebylex('a', '+', '[f') == [b('g'), b('f')]
assert await r.zrevrangebylex('a', '+', '-', start=3, num=2) == \
[b('d'), b('c')]
@pytest.mark.asyncio
async def test_command_on_invalid_key_type(self, r):
await r.flushdb()
await r.lpush('a', '1')
with pytest.raises(ResponseError):
await r.get('a')
# SERVER INFORMATION
@pytest.mark.asyncio
async def test_client_list(self, r):
client_lists = await r.client_list()
for server, clients in client_lists.items():
assert isinstance(clients[0], dict)
assert 'addr' in clients[0]
@pytest.mark.asyncio
async def test_client_getname(self, r):
client_names = await r.client_getname()
for server, name in client_names.items():
assert name is None
@pytest.mark.asyncio
async def test_client_setname(self, r):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import datetime
import re
import time
import pytest
from string import ascii_letters
from aredis.exceptions import RedisClusterException, ResponseError, DataError, RedisError
from aredis.utils import b, iteritems, iterkeys, itervalues
from aredis.commands.server import parse_info
from tests.cluster.conftest import skip_if_server_version_lt, skip_if_redis_py_version_lt
and context:
# Path: aredis/exceptions.py
# class RedisClusterException(Exception):
# pass
#
# class ResponseError(RedisError):
# pass
#
# class DataError(RedisError):
# pass
#
# class RedisError(Exception):
# pass
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def iteritems(x):
# return iter(x.items())
#
# def iterkeys(x):
# return iter(x.keys())
#
# def itervalues(x):
# return iter(x.values())
#
# Path: aredis/commands/server.py
# def parse_info(response):
# """Parses the result of Redis's INFO command into a Python dict"""
# info = {}
# response = nativestr(response)
#
# def get_value(value):
# if ',' not in value or '=' not in value:
# try:
# if '.' in value:
# return float(value)
# else:
# return int(value)
# except ValueError:
# return value
# else:
# sub_dict = {}
# for item in value.split(','):
# k, v = item.rsplit('=', 1)
# sub_dict[k] = get_value(v)
# return sub_dict
#
# for line in response.splitlines():
# if line and not line.startswith('#'):
# if line.find(':') != -1:
# key, value = line.split(':', 1)
# info[key] = get_value(value)
# else:
# # if the line isn't splittable, append it to the "__raw__" key
# info.setdefault('__raw__', []).append(line)
#
# return info
#
# Path: tests/cluster/conftest.py
# def skip_if_server_version_lt(min_version):
# """
# """
# versions = get_versions()
# for version in versions.values():
# if StrictVersion(version) < StrictVersion(min_version):
# return pytest.mark.skipif(True, reason="")
# return pytest.mark.skipif(False, reason="")
#
# def skip_if_redis_py_version_lt(min_version):
# """
# """
# import aredis
# version = aredis.__version__
# if StrictVersion(version) < StrictVersion(min_version):
# return pytest.mark.skipif(True, reason="")
# return pytest.mark.skipif(False, reason="")
which might include code, classes, or functions. Output only the next line. | with pytest.raises(RedisClusterException): |
Using the snippet: <|code_start|>
pytestmark = skip_if_server_version_lt('2.9.0')
async def redis_server_time(client):
t = await client.time()
seconds, milliseconds = list(t.values())[0]
timestamp = float('{0}.{1}'.format(seconds, milliseconds))
return datetime.datetime.fromtimestamp(timestamp)
class TestRedisCommands:
@pytest.mark.asyncio
@skip_if_server_version_lt('2.9.9')
async def test_zrevrangebylex(self, r):
await r.flushdb()
await r.zadd('a', a=0, b=0, c=0, d=0, e=0, f=0, g=0)
assert await r.zrevrangebylex('a', '[c', '-') == [b('c'), b('b'), b('a')]
assert await r.zrevrangebylex('a', '(c', '-') == [b('b'), b('a')]
assert await r.zrevrangebylex('a', '(g', '[aaa') == \
[b('f'), b('e'), b('d'), b('c'), b('b')]
assert await r.zrevrangebylex('a', '+', '[f') == [b('g'), b('f')]
assert await r.zrevrangebylex('a', '+', '-', start=3, num=2) == \
[b('d'), b('c')]
@pytest.mark.asyncio
async def test_command_on_invalid_key_type(self, r):
await r.flushdb()
await r.lpush('a', '1')
<|code_end|>
, determine the next line of code. You have imports:
import datetime
import re
import time
import pytest
from string import ascii_letters
from aredis.exceptions import RedisClusterException, ResponseError, DataError, RedisError
from aredis.utils import b, iteritems, iterkeys, itervalues
from aredis.commands.server import parse_info
from tests.cluster.conftest import skip_if_server_version_lt, skip_if_redis_py_version_lt
and context (class names, function names, or code) available:
# Path: aredis/exceptions.py
# class RedisClusterException(Exception):
# pass
#
# class ResponseError(RedisError):
# pass
#
# class DataError(RedisError):
# pass
#
# class RedisError(Exception):
# pass
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def iteritems(x):
# return iter(x.items())
#
# def iterkeys(x):
# return iter(x.keys())
#
# def itervalues(x):
# return iter(x.values())
#
# Path: aredis/commands/server.py
# def parse_info(response):
# """Parses the result of Redis's INFO command into a Python dict"""
# info = {}
# response = nativestr(response)
#
# def get_value(value):
# if ',' not in value or '=' not in value:
# try:
# if '.' in value:
# return float(value)
# else:
# return int(value)
# except ValueError:
# return value
# else:
# sub_dict = {}
# for item in value.split(','):
# k, v = item.rsplit('=', 1)
# sub_dict[k] = get_value(v)
# return sub_dict
#
# for line in response.splitlines():
# if line and not line.startswith('#'):
# if line.find(':') != -1:
# key, value = line.split(':', 1)
# info[key] = get_value(value)
# else:
# # if the line isn't splittable, append it to the "__raw__" key
# info.setdefault('__raw__', []).append(line)
#
# return info
#
# Path: tests/cluster/conftest.py
# def skip_if_server_version_lt(min_version):
# """
# """
# versions = get_versions()
# for version in versions.values():
# if StrictVersion(version) < StrictVersion(min_version):
# return pytest.mark.skipif(True, reason="")
# return pytest.mark.skipif(False, reason="")
#
# def skip_if_redis_py_version_lt(min_version):
# """
# """
# import aredis
# version = aredis.__version__
# if StrictVersion(version) < StrictVersion(min_version):
# return pytest.mark.skipif(True, reason="")
# return pytest.mark.skipif(False, reason="")
. Output only the next line. | with pytest.raises(ResponseError): |
Predict the next line for this snippet: <|code_start|> await r.rpush('a', '2', '3', '1')
assert await r.sort('a', get='user:*') == [b('u1'), b('u2'), b('u3')]
@pytest.mark.asyncio
async def test_sort_get_multi(self, r):
await r.flushdb()
await r.set('user:1', 'u1')
await r.set('user:2', 'u2')
await r.set('user:3', 'u3')
await r.rpush('a', '2', '3', '1')
assert await r.sort('a', get=('user:*', '#')) == \
[b('u1'), b('1'), b('u2'), b('2'), b('u3'), b('3')]
@pytest.mark.asyncio
async def test_sort_get_groups_two(self, r):
await r.flushdb()
await r.set('user:1', 'u1')
await r.set('user:2', 'u2')
await r.set('user:3', 'u3')
await r.rpush('a', '2', '3', '1')
assert await r.sort('a', get=('user:*', '#'), groups=True) == \
[(b('u1'), b('1')), (b('u2'), b('2')), (b('u3'), b('3'))]
@pytest.mark.asyncio
async def test_sort_groups_string_get(self, r):
await r.flushdb()
await r.set('user:1', 'u1')
await r.set('user:2', 'u2')
await r.set('user:3', 'u3')
await r.rpush('a', '2', '3', '1')
<|code_end|>
with the help of current file imports:
import datetime
import re
import time
import pytest
from string import ascii_letters
from aredis.exceptions import RedisClusterException, ResponseError, DataError, RedisError
from aredis.utils import b, iteritems, iterkeys, itervalues
from aredis.commands.server import parse_info
from tests.cluster.conftest import skip_if_server_version_lt, skip_if_redis_py_version_lt
and context from other files:
# Path: aredis/exceptions.py
# class RedisClusterException(Exception):
# pass
#
# class ResponseError(RedisError):
# pass
#
# class DataError(RedisError):
# pass
#
# class RedisError(Exception):
# pass
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def iteritems(x):
# return iter(x.items())
#
# def iterkeys(x):
# return iter(x.keys())
#
# def itervalues(x):
# return iter(x.values())
#
# Path: aredis/commands/server.py
# def parse_info(response):
# """Parses the result of Redis's INFO command into a Python dict"""
# info = {}
# response = nativestr(response)
#
# def get_value(value):
# if ',' not in value or '=' not in value:
# try:
# if '.' in value:
# return float(value)
# else:
# return int(value)
# except ValueError:
# return value
# else:
# sub_dict = {}
# for item in value.split(','):
# k, v = item.rsplit('=', 1)
# sub_dict[k] = get_value(v)
# return sub_dict
#
# for line in response.splitlines():
# if line and not line.startswith('#'):
# if line.find(':') != -1:
# key, value = line.split(':', 1)
# info[key] = get_value(value)
# else:
# # if the line isn't splittable, append it to the "__raw__" key
# info.setdefault('__raw__', []).append(line)
#
# return info
#
# Path: tests/cluster/conftest.py
# def skip_if_server_version_lt(min_version):
# """
# """
# versions = get_versions()
# for version in versions.values():
# if StrictVersion(version) < StrictVersion(min_version):
# return pytest.mark.skipif(True, reason="")
# return pytest.mark.skipif(False, reason="")
#
# def skip_if_redis_py_version_lt(min_version):
# """
# """
# import aredis
# version = aredis.__version__
# if StrictVersion(version) < StrictVersion(min_version):
# return pytest.mark.skipif(True, reason="")
# return pytest.mark.skipif(False, reason="")
, which may contain function names, class names, or code. Output only the next line. | with pytest.raises(DataError): |
Here is a snippet: <|code_start|> @skip_if_redis_py_version_lt("2.10.2")
async def test_bitpos(self, r):
"""
Bitpos was added in redis-py in version 2.10.2
# TODO: Added b() around keys but i think they should not have to be
there for this command to work properly.
"""
await r.flushdb()
key = 'key:bitpos'
await r.set(key, b('\xff\xf0\x00'))
assert await r.bitpos(key, 0) == 12
assert await r.bitpos(key, 0, 2, -1) == 16
assert await r.bitpos(key, 0, -2, -1) == 12
await r.set(key, b('\x00\xff\xf0'))
assert await r.bitpos(key, 1, 0) == 8
assert await r.bitpos(key, 1, 1) == 8
await r.set(key, '\x00\x00\x00')
assert await r.bitpos(key, 1) == -1
@pytest.mark.asyncio
@skip_if_server_version_lt('2.8.7')
@skip_if_redis_py_version_lt("2.10.2")
async def test_bitpos_wrong_arguments(self, r):
"""
Bitpos was added in redis-py in version 2.10.2
"""
key = 'key:bitpos:wrong:args'
await r.flushdb()
await r.set(key, b('\xff\xf0\x00'))
<|code_end|>
. Write the next line using the current file imports:
import datetime
import re
import time
import pytest
from string import ascii_letters
from aredis.exceptions import RedisClusterException, ResponseError, DataError, RedisError
from aredis.utils import b, iteritems, iterkeys, itervalues
from aredis.commands.server import parse_info
from tests.cluster.conftest import skip_if_server_version_lt, skip_if_redis_py_version_lt
and context from other files:
# Path: aredis/exceptions.py
# class RedisClusterException(Exception):
# pass
#
# class ResponseError(RedisError):
# pass
#
# class DataError(RedisError):
# pass
#
# class RedisError(Exception):
# pass
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def iteritems(x):
# return iter(x.items())
#
# def iterkeys(x):
# return iter(x.keys())
#
# def itervalues(x):
# return iter(x.values())
#
# Path: aredis/commands/server.py
# def parse_info(response):
# """Parses the result of Redis's INFO command into a Python dict"""
# info = {}
# response = nativestr(response)
#
# def get_value(value):
# if ',' not in value or '=' not in value:
# try:
# if '.' in value:
# return float(value)
# else:
# return int(value)
# except ValueError:
# return value
# else:
# sub_dict = {}
# for item in value.split(','):
# k, v = item.rsplit('=', 1)
# sub_dict[k] = get_value(v)
# return sub_dict
#
# for line in response.splitlines():
# if line and not line.startswith('#'):
# if line.find(':') != -1:
# key, value = line.split(':', 1)
# info[key] = get_value(value)
# else:
# # if the line isn't splittable, append it to the "__raw__" key
# info.setdefault('__raw__', []).append(line)
#
# return info
#
# Path: tests/cluster/conftest.py
# def skip_if_server_version_lt(min_version):
# """
# """
# versions = get_versions()
# for version in versions.values():
# if StrictVersion(version) < StrictVersion(min_version):
# return pytest.mark.skipif(True, reason="")
# return pytest.mark.skipif(False, reason="")
#
# def skip_if_redis_py_version_lt(min_version):
# """
# """
# import aredis
# version = aredis.__version__
# if StrictVersion(version) < StrictVersion(min_version):
# return pytest.mark.skipif(True, reason="")
# return pytest.mark.skipif(False, reason="")
, which may include functions, classes, or code. Output only the next line. | with pytest.raises(RedisError): |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
# python std lib
from __future__ import with_statement
# rediscluster imports
pytestmark = skip_if_server_version_lt('2.9.0')
async def redis_server_time(client):
t = await client.time()
seconds, milliseconds = list(t.values())[0]
timestamp = float('{0}.{1}'.format(seconds, milliseconds))
return datetime.datetime.fromtimestamp(timestamp)
class TestRedisCommands:
@pytest.mark.asyncio
@skip_if_server_version_lt('2.9.9')
async def test_zrevrangebylex(self, r):
await r.flushdb()
<|code_end|>
, determine the next line of code. You have imports:
import datetime
import re
import time
import pytest
from string import ascii_letters
from aredis.exceptions import RedisClusterException, ResponseError, DataError, RedisError
from aredis.utils import b, iteritems, iterkeys, itervalues
from aredis.commands.server import parse_info
from tests.cluster.conftest import skip_if_server_version_lt, skip_if_redis_py_version_lt
and context (class names, function names, or code) available:
# Path: aredis/exceptions.py
# class RedisClusterException(Exception):
# pass
#
# class ResponseError(RedisError):
# pass
#
# class DataError(RedisError):
# pass
#
# class RedisError(Exception):
# pass
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def iteritems(x):
# return iter(x.items())
#
# def iterkeys(x):
# return iter(x.keys())
#
# def itervalues(x):
# return iter(x.values())
#
# Path: aredis/commands/server.py
# def parse_info(response):
# """Parses the result of Redis's INFO command into a Python dict"""
# info = {}
# response = nativestr(response)
#
# def get_value(value):
# if ',' not in value or '=' not in value:
# try:
# if '.' in value:
# return float(value)
# else:
# return int(value)
# except ValueError:
# return value
# else:
# sub_dict = {}
# for item in value.split(','):
# k, v = item.rsplit('=', 1)
# sub_dict[k] = get_value(v)
# return sub_dict
#
# for line in response.splitlines():
# if line and not line.startswith('#'):
# if line.find(':') != -1:
# key, value = line.split(':', 1)
# info[key] = get_value(value)
# else:
# # if the line isn't splittable, append it to the "__raw__" key
# info.setdefault('__raw__', []).append(line)
#
# return info
#
# Path: tests/cluster/conftest.py
# def skip_if_server_version_lt(min_version):
# """
# """
# versions = get_versions()
# for version in versions.values():
# if StrictVersion(version) < StrictVersion(min_version):
# return pytest.mark.skipif(True, reason="")
# return pytest.mark.skipif(False, reason="")
#
# def skip_if_redis_py_version_lt(min_version):
# """
# """
# import aredis
# version = aredis.__version__
# if StrictVersion(version) < StrictVersion(min_version):
# return pytest.mark.skipif(True, reason="")
# return pytest.mark.skipif(False, reason="")
. Output only the next line. | await r.zadd('a', a=0, b=0, c=0, d=0, e=0, f=0, g=0) |
Here is a snippet: <|code_start|> assert await r.get('a') == b('1')
assert await r.incrbyfloat('a', 1.1) == 2.1
assert float(await r.get('a')) == float(2.1)
@pytest.mark.asyncio
async def test_keys(self, r):
await r.flushdb()
keys = await r.keys()
assert keys == []
keys_with_underscores = set(['test_a', 'test_b'])
keys = keys_with_underscores.union(set(['testc']))
for key in keys:
await r.set(key, 1)
assert set(await r.keys(pattern='test_*')) == {b(k) for k in keys_with_underscores}
assert set(await r.keys(pattern='test*')) == {b(k) for k in keys}
@pytest.mark.asyncio
async def test_mget(self, r):
await r.flushdb()
assert await r.mget(['a', 'b']) == [None, None]
await r.set('a', 1)
await r.set('b', 2)
await r.set('c', 3)
assert await r.mget('a', 'other', 'b', 'c') == [b('1'), None, b('2'), b('3')]
@pytest.mark.asyncio
async def test_mset(self, r):
await r.flushdb()
d = {'a': b('1'), 'b': b('2'), 'c': b('3')}
assert await r.mset(d)
<|code_end|>
. Write the next line using the current file imports:
import datetime
import re
import time
import pytest
from string import ascii_letters
from aredis.exceptions import RedisClusterException, ResponseError, DataError, RedisError
from aredis.utils import b, iteritems, iterkeys, itervalues
from aredis.commands.server import parse_info
from tests.cluster.conftest import skip_if_server_version_lt, skip_if_redis_py_version_lt
and context from other files:
# Path: aredis/exceptions.py
# class RedisClusterException(Exception):
# pass
#
# class ResponseError(RedisError):
# pass
#
# class DataError(RedisError):
# pass
#
# class RedisError(Exception):
# pass
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def iteritems(x):
# return iter(x.items())
#
# def iterkeys(x):
# return iter(x.keys())
#
# def itervalues(x):
# return iter(x.values())
#
# Path: aredis/commands/server.py
# def parse_info(response):
# """Parses the result of Redis's INFO command into a Python dict"""
# info = {}
# response = nativestr(response)
#
# def get_value(value):
# if ',' not in value or '=' not in value:
# try:
# if '.' in value:
# return float(value)
# else:
# return int(value)
# except ValueError:
# return value
# else:
# sub_dict = {}
# for item in value.split(','):
# k, v = item.rsplit('=', 1)
# sub_dict[k] = get_value(v)
# return sub_dict
#
# for line in response.splitlines():
# if line and not line.startswith('#'):
# if line.find(':') != -1:
# key, value = line.split(':', 1)
# info[key] = get_value(value)
# else:
# # if the line isn't splittable, append it to the "__raw__" key
# info.setdefault('__raw__', []).append(line)
#
# return info
#
# Path: tests/cluster/conftest.py
# def skip_if_server_version_lt(min_version):
# """
# """
# versions = get_versions()
# for version in versions.values():
# if StrictVersion(version) < StrictVersion(min_version):
# return pytest.mark.skipif(True, reason="")
# return pytest.mark.skipif(False, reason="")
#
# def skip_if_redis_py_version_lt(min_version):
# """
# """
# import aredis
# version = aredis.__version__
# if StrictVersion(version) < StrictVersion(min_version):
# return pytest.mark.skipif(True, reason="")
# return pytest.mark.skipif(False, reason="")
, which may include functions, classes, or code. Output only the next line. | for k, v in iteritems(d): |
Using the snippet: <|code_start|> await r.hmset('a', {'1': 1, '2': 2, '3': 3})
assert await r.hexists('a', '1')
assert not await r.hexists('a', '4')
@pytest.mark.asyncio
async def test_hgetall(self, r):
await r.flushdb()
h = {b('a1'): b('1'), b('a2'): b('2'), b('a3'): b('3')}
await r.hmset('a', h)
assert await r.hgetall('a') == h
@pytest.mark.asyncio
async def test_hincrby(self, r):
await r.flushdb()
assert await r.hincrby('a', '1') == 1
assert await r.hincrby('a', '1', amount=2) == 3
assert await r.hincrby('a', '1', amount=-2) == 1
@pytest.mark.asyncio
async def test_hincrbyfloat(self, r):
await r.flushdb()
assert await r.hincrbyfloat('a', '1') == 1.0
assert await r.hincrbyfloat('a', '1') == 2.0
assert await r.hincrbyfloat('a', '1', 1.2) == 3.2
@pytest.mark.asyncio
async def test_hkeys(self, r):
await r.flushdb()
h = {b('a1'): b('1'), b('a2'): b('2'), b('a3'): b('3')}
await r.hmset('a', h)
<|code_end|>
, determine the next line of code. You have imports:
import datetime
import re
import time
import pytest
from string import ascii_letters
from aredis.exceptions import RedisClusterException, ResponseError, DataError, RedisError
from aredis.utils import b, iteritems, iterkeys, itervalues
from aredis.commands.server import parse_info
from tests.cluster.conftest import skip_if_server_version_lt, skip_if_redis_py_version_lt
and context (class names, function names, or code) available:
# Path: aredis/exceptions.py
# class RedisClusterException(Exception):
# pass
#
# class ResponseError(RedisError):
# pass
#
# class DataError(RedisError):
# pass
#
# class RedisError(Exception):
# pass
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def iteritems(x):
# return iter(x.items())
#
# def iterkeys(x):
# return iter(x.keys())
#
# def itervalues(x):
# return iter(x.values())
#
# Path: aredis/commands/server.py
# def parse_info(response):
# """Parses the result of Redis's INFO command into a Python dict"""
# info = {}
# response = nativestr(response)
#
# def get_value(value):
# if ',' not in value or '=' not in value:
# try:
# if '.' in value:
# return float(value)
# else:
# return int(value)
# except ValueError:
# return value
# else:
# sub_dict = {}
# for item in value.split(','):
# k, v = item.rsplit('=', 1)
# sub_dict[k] = get_value(v)
# return sub_dict
#
# for line in response.splitlines():
# if line and not line.startswith('#'):
# if line.find(':') != -1:
# key, value = line.split(':', 1)
# info[key] = get_value(value)
# else:
# # if the line isn't splittable, append it to the "__raw__" key
# info.setdefault('__raw__', []).append(line)
#
# return info
#
# Path: tests/cluster/conftest.py
# def skip_if_server_version_lt(min_version):
# """
# """
# versions = get_versions()
# for version in versions.values():
# if StrictVersion(version) < StrictVersion(min_version):
# return pytest.mark.skipif(True, reason="")
# return pytest.mark.skipif(False, reason="")
#
# def skip_if_redis_py_version_lt(min_version):
# """
# """
# import aredis
# version = aredis.__version__
# if StrictVersion(version) < StrictVersion(min_version):
# return pytest.mark.skipif(True, reason="")
# return pytest.mark.skipif(False, reason="")
. Output only the next line. | local_keys = list(iterkeys(h)) |
Here is a snippet: <|code_start|> await r.hmset('a', {'1': 1, '2': 2, '3': 3})
assert await r.hlen('a') == 3
@pytest.mark.asyncio
async def test_hmget(self, r):
await r.flushdb()
assert await r.hmset('a', {'a': 1, 'b': 2, 'c': 3})
assert await r.hmget('a', 'a', 'b', 'c') == [b('1'), b('2'), b('3')]
@pytest.mark.asyncio
async def test_hmset(self, r):
await r.flushdb()
h = {b('a'): b('1'), b('b'): b('2'), b('c'): b('3')}
assert await r.hmset('a', h)
assert await r.hgetall('a') == h
@pytest.mark.asyncio
async def test_hsetnx(self, r):
await r.flushdb()
# Initially set the hash field
assert await r.hsetnx('a', '1', 1)
assert await r.hget('a', '1') == b('1')
assert not await r.hsetnx('a', '1', 2)
assert await r.hget('a', '1') == b('1')
@pytest.mark.asyncio
async def test_hvals(self, r):
await r.flushdb()
h = {b('a1'): b('1'), b('a2'): b('2'), b('a3'): b('3')}
await r.hmset('a', h)
<|code_end|>
. Write the next line using the current file imports:
import datetime
import re
import time
import pytest
from string import ascii_letters
from aredis.exceptions import RedisClusterException, ResponseError, DataError, RedisError
from aredis.utils import b, iteritems, iterkeys, itervalues
from aredis.commands.server import parse_info
from tests.cluster.conftest import skip_if_server_version_lt, skip_if_redis_py_version_lt
and context from other files:
# Path: aredis/exceptions.py
# class RedisClusterException(Exception):
# pass
#
# class ResponseError(RedisError):
# pass
#
# class DataError(RedisError):
# pass
#
# class RedisError(Exception):
# pass
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def iteritems(x):
# return iter(x.items())
#
# def iterkeys(x):
# return iter(x.keys())
#
# def itervalues(x):
# return iter(x.values())
#
# Path: aredis/commands/server.py
# def parse_info(response):
# """Parses the result of Redis's INFO command into a Python dict"""
# info = {}
# response = nativestr(response)
#
# def get_value(value):
# if ',' not in value or '=' not in value:
# try:
# if '.' in value:
# return float(value)
# else:
# return int(value)
# except ValueError:
# return value
# else:
# sub_dict = {}
# for item in value.split(','):
# k, v = item.rsplit('=', 1)
# sub_dict[k] = get_value(v)
# return sub_dict
#
# for line in response.splitlines():
# if line and not line.startswith('#'):
# if line.find(':') != -1:
# key, value = line.split(':', 1)
# info[key] = get_value(value)
# else:
# # if the line isn't splittable, append it to the "__raw__" key
# info.setdefault('__raw__', []).append(line)
#
# return info
#
# Path: tests/cluster/conftest.py
# def skip_if_server_version_lt(min_version):
# """
# """
# versions = get_versions()
# for version in versions.values():
# if StrictVersion(version) < StrictVersion(min_version):
# return pytest.mark.skipif(True, reason="")
# return pytest.mark.skipif(False, reason="")
#
# def skip_if_redis_py_version_lt(min_version):
# """
# """
# import aredis
# version = aredis.__version__
# if StrictVersion(version) < StrictVersion(min_version):
# return pytest.mark.skipif(True, reason="")
# return pytest.mark.skipif(False, reason="")
, which may include functions, classes, or code. Output only the next line. | local_vals = list(itervalues(h)) |
Predict the next line for this snippet: <|code_start|> @pytest.mark.asyncio
async def test_22_info(self):
"""
Older Redis versions contained 'allocation_stats' in INFO that
was the cause of a number of bugs when parsing.
"""
info = b"allocation_stats:6=1,7=1,8=7141,9=180,10=92,11=116,12=5330," \
b"13=123,14=3091,15=11048,16=225842,17=1784,18=814,19=12020," \
b"20=2530,21=645,22=15113,23=8695,24=142860,25=318,26=3303," \
b"27=20561,28=54042,29=37390,30=1884,31=18071,32=31367,33=160," \
b"34=169,35=201,36=10155,37=1045,38=15078,39=22985,40=12523," \
b"41=15588,42=265,43=1287,44=142,45=382,46=945,47=426,48=171," \
b"49=56,50=516,51=43,52=41,53=46,54=54,55=75,56=647,57=332," \
b"58=32,59=39,60=48,61=35,62=62,63=32,64=221,65=26,66=30," \
b"67=36,68=41,69=44,70=26,71=144,72=169,73=24,74=37,75=25," \
b"76=42,77=21,78=126,79=374,80=27,81=40,82=43,83=47,84=46," \
b"85=114,86=34,87=37,88=7240,89=34,90=38,91=18,92=99,93=20," \
b"94=18,95=17,96=15,97=22,98=18,99=69,100=17,101=22,102=15," \
b"103=29,104=39,105=30,106=70,107=22,108=21,109=26,110=52," \
b"111=45,112=33,113=67,114=41,115=44,116=48,117=53,118=54," \
b"119=51,120=75,121=44,122=57,123=44,124=66,125=56,126=52," \
b"127=81,128=108,129=70,130=50,131=51,132=53,133=45,134=62," \
b"135=12,136=13,137=7,138=15,139=21,140=11,141=20,142=6,143=7," \
b"144=11,145=6,146=16,147=19,148=1112,149=1,151=83,154=1," \
b"155=1,156=1,157=1,160=1,161=1,162=2,166=1,169=1,170=1,171=2," \
b"172=1,174=1,176=2,177=9,178=34,179=73,180=30,181=1,185=3," \
b"187=1,188=1,189=1,192=1,196=1,198=1,200=1,201=1,204=1,205=1," \
b"207=1,208=1,209=1,214=2,215=31,216=78,217=28,218=5,219=2," \
b"220=1,222=1,225=1,227=1,234=1,242=1,250=1,252=1,253=1," \
b">=256=203"
<|code_end|>
with the help of current file imports:
import datetime
import re
import time
import pytest
from string import ascii_letters
from aredis.exceptions import RedisClusterException, ResponseError, DataError, RedisError
from aredis.utils import b, iteritems, iterkeys, itervalues
from aredis.commands.server import parse_info
from tests.cluster.conftest import skip_if_server_version_lt, skip_if_redis_py_version_lt
and context from other files:
# Path: aredis/exceptions.py
# class RedisClusterException(Exception):
# pass
#
# class ResponseError(RedisError):
# pass
#
# class DataError(RedisError):
# pass
#
# class RedisError(Exception):
# pass
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def iteritems(x):
# return iter(x.items())
#
# def iterkeys(x):
# return iter(x.keys())
#
# def itervalues(x):
# return iter(x.values())
#
# Path: aredis/commands/server.py
# def parse_info(response):
# """Parses the result of Redis's INFO command into a Python dict"""
# info = {}
# response = nativestr(response)
#
# def get_value(value):
# if ',' not in value or '=' not in value:
# try:
# if '.' in value:
# return float(value)
# else:
# return int(value)
# except ValueError:
# return value
# else:
# sub_dict = {}
# for item in value.split(','):
# k, v = item.rsplit('=', 1)
# sub_dict[k] = get_value(v)
# return sub_dict
#
# for line in response.splitlines():
# if line and not line.startswith('#'):
# if line.find(':') != -1:
# key, value = line.split(':', 1)
# info[key] = get_value(value)
# else:
# # if the line isn't splittable, append it to the "__raw__" key
# info.setdefault('__raw__', []).append(line)
#
# return info
#
# Path: tests/cluster/conftest.py
# def skip_if_server_version_lt(min_version):
# """
# """
# versions = get_versions()
# for version in versions.values():
# if StrictVersion(version) < StrictVersion(min_version):
# return pytest.mark.skipif(True, reason="")
# return pytest.mark.skipif(False, reason="")
#
# def skip_if_redis_py_version_lt(min_version):
# """
# """
# import aredis
# version = aredis.__version__
# if StrictVersion(version) < StrictVersion(min_version):
# return pytest.mark.skipif(True, reason="")
# return pytest.mark.skipif(False, reason="")
, which may contain function names, class names, or code. Output only the next line. | parsed = parse_info(info) |
Next line prediction: <|code_start|>
@pytest.mark.asyncio
async def test_bitcount(self, r):
await r.flushdb()
await r.setbit('a', 5, True)
assert await r.bitcount('a') == 1
await r.setbit('a', 6, True)
assert await r.bitcount('a') == 2
await r.setbit('a', 5, False)
assert await r.bitcount('a') == 1
await r.setbit('a', 9, True)
await r.setbit('a', 17, True)
await r.setbit('a', 25, True)
await r.setbit('a', 33, True)
assert await r.bitcount('a') == 5
assert await r.bitcount('a', 0, -1) == 5
assert await r.bitcount('a', 2, 3) == 2
assert await r.bitcount('a', 2, -1) == 3
assert await r.bitcount('a', -2, -1) == 2
assert await r.bitcount('a', 1, 1) == 1
@pytest.mark.asyncio
async def test_bitop_not_supported(self, r):
await r.flushdb()
await r.set('a', '')
with pytest.raises(RedisClusterException):
await r.bitop('not', 'r', 'a')
@pytest.mark.asyncio
@skip_if_server_version_lt('2.8.7')
<|code_end|>
. Use current file imports:
(import datetime
import re
import time
import pytest
from string import ascii_letters
from aredis.exceptions import RedisClusterException, ResponseError, DataError, RedisError
from aredis.utils import b, iteritems, iterkeys, itervalues
from aredis.commands.server import parse_info
from tests.cluster.conftest import skip_if_server_version_lt, skip_if_redis_py_version_lt)
and context including class names, function names, or small code snippets from other files:
# Path: aredis/exceptions.py
# class RedisClusterException(Exception):
# pass
#
# class ResponseError(RedisError):
# pass
#
# class DataError(RedisError):
# pass
#
# class RedisError(Exception):
# pass
#
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def iteritems(x):
# return iter(x.items())
#
# def iterkeys(x):
# return iter(x.keys())
#
# def itervalues(x):
# return iter(x.values())
#
# Path: aredis/commands/server.py
# def parse_info(response):
# """Parses the result of Redis's INFO command into a Python dict"""
# info = {}
# response = nativestr(response)
#
# def get_value(value):
# if ',' not in value or '=' not in value:
# try:
# if '.' in value:
# return float(value)
# else:
# return int(value)
# except ValueError:
# return value
# else:
# sub_dict = {}
# for item in value.split(','):
# k, v = item.rsplit('=', 1)
# sub_dict[k] = get_value(v)
# return sub_dict
#
# for line in response.splitlines():
# if line and not line.startswith('#'):
# if line.find(':') != -1:
# key, value = line.split(':', 1)
# info[key] = get_value(value)
# else:
# # if the line isn't splittable, append it to the "__raw__" key
# info.setdefault('__raw__', []).append(line)
#
# return info
#
# Path: tests/cluster/conftest.py
# def skip_if_server_version_lt(min_version):
# """
# """
# versions = get_versions()
# for version in versions.values():
# if StrictVersion(version) < StrictVersion(min_version):
# return pytest.mark.skipif(True, reason="")
# return pytest.mark.skipif(False, reason="")
#
# def skip_if_redis_py_version_lt(min_version):
# """
# """
# import aredis
# version = aredis.__version__
# if StrictVersion(version) < StrictVersion(min_version):
# return pytest.mark.skipif(True, reason="")
# return pytest.mark.skipif(False, reason="")
. Output only the next line. | @skip_if_redis_py_version_lt("2.10.2") |
Given the code snippet: <|code_start|>
class ConnectionCommandMixin:
RESPONSE_CALLBACKS = {
'AUTH': bool,
'PING': lambda r: nativestr(r) == 'PONG',
'SELECT': bool_ok,
}
async def echo(self, value):
"Echo the string back from the server"
return await self.execute_command('ECHO', value)
async def ping(self):
"Ping the Redis server"
return await self.execute_command('PING')
class ClusterConnectionCommandMixin(ConnectionCommandMixin):
NODES_FLAGS = {
<|code_end|>
, generate the next line using the imports in this file:
from aredis.utils import (NodeFlag,
bool_ok,
nativestr)
and context (functions, classes, or occasionally code) from other files:
# Path: aredis/utils.py
# class NodeFlag:
# BLOCKED = 'blocked'
# ALL_NODES = 'all-nodes'
# ALL_MASTERS = 'all-masters'
# RANDOM = 'random'
# SLOT_ID = 'slot-id'
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
. Output only the next line. | 'PING': NodeFlag.ALL_NODES, |
Given the code snippet: <|code_start|>
class ConnectionCommandMixin:
RESPONSE_CALLBACKS = {
'AUTH': bool,
'PING': lambda r: nativestr(r) == 'PONG',
<|code_end|>
, generate the next line using the imports in this file:
from aredis.utils import (NodeFlag,
bool_ok,
nativestr)
and context (functions, classes, or occasionally code) from other files:
# Path: aredis/utils.py
# class NodeFlag:
# BLOCKED = 'blocked'
# ALL_NODES = 'all-nodes'
# ALL_MASTERS = 'all-masters'
# RANDOM = 'random'
# SLOT_ID = 'slot-id'
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
. Output only the next line. | 'SELECT': bool_ok, |
Given snippet: <|code_start|>
class ConnectionCommandMixin:
RESPONSE_CALLBACKS = {
'AUTH': bool,
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from aredis.utils import (NodeFlag,
bool_ok,
nativestr)
and context:
# Path: aredis/utils.py
# class NodeFlag:
# BLOCKED = 'blocked'
# ALL_NODES = 'all-nodes'
# ALL_MASTERS = 'all-masters'
# RANDOM = 'random'
# SLOT_ID = 'slot-id'
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
which might include code, classes, or functions. Output only the next line. | 'PING': lambda r: nativestr(r) == 'PONG', |
Next line prediction: <|code_start|>
:start: and :num:
are for paging through the sorted data
:by:
allows using an external key to weight and sort the items.
Use an "*" to indicate where in the key the item value is located
:get:
is for returning items from external keys rather than the
sorted data itself. Use an "*" to indicate where int he key
the item value is located
:desc:
is for reversing the sort
:alpha:
is for sorting lexicographically rather than numerically
:store:
is for storing the result of the sort into the key `store`
ClusterImpl:
A full implementation of the server side sort mechanics because many of the
options work on multiple keys that can exist on multiple servers.
"""
if (start is None and num is not None) or \
(start is not None and num is None):
raise RedisError("RedisError: ``start`` and ``num`` must both be specified")
try:
<|code_end|>
. Use current file imports:
(from aredis.utils import (b, dict_merge,
bool_ok, nativestr,
string_keys_to_dict)
from aredis.exceptions import (DataError,
RedisClusterException,
RedisError))
and context including class names, function names, or small code snippets from other files:
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
#
# Path: aredis/exceptions.py
# class DataError(RedisError):
# pass
#
# class RedisClusterException(Exception):
# pass
#
# class RedisError(Exception):
# pass
. Output only the next line. | data_type = b(await self.type(name)) |
Given snippet: <|code_start|>
class ListsCommandMixin:
RESPONSE_CALLBACKS = dict_merge(
string_keys_to_dict(
'BLPOP BRPOP',
lambda r: r and tuple(r) or None
),
string_keys_to_dict(
# these return OK, or int if redis-server is >=1.3.4
'LPUSH RPUSH',
lambda r: isinstance(r, int) and r or nativestr(r) == 'OK'
),
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from aredis.utils import (b, dict_merge,
bool_ok, nativestr,
string_keys_to_dict)
from aredis.exceptions import (DataError,
RedisClusterException,
RedisError)
and context:
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
#
# Path: aredis/exceptions.py
# class DataError(RedisError):
# pass
#
# class RedisClusterException(Exception):
# pass
#
# class RedisError(Exception):
# pass
which might include code, classes, or functions. Output only the next line. | string_keys_to_dict('LSET LTRIM', bool_ok), |
Continue the code snippet: <|code_start|>
class ListsCommandMixin:
RESPONSE_CALLBACKS = dict_merge(
string_keys_to_dict(
'BLPOP BRPOP',
lambda r: r and tuple(r) or None
),
string_keys_to_dict(
# these return OK, or int if redis-server is >=1.3.4
'LPUSH RPUSH',
<|code_end|>
. Use current file imports:
from aredis.utils import (b, dict_merge,
bool_ok, nativestr,
string_keys_to_dict)
from aredis.exceptions import (DataError,
RedisClusterException,
RedisError)
and context (classes, functions, or code) from other files:
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
#
# Path: aredis/exceptions.py
# class DataError(RedisError):
# pass
#
# class RedisClusterException(Exception):
# pass
#
# class RedisError(Exception):
# pass
. Output only the next line. | lambda r: isinstance(r, int) and r or nativestr(r) == 'OK' |
Given the following code snippet before the placeholder: <|code_start|> if by is not None:
# _sort_using_by_arg mutates data so we don't
# need need a return value.
data = await self._sort_using_by_arg(data, by, alpha)
elif not alpha:
data.sort(key=self._strtod_key_func)
else:
data.sort()
if desc:
data = data[::-1]
if not (start is None and num is None):
data = data[start:start + num]
if get:
data = await self._retrive_data_from_sort(data, get)
if store is not None:
if data_type == b("set"):
await self.delete(store)
await self.rpush(store, *data)
elif data_type == b("list"):
await self.delete(store)
await self.rpush(store, *data)
else:
raise RedisClusterException("Unable to store sorted data for data type : {0}".format(data_type))
return len(data)
if groups:
if not get or isinstance(get, str) or len(get) < 2:
<|code_end|>
, predict the next line using imports from the current file:
from aredis.utils import (b, dict_merge,
bool_ok, nativestr,
string_keys_to_dict)
from aredis.exceptions import (DataError,
RedisClusterException,
RedisError)
and context including class names, function names, and sometimes code from other files:
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
#
# Path: aredis/exceptions.py
# class DataError(RedisError):
# pass
#
# class RedisClusterException(Exception):
# pass
#
# class RedisError(Exception):
# pass
. Output only the next line. | raise DataError('when using "groups" the "get" argument ' |
Predict the next line for this snippet: <|code_start|> is for returning items from external keys rather than the
sorted data itself. Use an "*" to indicate where int he key
the item value is located
:desc:
is for reversing the sort
:alpha:
is for sorting lexicographically rather than numerically
:store:
is for storing the result of the sort into the key `store`
ClusterImpl:
A full implementation of the server side sort mechanics because many of the
options work on multiple keys that can exist on multiple servers.
"""
if (start is None and num is not None) or \
(start is not None and num is None):
raise RedisError("RedisError: ``start`` and ``num`` must both be specified")
try:
data_type = b(await self.type(name))
if data_type == b("none"):
return []
elif data_type == b("set"):
data = list(await self.smembers(name))[:]
elif data_type == b("list"):
data = await self.lrange(name, 0, -1)
else:
<|code_end|>
with the help of current file imports:
from aredis.utils import (b, dict_merge,
bool_ok, nativestr,
string_keys_to_dict)
from aredis.exceptions import (DataError,
RedisClusterException,
RedisError)
and context from other files:
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
#
# Path: aredis/exceptions.py
# class DataError(RedisError):
# pass
#
# class RedisClusterException(Exception):
# pass
#
# class RedisError(Exception):
# pass
, which may contain function names, class names, or code. Output only the next line. | raise RedisClusterException("Unable to sort data type : {0}".format(data_type)) |
Here is a snippet: <|code_start|> async def sort(self, name, start=None, num=None, by=None, get=None, desc=False, alpha=False, store=None, groups=None):
"""Sorts and returns a list, set or sorted set at ``name``.
:start: and :num:
are for paging through the sorted data
:by:
allows using an external key to weight and sort the items.
Use an "*" to indicate where in the key the item value is located
:get:
is for returning items from external keys rather than the
sorted data itself. Use an "*" to indicate where int he key
the item value is located
:desc:
is for reversing the sort
:alpha:
is for sorting lexicographically rather than numerically
:store:
is for storing the result of the sort into the key `store`
ClusterImpl:
A full implementation of the server side sort mechanics because many of the
options work on multiple keys that can exist on multiple servers.
"""
if (start is None and num is not None) or \
(start is not None and num is None):
<|code_end|>
. Write the next line using the current file imports:
from aredis.utils import (b, dict_merge,
bool_ok, nativestr,
string_keys_to_dict)
from aredis.exceptions import (DataError,
RedisClusterException,
RedisError)
and context from other files:
# Path: aredis/utils.py
# def b(x):
# return x.encode('latin-1') if not isinstance(x, bytes) else x
#
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# def string_keys_to_dict(key_string, callback):
# return dict.fromkeys(key_string.split(), callback)
#
# Path: aredis/exceptions.py
# class DataError(RedisError):
# pass
#
# class RedisClusterException(Exception):
# pass
#
# class RedisError(Exception):
# pass
, which may include functions, classes, or code. Output only the next line. | raise RedisError("RedisError: ``start`` and ``num`` must both be specified") |
Here is a snippet: <|code_start|> Check if a script exists in the script cache by specifying the SHAs of
each script as ``args``. Returns a list of boolean values indicating if
if each already script exists in the cache.
"""
return await self.execute_command('SCRIPT EXISTS', *args)
async def script_flush(self):
"""Flushes all scripts from the script cache"""
return await self.execute_command('SCRIPT FLUSH')
async def script_kill(self):
"""Kills the currently executing Lua script"""
return await self.execute_command('SCRIPT KILL')
async def script_load(self, script):
"""Loads a Lua ``script`` into the script cache. Returns the SHA."""
return await self.execute_command('SCRIPT LOAD', script)
def register_script(self, script):
"""
Registers a Lua ``script`` specifying the ``keys`` it will touch.
Returns a Script object that is callable and hides the complexity of
dealing with scripts, keys, and shas. This is the preferred way of
working with Lua scripts.
"""
return Script(self, script)
class ClusterScriptingCommandMixin(ScriptingCommandMixin):
<|code_end|>
. Write the next line using the current file imports:
from aredis.utils import (dict_merge, nativestr,
list_keys_to_dict,
NodeFlag, bool_ok)
from aredis.scripting import Script
and context from other files:
# Path: aredis/utils.py
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# def list_keys_to_dict(key_list, callback):
# return dict.fromkeys(key_list, callback)
#
# class NodeFlag:
# BLOCKED = 'blocked'
# ALL_NODES = 'all-nodes'
# ALL_MASTERS = 'all-masters'
# RANDOM = 'random'
# SLOT_ID = 'slot-id'
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
, which may include functions, classes, or code. Output only the next line. | NODES_FLAGS = dict_merge( |
Given snippet: <|code_start|>
class ScriptingCommandMixin:
RESPONSE_CALLBACKS = {
'SCRIPT EXISTS': lambda r: list(map(bool, r)),
'SCRIPT FLUSH': bool_ok,
'SCRIPT KILL': bool_ok,
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from aredis.utils import (dict_merge, nativestr,
list_keys_to_dict,
NodeFlag, bool_ok)
from aredis.scripting import Script
and context:
# Path: aredis/utils.py
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# def list_keys_to_dict(key_list, callback):
# return dict.fromkeys(key_list, callback)
#
# class NodeFlag:
# BLOCKED = 'blocked'
# ALL_NODES = 'all-nodes'
# ALL_MASTERS = 'all-masters'
# RANDOM = 'random'
# SLOT_ID = 'slot-id'
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
which might include code, classes, or functions. Output only the next line. | 'SCRIPT LOAD': nativestr, |
Given snippet: <|code_start|> return await self.execute_command('SCRIPT EXISTS', *args)
async def script_flush(self):
"""Flushes all scripts from the script cache"""
return await self.execute_command('SCRIPT FLUSH')
async def script_kill(self):
"""Kills the currently executing Lua script"""
return await self.execute_command('SCRIPT KILL')
async def script_load(self, script):
"""Loads a Lua ``script`` into the script cache. Returns the SHA."""
return await self.execute_command('SCRIPT LOAD', script)
def register_script(self, script):
"""
Registers a Lua ``script`` specifying the ``keys`` it will touch.
Returns a Script object that is callable and hides the complexity of
dealing with scripts, keys, and shas. This is the preferred way of
working with Lua scripts.
"""
return Script(self, script)
class ClusterScriptingCommandMixin(ScriptingCommandMixin):
NODES_FLAGS = dict_merge(
{
'SCRIPT KILL': NodeFlag.BLOCKED
},
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from aredis.utils import (dict_merge, nativestr,
list_keys_to_dict,
NodeFlag, bool_ok)
from aredis.scripting import Script
and context:
# Path: aredis/utils.py
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# def list_keys_to_dict(key_list, callback):
# return dict.fromkeys(key_list, callback)
#
# class NodeFlag:
# BLOCKED = 'blocked'
# ALL_NODES = 'all-nodes'
# ALL_MASTERS = 'all-masters'
# RANDOM = 'random'
# SLOT_ID = 'slot-id'
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
which might include code, classes, or functions. Output only the next line. | list_keys_to_dict( |
Continue the code snippet: <|code_start|> if each already script exists in the cache.
"""
return await self.execute_command('SCRIPT EXISTS', *args)
async def script_flush(self):
"""Flushes all scripts from the script cache"""
return await self.execute_command('SCRIPT FLUSH')
async def script_kill(self):
"""Kills the currently executing Lua script"""
return await self.execute_command('SCRIPT KILL')
async def script_load(self, script):
"""Loads a Lua ``script`` into the script cache. Returns the SHA."""
return await self.execute_command('SCRIPT LOAD', script)
def register_script(self, script):
"""
Registers a Lua ``script`` specifying the ``keys`` it will touch.
Returns a Script object that is callable and hides the complexity of
dealing with scripts, keys, and shas. This is the preferred way of
working with Lua scripts.
"""
return Script(self, script)
class ClusterScriptingCommandMixin(ScriptingCommandMixin):
NODES_FLAGS = dict_merge(
{
<|code_end|>
. Use current file imports:
from aredis.utils import (dict_merge, nativestr,
list_keys_to_dict,
NodeFlag, bool_ok)
from aredis.scripting import Script
and context (classes, functions, or code) from other files:
# Path: aredis/utils.py
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# def list_keys_to_dict(key_list, callback):
# return dict.fromkeys(key_list, callback)
#
# class NodeFlag:
# BLOCKED = 'blocked'
# ALL_NODES = 'all-nodes'
# ALL_MASTERS = 'all-masters'
# RANDOM = 'random'
# SLOT_ID = 'slot-id'
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
. Output only the next line. | 'SCRIPT KILL': NodeFlag.BLOCKED |
Here is a snippet: <|code_start|>
class ScriptingCommandMixin:
RESPONSE_CALLBACKS = {
'SCRIPT EXISTS': lambda r: list(map(bool, r)),
<|code_end|>
. Write the next line using the current file imports:
from aredis.utils import (dict_merge, nativestr,
list_keys_to_dict,
NodeFlag, bool_ok)
from aredis.scripting import Script
and context from other files:
# Path: aredis/utils.py
# def dict_merge(*dicts):
# merged = {}
# for d in dicts:
# merged.update(d)
# return merged
#
# def nativestr(x):
# return x if isinstance(x, str) else x.decode('utf-8', 'replace')
#
# def list_keys_to_dict(key_list, callback):
# return dict.fromkeys(key_list, callback)
#
# class NodeFlag:
# BLOCKED = 'blocked'
# ALL_NODES = 'all-nodes'
# ALL_MASTERS = 'all-masters'
# RANDOM = 'random'
# SLOT_ID = 'slot-id'
#
# def bool_ok(response):
# return nativestr(response) == 'OK'
, which may include functions, classes, or code. Output only the next line. | 'SCRIPT FLUSH': bool_ok, |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.